Example:
temp = x*x + y*y;
d = Math.sqrt(temp);
x = 5;
y = 11;
z = x + y;
System.out.println(z);
Example:
{
double temp, d;
temp = x*x + y*y;
d = Math.sqrt(temp);
}
if (condition) {
statements
}
Example:
if (x % 2 == 0) {
System.out.println("The number is
even.");
}
Example: Age.java
if (condition) {
statement1;
} else {
statement2;
}
if (condition1) {
statement1;
} else if (condition2) {
statement2;
} else if (condition3) {
statement3;
} else {
statement4;
}
Example: Wages.java
Example: MinOfThree.java
MinOfThree1.java (Version avoiding nesting)
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
case value3:
statement3;
break;
default:
statement4;
}
Example: GradeReport.java)
Example:
(x >= 0) ? x : -x ;
The conditional expression returns one of the two values. Usualy we use the value returned by the expression in an assignment statement:
Example: int larger = (x > y) ? x : y ;
while (condition) {
statements;
}
When the body of a while statement, or of a for statement consists of a single statement, no braces are necessary.
Example:
int i = 1;
while (i <= 20) {
System.out.println(i);
i++;
}
for (initialization; condition;
incrementation) {
statements;
}
Example:
for (int i = 1; i <= 20; i++) {
System.out.println(i);
}
do {
statements;
} while (condition);
// Do NOT forget the semi-colon
Example:
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 20);
Example:
int i = 0;
while (i <= 20) {
i++;
if (i % 5 == 0) break;
System.out.println(i);
//prints 1 2 3 4 6 7 8 9 11 12 13 14 16 17 18 19 21,
//one number per line
}
Example:
int i = 0;
while (i <= 20) {
i++;
if (i % 5 == 0) continue;
System.out.println(i);
// print 1 2 3 4 , one number per line
}
ClassName.methodName(parameters,
...)
Other examples using the Keyboard class: Average.java Quadratic.java
Here are now the Echo and Quadratic classes without using Keyboard class EchoStd.java Quadratic1.java