By Jack G. Zheng, CIS@Georgia State University
Last updated 8/16/2006
This lecture assumes you have basic programming language experience with
C/C++, C#. For those who have taken C# course, here is a good
syntax
comparison of C# and Java (J2SE 5.0). You can also download
examples in a ZIP file.
Java is a strong type language; everything belongs to a type.
Keyword |
Description |
Size (value range) |
(integers)
|
||
byte |
Byte-length integer |
8-bit (-128 to 127) |
short |
Short integer |
16-bit (-32768 to 32767) |
int |
Integer |
32-bit (-2^32/2 to 2^32/2-1) - about 2
billion |
long |
Long integer |
64-bit (…) |
(real numbers)
|
||
float |
Single-precision floating point |
32-bit |
double |
Double-precision floating point |
64-bit |
(other types)
|
||
char |
A single character |
16-bit Unicode character: 'a', '?' |
boolean |
A boolean value |
true, false |
Note: String is reference type
public static void main(String[] args)
{
// integer
int int1; //declaration
int1=1; //assignment
long long1=2;
System.out.println("int1: "+int1);
System.out.println("long1: "+long1);
// decimal
double d1=1.0;
double d2=1; //integers can be assigned to a decimal type variable
System.out.println("d1: "+d1);
System.out.println("d2: "+d2);
// char data type
char c1='A';
char c2=65; //ASCII code value can be used
System.out.println("c1: "+c1);
System.out.println("c2: "+c2);
// boolean
boolean b1=true;
boolean b2=false;
System.out.println("b1: "+b1);
System.out.println("b2: "+b2);
//String
String s1="hello";
System.out.println("s1: "+s1);
//constants, using the keyword "final"
final double PI=3.1415926; // trying to assign another value later will generate a compiler error
System.out.println("PI: "+PI);
}
increment/decrement expr++ expr-- unary operators ! multiplicative * / % additive + - relational < > <= >= equality == != logical AND && logical OR || assignment = += -= *= /= %=For complete precedence table, see http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html
income=41000;
// use "if ... else if"
if (income >= 50000)taxRate=0.4; // note: curly braces are optional for a single statement
else if (income >= 40000)
taxRate=0.35;
else if (income >= 30000)
taxRate=0.3;
else if (income >= 20000)
taxRate=0.25;
else
taxRate=0.2;
System.out.println("Income: "+income+"\tTax rate: "+taxRate);
char k='C';
switch (k)
{
case 'A': System.out.println("1. "+k); break;
case 'B': System.out.println("2. "+k); break;
case 'C': System.out.println("3. "+k); break;
default: System.out.println("Default. "+k);
}
int i=0;
while (i<10)
{
System.out.print("*");
i=i+1;
}
int i=0;
do
{
System.out.print("*");
i=i+1;
} while (i<10);
for (initialization; termination/continuation; increment/decrement)
{ statement(s); }
int i;
for (i=0;i<10;i++)
{
System.out.print("*");
}
for (int i=0;i<10;i=i+2)
System.out.print( "*"); // note: curly braces are optional for a single statement }
int m, n;
for (m=1; m < 10; n ++) { ... }
int i=0;
while (i<10)
{
System.out.println("endless");
}