Java Statements
Java Statements
Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of
execution.
The following types of expressions can be made into a statement by terminating the expression with a
semicolon (;).
Assignment expressions
Any use of ++ or --
Method invocations
Object creation expressions
o some examples of expression statements.
// assignment statement
aValue = 8933.234;
// increment statement
aValue++;
// method invocation statement
System.out.println("Hello World!");
// object creation statement
Bicycle myBike = new Bicycle();
declaration statements
o // declaration statement
o double aValue = 8933.234;
decision-making statements (
if-then : to execute a certain section of code only if a particular test evaluates to true.
if-then-else: provides a secondary path of execution when an "if" clause evaluates
to false.
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the
remaining conditions are not evaluated.
Switch
o the switch statement can have a number of possible execution paths.
o works with the byte, short, char, and int primitive data types
o also works with enumerated types
o the String class, and a few special classes that wrap certain primitive
types: Character, Byte, Short, and Integer
o body of a switch statement is known as a switch block
o executes all statements that follow the matching case label
o All statements after the matching case label are executed in sequence, regardless of the
expression of subsequent caselabels, until a break statement is encountered.
o Deciding whether to use if-then-else statements or a switch statement is based
on readability and the expression that the statement is testing. An if-then-
else statement can test expressions based on ranges of values or conditions,
whereas a switch statement tests expressions based only on a single integer,
enumerated value, or String object.
o switch (optt){
o case 1: {System.out.println("January"); break;}
o case 5:{System.out.println("may"); break;}
o default: {System.out.println("none"); break;}
o }
o a statement can have multiple case labels
java.util.ArrayList<String> futureMonths =
new java.util.ArrayList<String>();
case 12: futureMonths.add("December");
break;
if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
===============================================================
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;