02_Java_Programming_lec2
02_Java_Programming_lec2
Computer Programming I
Java Programming Language
Lecture 2: Basic Elements of Java
illegal legal
me+u _myName
49ers TheCure
side-swipe ANSWER_IS_42
employee salary $bling$
Java Programming Language Slide 5
Keywords
Keywords (Reserved Words):
An identifier that you cannot use because it already has
a reserved meaning in Java.
abstract default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
continue goto package synchronized
Variables
A piece of the computer's memory that is given a name
and type, and can store a value that may be changed in
the program.
Steps for using a variable:
Declare it - state its name and type
Initialize it - store a value into it
Use it - print it or use it as part of an expression
int x; x 3
x = 3;
double yourGPA;
yourGPA 3.25
yourGPA = 1.0 + 2.25;
Java Programming Language Slide 8
Variables (continued)
Using variables: Once given a value, a variable can be used in
expressions:
int x;
x = 3;
System.out.println("x is " + x); x is 3
System.out.println(5 * x - 1); 14
You can assign a value more than once:
int x;
x = 3;
System.out.println(x + " here"); 3 here
x = 4 + 7;
System.out.println("now x is " + x); now x is 11
Java Programming Language Slide 9
Variables (continued)
int x;
System.out.println(x);
double vs float
The double type values are more accurate than the float
type values. For example:
– + addition 2+2=4
– - subtraction 53 – 18 = 35
– * multiplication 300 * 30 = 9000
– / division 4.8 / 2.0 = 2.4
– % remainder or mod 20 % 3 = 2
6
باقي
القسمة
3 ) 20
Java Programming Language Slide 16
Precedence
Precedence: Order in which operators are evaluated.
Generally operators evaluate left-to-right.
1 - 2 - 3 is (1 - 2) - 3 which is -4
But * / % have a higher level of precedence than + -
1 + 3 * 4 is 13
6 + 8 / 2 * 3
6 + 4 * 3
6 + 12 is 18
Parentheses can force a certain order of evaluation:
(1 + 3) * 4 is 16
x = 5; x = 5; y = 6; x = 5; x = 5; y = 5;
y = ++x; X = x +1; y = x++; y = x;
y = x; X = x +1;
"hello" + 42 is "hello42"
1 + "abc" + 2 is "1abc2"
"abc" + 1 + 2 is "abc12"
1 + 2 + "abc" is "3abc"
"abc" + 9 * 3 is "abc27"
"1" + 1 is "11"
4 - 1 + "abc" is "3abc"