LEC 02 Java Basics
COMP2021: Object-Oriented Programming
Java Basics
Dr. Max Yu PEI
Learning Objectives
❖ After the lecture, students should be able to
➢ understand the need for names and data types in
programming languages;
➢ understand how values of different basic types are stored
in Java programs;
➢ convert between decimal and binary numbers;
➢ master the operations on data of basic data types;
➢ understand how control structures influence the execution
of programs; and
➢ use control structures to construct programs.
2
Identifiers, Names, and Basic Data
Types
3
Variable Declaration
❖ Identifier
➢ A sequence of characters that consist of letters, digits,
underscores (_), and dollar signs ($)
▪ Start with a letter, an underscore (_), or a dollar sign ($)
▪ Cannot be a reserved word
▪ Can be of any length
❖ Names
➢ Variables and method names: camelCase
➢ Class names: capitalized camelCase
➢ Constants: all in upper case and connected using underscores
class BoardGame {…}
4
double sideLength = 10;
final double MINIMUM_HEALTH = 0;
10101101 11101101 10100101 11011010
01101010 01001100 00000110 11010011
01011001 01010100 00001111 11001100
00100111 01111100 01000110 01010010
11100101 01101111 11010101 00011100
01100011 10000001 01101100 00001100
10100010 11110101 00101110 10100000
01110001 10111000 11101000 11001001
01110011 11111001 10001100 01101001
00000101 11001100 11000100 01110111
5
x
byte: 89
char: ‘奔’
short: 22868
int: 1498681292
long: 6436787136929482322
float: 3.73062899E15
double: 2.0721738140865223E122
Java Primitive Data Types
Type Contains Default Size Range
boolean true or false false 1 bit NA
char
Unicode character
(Unsigned integer)
\u0000 16 bits \u0000 to \uFFFF
byte Signed integer 0 8 bits -128 to 127
short Signed integer 0 16 bits -32768 to 32767
int Signed integer 0 32 bits -2147483648 to 2147483647
long Signed integer 0 64 bits
-9223372036854775808 to
9223372036854775807
float floating point 0.0 32 bits ±1.4E-45 to ±3.4028235E+38
double floating point 0.0 64 bits
±4.9E-324 to
±1.7976931348623157E+308
6
Integer values Real values
Number Systems
7
Integer Types
❖ Integer types
➢ byte/char/short/int/long
➢ signed/unsigned
➢ Unsigned: only positive values
▪ All bits expressing the magnitude
➢ Signed: positive or negative values
▪ Signed Magnitude: Left bit (Most-Significant Bit, MSB) as the sign
bit, the rest bits to express the magnitude
▪ Two’s complement: 2n – N for negative values, where n is the
number of bits and N is the magnitude
8
Integer Values
❖ Benefits of Two’s complement
➢ One representation of zero
➢ Subtraction by Addition
9
6 -6 0 -0
4 bits
Signed magnitude 0110 1110 0000 1000
Two’s Complement 0110 1010 0000 0000
8 bits
Signed magnitude 0000 0110 1000 0110 0000 0000 1000 0000
Two’s Complement 0000 0110 1111 1010 0000 0000 0000 0000
x – y
= x – y + 2n (n bit encoding)
= x + (2n – y)
= x + (-y)
Conversion between Integer Types
❖ Between signed and unsigned
➢ Preserve the bit pattern, use different interpretations
❖ Widening
➢ Sign-extend
❖ Narrowing
➢ Discard the high order bits
10
0110signed = 610 <=> 0110unsigned = 610
1010signed = -610 <=> 1010unsigned = 1010
0110signed = 610 => 00000110signed = 610
1010signed = -610 => 11111010signed = -610
00001010signed = 1010 => 1010signed = -610
11110010signed = -1410 => 0010signed = 210
First make the size (i.e., the number of bits) match through widening or narrowing.
Then change the interpretation when necessary.
Floating-Point Types
❖ Floating-point types
➢ float and double
❖ Scientific notation
❖ IEEE standards for floating-point representation
11
+1010001.1101 <-6 +26 x 1.01000111001
-111.000011 <-2 -22 x 1.11000011
+0.00000111001 6-> +2-6 x 1.11001
-0.001110011 3-> -2-3 x 1.110011
Magnitude = 2Exponent * 1.Mantissa
1 8 23
1 11 52
Sign
float
double
Exponent
Excess 127
Mantissa
Sign Exponent
Excess 1023
Mantissa
Sign Exponent MantissaImplicit bit
Range vs. Precision
❖ 8 bits
➢ Integer:
▪ Two’s complement
➢ Floating point
▪ Sign: 1 bit; Exponent: 6 bits (excess 25-1); Mantissa: 1 bit
12
10000000
…
11111111
00000000
00000001
…
01111111
-27
…
-1
0
1
…
27-1
1
0
0
1
000000
…
011111
…
111111
-128 ~ 127Range
-31 ~ 32 1,1.5
-1.5*232 ~ +1.5*232
+/-
… -2, -1, 0, 1,
2, …
Integer
Values
…, -1, 0, 1, 2, 3, 4, 6, 8,
12, 16, 24, …
Integer to floating point: Nearest value
Floating point to integer: Round towards zero
(-1.2: -1; 1.2: 1)
Reading from the Keyboard
❖ In coursework
❖ In practice
➢ Do not use Scanner together with System.in;
➢ Always first read the input as a string, then parse the string.
13
Scanner input = new Scanner(System.in);
int value = input.nextInt();
Method Description
nextByte() Reads an integer of the byte type
nextShort() Reads an integer of the short type
nextInt() Reads an integer of the int type
nextLong() Reads an integer of the long type
nextFloat() Reads a number of the float type
nextDouble() Reads a number of the double type
23
String str = input.nextLine();
Numeric Operators
14
Name Meaning Example Result Side-effect
+ Addition 34 + 1 35 None
– Subtraction 34.5 – 2 32.5 None
* Multiplication 30 * 4 120 None
/ Division 7 / 2 3 None
/ Division 1.0 / 4.0 0.25 None
% Remainder 20 % 3 2 None
% Remainder 4.25 % 2.0 0.25 None
(int)(x / y) * y + (x % y) == x for any two values x and y (y != 0)
7.0 / 2 = 7.0 % 2 = -7.0 / 2 = -7.0 % 2 =
7 / 3 = 7 % 3 = -7 / 3 = -7 % 3 =
Which Day Is It?
❖ We know that the first day of 2019, i.e., Jan. 1st, 2019, is a
Tuesday. Given an integer x (1 <= x <= 365), what day is the x-
th day of 2019? (1 for Monday, 2 for Tuesday, …, and 0 for
Sunday)
➢ Example:
▪ Input: 1; Output: 2
▪ Input: 2; Output: 3
▪ Input: 3; Output: 4
▪ Input: 4; Output: 5
▪ …
▪ Input: 8; Output: 2
15
More Operators
Operator Name Example Result Side-effect
+= Addition assignment i += 8 9 i is 9
-= Subtraction assignment i -= 8 -7 i is -7
*= Multiplication assignment i *= 8 8 i is 8
/= Division assignment i /= 8 0 i is 0
%= Remainder assignment i %= 8 1 i is 1
++var Preincrement ++i 2 i is 2
var++ Postincrement i++ 1 i is 2
--var Predecrement --i 0 i is 0
var-- Postdecrement i-- 1 i is 0
16
❖ Assuming i has value 1
i = ++j;
i is
j is
i = j++; i = (j += 2);
int i = 3, j = 3; // what are i and j’s values afterwards ?
i is
j is
i is
j is
var op= expr; var = var op (expr);
i += j + 1;
i is
j is
Side-effect: modifications to the state (i.e.,
the memory) of the program.
Assignment Expressions and Assignment Statements
❖ Prior to Java 2, all the expressions can be used as statements.
❖ Since Java 2, only the following types of expressions can be
statements:
17
variable = expression;
variable op= expression;
++variable;
variable++;
--variable;
variable--;
Numeric Type Conversion
❖ Consider the following statements:
❖ When performing a binary operation involving two operands of
different types, convert the operands:
➢ If one of the operands is double, the other is converted into
double.
➢ Otherwise, if one of the operands is float, the other is converted
into float.
➢ Otherwise, if one of the operands is long, the other is converted
into long.
➢ Otherwise, both operands are converted into int.
18
byte i = 100;
long k = i * 3 + 4; // 3.1 is of type double. To
double d = i * 3.1 + k / 2; // get a float, use 3.1f.
Numeric Type Conversion (Cont’d)
❖ Implicit
❖ Explicit (casting)
❖ Attention
➢ Precision vs. Range
19
double d = 3; // type widening
int i = (int)3.5; // type narrowing
int i = 5 / 2.0; // error!
byte, short, int, long, float, double
rangesmaller larger
int x = 1234567890;
float y = x;
int z = (int) y;
// z is 1234567936
➢ Augmented assignment
short x = 2;
x = x + 1.1;
x += 1.1;
// x = (short)(x + 1.1)
// error!
// OK!
Common Errors
❖ Integer Overflow
❖ Round-off Errors
❖ Unintended Integer Division
20
int value = 2147483647 + 1;
float f = 0.1f;
System.out.println(1.0 - f);
int x = 1, y = 2;
double z = (x + y) / 2;
System.out.println(z);
// value will be -2147483648
// will print 0.8999999985098839
// will print 1.0
long longValue = 2147483649L; // Error: 2147483649
The boolean Type and Operators
❖ Use a boolean value to denote true or false
❖ Suppose we have
21
boolean b = (1 > 2);
Name Meaning Example Result Side-effect
< Less than radius < 0 false None <= Less than or equal to radius <= 0 false None > Greater than radius > 0 true None
>= Greater than or equal to radius >= 0 true None
== Equal to radius == 0 false None
!= Not equal to radius != 0 true None
int radius = 1;
Logical Operators
Name Meaning Example Result Side-effect
! Not !true false None
!false true None
&& And true && true true None
true && false false None
false && true false None
false && false false None
|| Or true || true true None
true || false true None
false || true true None
false || false false None
^ Exclusive or true ^ true false None
true ^ false true None
false ^ true true None
false ^ false false None
22
Short Circuit Logical Operators
❖ Short circuit evaluation
➢ If the value of the left operand is enough to decide the
result of the logical operator, the right operand will not be
evaluated
➢ &&, ||
23
int x = 1, y = 2;
boolean b = x < 0 && y++ > 2;
System.out.println(x + “,” + y);
Bitwise and Bit Shift Operators
❖ Perform bitwise and bit shift operations on integral types
24
Name Meaning Example Result Side-effect
~ bitwise complement (byte)~b1 0B01011110 None
& Bitwise AND (byte)(b1 & b2) 0B00100000 None
| Bitwise OR (byte)(b1 | b2) 0B10100001 None
>> Signed right shift (byte)(b1 >> 2) 0B11101000 None
<< Signed left shift (byte)(b1 << 2) 0B10000100 None >>> Unsigned right shift (byte)(b1 >>> 2) 0B00101000 None
byte b1 = (byte)0B10100001, b2 = (byte)0B00100000;
System.out.println(Integer.toBinaryString((byte)~b1));
What if “(byte)” is removed from the output statement?
Eager Logical Operators
❖ Eager evaluation
➢ Both operands are always evaluated first, then the result of
the operator is computed
➢ &, |
25
int x = 1, y = 2;
boolean b = x < 0 & y++ > 2;
System.out.println(x + “,” + y);
Conditional Expressions
❖ If boolean-expression evaluates to true, then the value
of the whole expression is that of exp1; otherwise, that of
exp2.
26
boolean-expression ? exp1 : exp2
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);
// is equivalent to the following
System.out.println(
(num % 2 == 0)? num + “is even” : num + “is odd”);
Operator Description Level Associativity
[]
.
()
++
—
access array element
access object member
invoke a method
post-increment
post-decrement
1 left to right
++
—
+
–
!
~
pre-increment
pre-decrement
unary plus
unary minus
logical NOT
bitwise NOT
2 right to left
()
new
cast
object creation
3 right to left
*
/
%
multiplicative 4 left to right
Java Operator Precedence Table
27
Java Operator Precedence Table (Cont’d)
28
Operator Description Level Associativity
+ –
+
additive
string concatenation
5 left to right
<< >>
>>>
shift 6 left to right
< <= > >=
instanceof
relational
type comparison
7 left to right
==
!=
equality 8 left to right
& bitwise AND 9 left to right
^ bitwise XOR 10 left to right
| bitwise OR 11 left to right
&& conditional AND 12 left to right
|| conditional OR 13 left to right
?: conditional 14 right to left
= += -= *= /= %=
&= ^= |= <<= >>=
>>>=
assignment 15 right to left
Evaluation Order
❖ Precedence
➢ When two different operators are adjacent, the operator with
the higher precedence gets evaluated first.
❖ Associativity (left to right, right to left)
➢ When two operators with the same precedence are adjacent, the
operators are evaluated according to their associativity.
❖ Operands are evaluated from left to right
29
1 + 2 * 3 is treated as 1 + (2 * 3)
1 * 2 + 3 is treated as (1 * 2) + 3
x = y = z = 7 is treated as x = (y = (z = 7))
x + y + z + 7 is treated as ((x + y) + z) + 7
int i = 1;
y = (i += 3) / (i == 1 ? 4 : 2);
How Are They Evaluated?
❖ Let
what are the values of a, b, and c after executing the
following statement?
❖ When in doubt, use parentheses!
30
a = b += c = a + 5;
int a = 1, b = 2, c = 3;
Control Structures
31
Control Structures
❖ Selection
➢ if
➢ switch
❖ Loop
➢ for
➢ while and do-while
❖ break and continue
32
if Statements
33
if(boolean-expression)
statement;
statement
boolean-expression
true
false
if(boolean-expression)
statement1;
else
statement2;
statement2
boolean-expression
false
statement1
true
Unlike in C, if conditions in Java must be of type boolean. Otherwise, you will get
a compilation error.
What Does It Print?
34
if(i > j)
if(i > k)
System.out.println(“A”);
else
System.out.println(“B”);
int i = 1, j = 2, k = 3;
if(i > j);
if(i > k)
System.out.println(“A”);
else
System.out.println(“B”);
Tips
35
if(condition1)
statement1;
else
if(condition2)
statement2;
else
if(condition3)
statement3;
else
statement4;
if(condition1)
statement1;
else if(condition2)
statement2;
else if(condition3)
statement3;
else
statement4;
is equivalent to
if(number % 2 == 0)
isEven = true;
else
isEven = false;
boolean isEven
= number % 2 == 0;
is equivalent to
if(even == true){
statement(s);
}
if(even){
statement(s);
}
is equivalent to
switch Statements
36
switch(expr){
case const1: statements1;
break;
case const1: statements2;
break;
case const1: statements3;
break;
default: statements4;
break;
}
o expr type must be char, byte, short, int, boolean, String, or enum;
• Not long, float, double;
o Constants must be of the same type as expr (and use no variable);
o default is optional;
• Does nothing if expr cannot match any constant and there is no default;
o breaks are optional;
• Without a break, execution falls through;
expr == const1
statements1 break
expr == const2
statements2 break
expr == const3
statements3 break
default
statements4 break
break Statement and Falling Through
❖ A break statement causes control to transfer to the end of the
switch
➢ If not present, the flow of control will continue into the next
case (fall through)
37
switch(n){
case 1:
System.out.println(“1”);
case 2:
System.out.println(“2”);
break;
case 3:
System.out.println(“3”);
}
n == 4
n == 3
n == 2
n == 1
while Statements
38
while(loop-condition)
// loop body
statement;
statement
loop-condition
true
false
do
// loop body
statement;
while(loop-condition)
statement
loop-condition
true
false
for Statements
39
for(initial-action;
loop-continuation-condition;
action-after-each-iteration)
// loop body
statement;
// enhanced for loop
for(element-type var: element-collection)
// loop body
statement;
statement
loop-continuation-condition
true
false
initial-action
action-after-each-iteration
int[] numbers = …;
for(int n: numbers){
System.out.println(n);
}
o Both initial-action and action-
after-each-iteration can be empty
o loop-continuation-condition must
be of type boolean
o If loop-continuation-condition is
missing, true is used by default
Which Loop to Use?
❖ while and for statements have equal expressive power
➢ You can write a loop in any of the two forms
➢ Examples
40
while(loop-condition){
// loop body
statements;
}
for(; loop-condition; ){
// loop body
statements;
}
for(initial-action;
loop-continuation-condition;
action-after-each-iteration){
// loop body
statements;
}
initial-action;
while(loop-continuation-condition){
// loop body
statements;
action-after-each-iteration;
}
break and continue
❖ A break statement causes control to transfer to the end of the
enclosing switch/for/while/do-while structure
❖ A continue statement causes control to transfer to the end of
the body of the enclosing for/while/do-while structure
41
for(int i = 0; i < 6; i++){ if(i == 3){ break; } System.out.println(i); } for(int i = 0; i < 6; i++){ if(i == 3){ continue; } System.out.println(i); } Summary ❖ Identifiers, names, and basic data types ➢ Type conversion and casting (range and precision) ➢ Short circuit and eager logical operators ➢ Evaluation order ❖ Control structures ➢ Condition expressions must be of type boolean ➢ break and continue 42 43 End