JavaClass Lecture2
JavaClass Lecture2
Lecture 2
Expressions are like C
• Assignment statements mostly look like those in C; you
can use =, +=, *= etc.
• Arithmetic uses the familiar + - * / %
• Java also has ++ and --
• Java has boolean operators && || !
• Java has comparisons < <= == != >= >
• Java does not have pointers or pointer arithmetic
a = a + b; a += b; a = a + 1; a++;
a = a - b; a -= b; a = a - 1; a--;
a = a * b; a *= b;
a = a / b; a /= b;
a = a % b; a %= b;
'A' "A"
123 "123"
-1 "-1"
.1 "0.1"
3.14 "3.14"
Math.PI "3.141592653589793"
• The same rules apply to System.out.print(x)
15 March 2007 Java : Lecture 2 21
Type Casting
Which of the following are legal?
• int x = 3.5;
Illegal: 3.5 is not an int
• float x = 3;
Legal: 3 is an int, which is also a float
• long i = 3;
Legal: 3 is an int, which is also a long
• byte x = 155;
Illlegal: 155 is to big to be a byte (> 127)
• double d = 3.14159F;
Legal: 3.14159F is a float, which is also a double
15 March 2007 Java : Lecture 2 22
What is “Type Casting”?
• Type casting: automatic conversion of
values from one type to another
e.g. int → double
float → double
int → long
• Type casts can be:
– Implicit: performed automatically
– Explicit: programmed by developer