Decision Making Statements
if statement
if-else statement
switch statement
Loop Statements
while loop
do-while loop
for loop
for-each loop
Branching Statements
break
continue
return
if statement
if (condition) {
// block of code to be executed if the condition is true
}
if: This keyword checks the condition given in parentheses.
condition: A boolean expression that, when true, executes the block of code
inside the curly braces.
Block of code: If the condition is true, the statements inside the curly braces
are executed.
// Define a class named 'NumberCheck'
public class NumberCheck
{
// The main method - entry point of the Java application
public static void main(String[] args) {
// Declare an int variable 'number' and initialize it with -10
int number = -10;
// An 'if' statement to check if the variable 'number' is greater than 0
if (number > 0) {
// This line is executed only if the 'if' condition is true
// Prints "The number is positive." to the console
System.out.println("The number is positive.");
}
else {
// This line is executed only if the 'if' condition is false
// Prints "The number is not positive." to the console
System.out.println("The number is not positive.");
}
}
}
A COLLEGE has following rules for grading
system:
a. Below 25 - F
b. 25 to 45 - E
c. 45 to 50 - D
d. 50 to 60 - C
e. 60 to 80 - B
f. Above 80 - A
Ask user to enter marks and print the
corresponding grade.
for (int i = 1; i <= 5; i++)
Java Labeled For Loop
for-each loop
The for-each loop is used to loop through elements in an array
or a collection.
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
Branching Statements
break
The break statement is used to exit a
loop or a switch statement.
for (int i = 1; i <= 10; i++) 1
{ 2
if (i == 6) 3
{ 4
break; // It will exit the loop when i is 6 5
}
System.out.println(i);
}
Continue
The continue statement skips the current iteration of a loop and
continues with the next iteration.
continue;: The continue statement is executed
1 when i is even. It causes the loop to immediately
for (int i = 1; i <= 10; i++) 3 stop executing the remaining code in the current
{ 5 iteration and proceed with the next iteration of
7 the loop.
if (i % 2 == 0) 9
{
continue; // It will skip the rest of the loop body if i is even
}
System.out.println(i);
}