Bài giảng Phát triển phần mềm phân tán - Bài 3: Java syntax basics (Tiếp theo) - Vũ Thị Hương Giang
21-Oct-16
Objectives
LESSON III.
Java syntax basics (cont.)
•
Develop knowledge about the syntax and
semantic of Java programming language
Vu Thi Huong Giang
SoICT (School of Information and
Communication Technology)
HUST (Hanoi University of Science
and Technology)
Content
•
•
•
•
•
Operators
Expression
Statement
Block
I. OPERATORS
Control flow statements
1. Classification
2. Assignment
3. Arithmetic and substitution
4. Increment and decrement
5. Relational and logic operator
6. Ternary and instance of operator
7. Shift operator
1. Operators classification
2. Assignment operator
•
Operators are special symbols that perform specific
operations on one, two, or three operands, and then return
a result.
•
This operator assigns the value of the expression
to the variable.
variable = expression;
•
•
Unary operators
–
Increment and decrement operators
–
The types of the variable and expression must be
compatible.
Binary operators
–
–
–
–
–
–
–
Assignment operator
Arithmetic operators
Substitution operators
Relational operators
Logical operators
–
The value of the whole assignment expression is the
value of the expression on the right possible to chain
assignment expressions:
Conditional operators
instanceOf operator
int x, y, z;
x = y = z = 2;
•
Ternary operators
Used to build value expressions.
5
1
21-Oct-16
3. Arithmetic and substitution
4. Increment and Decrement
•
•
Use only one operand
The increment operator (++) adds one to its
operand
Arithmetic operators
Substitution operators
•
•
•
•
•
•
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
•
Store the value of
right side to left side
–
2 statements count++; and count=count+1; are
functionally equivalent
–
–
–
–
Addition and
assignment (+=)
•
The decrement operator (--) subtracts one from
its operand
Subtraction and
assignment (-=)
Modulo (%)
Example:
Multiplication and
assignment (*=)
System.out.println(
" i % j = " +
(i % j));
Division and assignment
(/=)
7
8
6. Ternary and instanceOf operator
5. Relational and Logic operators
Relational operators
Logic operators
Ternary operator
instanceOf operator
•
•
•
Used to evaluate boolean
expressions
Decide which value should be
assigned to the variable
•
Judge if an object is a product
generated from a class
Syntax:
•
judge the equivalence or
bigness and smallness of
two expressions and
variables.
== (equal to)
<= (less than or equal to)
>= (greater than or equal
to)
!= (not equal to)
> (greater than)
< (less than)
•
•
•
•
&& (logical AND)
& (boolean logical AND)
|| (logical OR)
•
object instanceOf class
Example
String name
boolean result
Syntax:
•
•
•
•
conditional_expression
value_if_true
value_if_false;
Example:
10;
?
| (boolean logical
inclusive OR)
=
'James';
=
:
name instanceOf String;
// True, since name is type of
// String
•
•
•
^ (boolean logical
exclusive OR)
int
a =
•
•
•
boolean
true
//
b
:
=
(a == 1)
?
false;
! (logical NOT)
b = false, since a is
// not equal to
1
9
10
7. Shift operator
II. Expression
•
Program
• Task: compute values
• Feature:
Right shift (>>)
Left shift (<<)
–
Package
Class
– Methods/block
» Statement
Expression
Token
•
•
•
Shifts the value's bit
row to the right by a
specified bit.
•
•
•
Shifts the value's bit
row to the left by a
specified bit.
•
– Be made up of variables,
operators, and method
calls
– Be built according to the
•
Syntax: n >> p
Syntax: n << p
syntax of the language
•
–
Shifts the bits of n right
p positions
–
Shifts the bits of n left p
positions.
– Evaluate to a single value.
The data type of this
value depends on the
elements used in the
expression.
Example:
Example:
int
System.out.println(x>>1);
-2
x
=
-4;
int
System.out.println(x<<2);
12
x = 3;
if (value1 == value2) System.out.println("value1 == value2");
int result = 1 + 2 * 3; // result is now 7
11
2
21-Oct-16
Precedence and associativity of Java
operators
Operator order in expression
Operator
Description
Level Associativity
•
•
Java operators are assigned precedence order.
When two operators share an operand, the operator with the
higher precedence goes first.
[]
.
()
++, --
access array element
access object member
invoke a method
1
2
left to right
right to left
–
Example: since multiplication has a higher precedence than addition,
so:
post-increment, post-decrement
•
1 + 2 * 3 is treated as 1 + (2 * 3)
++, --
+, -
!
pre-increment, pre-decrement
unary plus, unary minus
logical NOT
•
1 * 2 + 3 is treated as (1 * 2) + 3
•
•
When two operators with the same precedence the expression
is evaluated according to its associativity.
~
bitwise NOT
–
Example:
()
new
cast
object creation
3
4
5
6
right to left
left to right
left to right
left to right
•
x = y = z = 17 is treated as x = (y = (z = 17)), since the assignment
operator has right-to-left associativity.
•
72 / 2 / 3 is treated as (72 / 2) / 3 since the division operator has left-to-
right associativity.
*, /, %
multiplicative
+ -
+
additive
string concatenation
Precedence rules can be overridden by explicit parentheses.
<<, >>, >>> shift
Precedence and associativity of Java
operators
III. Statement
Operator
Description
Level
Associativity
•
•
A statement forms a complete unit of execution.
Two kinds of statements
<, <=, >, >= relational
instanceof
7
left to right
type comparison
–
Expression statement or single statement
==, !=
equality
8
left to right
left to right
left to right
left to right
left to right
left to right
right to left
–
Control flow statement
&
bitwise AND
bitwise XOR
bitwise OR
9
^
|
10
11
12
13
14
&&
||
?:
conditional AND
conditional OR
conditional
=, +=, -=, *=
/=, %=, &=
^=, |=, <<=
>>=, >>>=
assignment
15
right to left
Expression statement
IV. Block
•
A block is a group of zero or more statements between balanced
braces
A block can be used anywhere a single statement is allowed
•
•
Syntax:
expression;
•
class BlockDemo
public static void main(String[] args)
boolean condition true;
if (condition) // begin block one
{
Expression can be
{
–
–
–
–
Assignment expressions
aValue = 8933.234;
=
{
Any use of increment (++) or decrement (--) operator
aValue++;
System.out.println("Condition is true.");
// end block one
}
else
{
// begin block
System.out.println("Condition is false.");
// end block
2
Method calls
System.out.println("Hello World!");
Object creation expressions
String[] array = new String[5];
}
2
}
}
3
21-Oct-16
V. Control flow statements
1. Selection statements
•
•
Coding a program means expressing the proposed
algorithm by writing Java statements into a source file
Without control flow, the interpreter would execute these
statements in the order they appear in the source file, left-
to-right and top-down
•
Java selection statements allow to control the
flow of program’s execution based upon
conditions known only during run-time.
•
Java provides four selection statements:
– if
•
•
Control flow statements regulate the order in which
statements get executed
Control statements are divided into three groups:
– if-else
– if-else-if
– switch
–
–
–
Selection statements: allow the program choosing different parts
of the execution based on the result of an expression
Iteration statements: enable the program execution to repeat one
or more statements
Jump statements enable your program to execute in a non-linear
fashion
The if statement
The if-else statement
•
Syntax:
if (condition) statement;
•
An else clause can be added to an if statement to
make an if-else statement
if (condition)
–
If conditionis evaluated to
true, execute statement,
otherwise do nothing.
statement1;
condition evaluated
condition evaluated
else
statement2;
–
The condition must be of type
boolean.
true
true
false
statement
statement1
statement2
•
The component statement
may be:
–
simple:
if (condition) statement;
compound:
if (condition) {statement;}
–
int max(int n1, int n2) {
if (n1 >= n2) { return n1; }
else { return n2; }
}
The if-else-if statement
Example
public class IfElseUsage
{
•
Syntax:
•
Semantics:
public static void main(String args[])
int month 12;
{
if (condition1) statement1
else if (condition2) statement2
…
–
statements are executed top-
down
=
String season;
if (month == 12 || month ==
–
as soon as one expressions is
true, its statement is
executed
1
|| month == 2)
else statement
season
else if(month ==
season
else if(month ==
season
else if(month ==
season
else season
System.out.println(
"December is in the
=
"Winter";
|| month ==
"Spring";
3
4
7
|| month == 5)
|| month == 8)
–
if none of the expressions is
true, the last statement is
executed
=
6
|| month ==
condition1 evaluated
false
=
"Summer";
9
|| month == 10 || month == 11)
"Autumn";
"Bogus Month";
true
=
statement1
condition2 evaluated
=
false
true
"
+ season + ".");
statement2
}
statement2
}
4
21-Oct-16
The switch statement
The switch statement
•
Semantic:
•
The general syntax of a switch
statement is:
•
The general syntax of a switch
statement is:
•
Assumptions:
–
Condition is evaluated; its value is
–
condition must be of type
byte, short, int or char
compared with each of the case
values
switch (condition) {
switch (condition) {
case value1: statement1; [break;]
–
–
–
–
If a match is found, the statement
following the case is executed
If no match is found, the statement
following default is executed
The break statement terminates the
enclosed iteration
Both default and break are optional.
–
each of the case values must
be a literal of the compatible
type
case value1: statement1; [break;]
case value2: statement2; [break;]
case value3: statement3; [break;]
…
case value2: statement2; [break;]
case value3: statement3; [break;]
–
case values must be unique
…
[default: statement;]
}
[default: statement;]
condition evaluated
condition1 evaluated
}
statement1
statement2
statement2
statement2
statement1
statement2
statement2
statement2
Example
Comparing switch and if
•
What is the result of this code?
• Two main differences:
–
switch can only test for equality, while if can evaluate
any kind of boolean expression
int month = 1;
switch(month){
case 1:
–
Java creates a “jump table” for switch expressions, so a
switch statement is usually more efficient than a set of
nested if statements
System.out.println("A Happy New Year!");
case 12:
System.out.println("Merry Christmas !");
break;
switch is a better alternative than if-else-if when
the execution follows several branches depending
on the value of an expression.
}
27
2. Iteration statements
The for Statement
•
Syntax:
•
Java iteration statements enable repeated
execution of part of a program until a certain
termination condition becomes true.
for ( initialization ; condition ; increment )
statement;
Semantic:
•
•
Java provides three iteration statements:
–
–
Execute the initialization
Evaluate the termination condition :
–
Iteration number is known in advance:
•
•
if false, terminate the iteration
otherwise, continue to the next step
for
–
Iteration number is not known in advance:
–
–
–
Execute the increment statement
Execute the statement component
control flow continues from the second step
•
Termination condition is checked before the execution:
while
•
Example:
•
Termination condition is checked after the execution:
for (int count=1; count <= 5; count++)
System.out.println (count);
do-while
30
5
21-Oct-16
The for each statement
While-do and do-while statement
public class Arithmetic
public static void main(String[] args)
{
for (variable
body;
}
: array) {
•
While-do statement
{
int data[]
=
{1, 80,22, 134, 0, 33,
93,45,33, 12};
while (condition) {
For each variable in an array, do the
body statements
int sum
float ave
for(int num
= 0; // Total value
body;
}
=
0;
:
condition
evaluated
statement1
data){
sum += num;
for (variable: collection)
body;
}
{
true
false
true
}
•
Do-while statement
do {
body;
ave
= sum/10.0f;
condition
evaluated
System.out.println(
"Total sum :"
statement1
For each variable in a collection, do the
body statements
+
sum);
System.out.println(
false
"Mean :"
+ ave);
}
}
} while (condition);
31
32
3. Jump statements
Example
break;
continue;
•
What is the output of the following code?
–
The break statement jumps
–
The continue statement
immediately jumps to the
public class BreakAndContinueUsage
{
to end and out of the
enclosed compound
head of the next iteration (if
any) of the enclosed loop:
for, while-do and do-while
continue does not apply
to switch statement or
block Statement.
public static void main(String[] args)
{
statement break must be
the last statement in each
compound statement.
System.out.println("Break Usage");
for(int
i
=
1;
System.out.println(i);
if(i 1) break;
i < 100; i++){
–
It transfers the control to
the next statement outside
the compound statement.
>
}
continue label;
The continue statement
System.out.println("Continue Usage");
break label;
–
for(int
i
=
1;
>
i
<
100; i++){
immediately jumps to the
head of the enclosing loop
that is identified by label
label: { statements }
if(i
1) continue;
–
It transfers the control to
the block of statements that
is identified by label
System.out.println(i);
}
}
}
34
The return statement
Quiz - Operator
•
The return statement is used to return from the
current method: it causes program control to
transfer back to the caller of the method.
1. Compile and run the program
AndOperatorUsage.
2. Explain the difference between two AND
operators &&, &
return;
public class AndOperatorUsage
public static void main(String[] args)
int 0; int 5;
false;
{
–
return without value
{
return expression;
i
=
j =
boolean test
=
–
Return with the result of the expression
The type of returned value must match with the
declared return type
//&& operator
test
=
(i
>
5) && (j++
>
4);
–
System.out.println("i
=
"
+
i); System.out.println("j
=
=
"
"
+
+
j);
j);
System.out.println("&& evaluation result:
//& operator
" + test);
•
Inside a method, statements after the return
statement are not executed
test
=
(i
>
5)
&
(j++
>
=
4);
System.out.println("i
System.out.println("& evaluation result:"
"
+
i); System.out.println("j
test);
+
}
}
36
6
21-Oct-16
Quiz 1 - Solution
Quiz 2 - Solution
public class AndOperatorUsage
public static void main(String[] args)
int 0; int 5;
false;
{
Logical AND operator
(&&)
Boolean logical AND
operator (&)
{
i
=
j =
boolean test
=
•
support partial evaluations
(short-circuit evaluations)
•
Does not support partial
evaluations
//&& operator
test
=
(i
>
5) && (j++
>
4);
System.out.println("i
=
"
+
i); System.out.println("j
=
=
"
"
+
+
j);
j);
• exp1 && exp2
• exp1 & exp2
System.out.println("&& evaluation result:
//& operator
" + test);
–
Evaluate the expression
–
–
–
Evaluate the expression
exp1
Evaluate the expression
exp2
Return the result of the
operator
test
=
(i
>
5)
&
(j++
>
4);
exp1
System.out.println("i
System.out.println("& evaluation result:"
=
"
+
i); System.out.println("j
test);
+
–
If exp1 est false:
immediately return a false
value
}
}
•
The operator never
evaluates exp2, because
the result will be false
regardless of the exp2
value
38
Quiz – control flow
Quiz 3 - solution
public class SwitchUsage
public static void main(String args[])
int month 12;
{
3. Using switch statement instead of if-then-else,
write the class SwitchUsage to perform the same
operations as the following class:
{
=
String season;
switch (month)
{
case 12: case 1:
public class IfElseUsage
public static void main(String args[])
int month 12;
{
{
case 2: season
case 3: case 4:
case 5: season
case 6: case 7:
case 8: season
=
=
=
"Winter"; break;
"Spring"; break;
"Summer"; break;
=
String season;
if (month == 12 || month ==
1
|| month == 2)
season
else if(month ==
season
else if(month ==
season
= "Winter";
3
=
|| month ==
"Spring";
4
7
|| month == 5)
|| month == 8)
case 9: case 10:
case 11: season
default: season
}
6
=
|| month ==
"Summer";
=
=
"Autumn"; break;
"Bogus Month";
else if(month ==
season
9
=
|| month == 10 || month == 11)
"Autumn";
System.out.println("December is in
" + season + ".");
else season
= "Bogus Month";
System.out.println("December is in the
"
+
season
+
".");
}
}
}
}
Quiz – control flow
Quiz 4 – solution
•
The break statement terminates the inner iteration after 10 passing.
The outer iteration is performed normally.
If a break statement is used inside nested loops, break will only terminate
the innermost iteration
4. Compile and run the following program. Explain the result.
5. Modify the program so that break statement terminates the
outer iteration just after the first passing.
•
public class NestedLoopAndBreakUsage
public static void main(String args[])
for (int 0; 3; i++)
System.out.print("Outer iteration No
for (int 0; 100; j++)
if (j == 10)
{
public class NestedLoopAndBreakUsage
public static void main(String args[])
for (int 0; 3; i++)
{
{
{
i
=
i
<
{
i
=
i
<
{
"
+ (i + 1) + ": ");
System.out.print("Outer iteration No
": ");
"
+
(i
+
1)
+
j
=
j
<
{
{
System.out.println("Break;");
break;
for (int
j = 0; j < 100; j++) {
if (j == 10)
{
}
System.out.println("Break;");
break;
System.out.print(j
+ " ");
}
}
}
System.out.print(j
+ " ");
System.out.println("Loops complete.");
}
}
}
}
System.out.println("Loops complete.");
}
}
7
21-Oct-16
Quiz 5 – solution
Review
•
•
•
Move the break statement out of the inner iteration.
Place it as the last statement of the outner iteration.
Now the inner iteration terminates after 100 passings, the
outer iteration is terminated after the first passing.
•
Operators: perform specific operations
–
–
–
Unary
Binary
Ternary
public class NestedLoopAndBreakUsage
public static void main(String args[])
for (int 0; 3; i++)
System.out.print("Outer iteration No
for (int 0; 100; j++)
System.out.print(j ");
{
{
•
•
Expression, statement and block
Control flow structures: transfer the program flow
i
=
i
<
{
"
+ (i + 1) + ": ");
j
=
j
<
{
+
"
–
–
–
–
Sequence
Selection
Iteration
Jump
}
System.out.println("Break;");
break;
}
System.out.println("Loops complete.");
}
}
8
Bạn đang xem tài liệu "Bài giảng Phát triển phần mềm phân tán - Bài 3: Java syntax basics (Tiếp theo) - Vũ Thị Hương Giang", để tải tài liệu gốc về máy hãy click vào nút Download ở trên
File đính kèm:
- bai_giang_phat_trien_phan_mem_phan_tan_bai_3_java_syntax_bas.pdf