JAVA Statements
JAVA Statements
4. Java Statements
1. Input and Output Statements:
2. Conditional Statements: if,if-else,if-else-ladder,nested-if-else,switch
3. Iterative Statements: for,for-each, while, do-while,
4. Transfer Statements: break, continue
1.Input and Output Statements
if (condition) {
// statements
}
Here, condition is a boolean expression such as age >= 18.
The if statement executes a certain section of code if the test expression is evaluated to
true. However, if the test expression is evaluated to false, it does nothing.
The syntax of the if...else statement is:
if (condition) {
// codes in if block
}
else {
// codes in else block
}
if-else ladder
In Java, we have an if...else...if ladder, that can be used to execute one block of code among
multiple other blocks.
if (condition1) {
// codes
}
else if(condition2) {
// codes
}
else if (condition3) {
// codes
}
.
else {
// codes
}
Nested if-else
In Java, it is also possible to use if..else statements inside an if...else
statement. It's called the nested if...else statement.
Switch
The switch statement allows us to execute a block of code among many alternatives.
The syntax of the switch statement in Java is:
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
...
...
default:
// default statements
}
3. Iterative Statements
In computer programming, loops are used to repeat a block of code. For
example, if you want to show a message 100 times, then rather than
typing the same code 100 times, you can use a loop.
• for loop
• for each loop
• while loop
• do...while loop
Java for Loop
Java for loop is used to run a block of code for a certain number of
times. The syntax of for loop is:
for (initialExpression; testExpression; updateExpression) {
// body of the loop
}
Java for-each Loop
The Java for loop has an alternative syntax that makes it easy to iterate through
arrays and collections. For example,