Page 335 - CITS - Computer Software Application -TT
P. 335
COMPUTER SOFTWARE APPLICATION - CITS
Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement.
Syntax of Nested if-statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.
Student.java
public class Student {
public static void main(String[] args) {
String address = “Delhi, India”;
if(address.endsWith(“India”)) {
if(address.contains(“Meerut”)) {
System.out.println(“Your city is Meerut”);
}else if(address.contains(“Noida”)) {
System.out.println(“Your city is Noida”);
}else {
System.out.println(address.split(“,”)[0]);
}
}else {
System.out.println(“You are not living in India”);
}
}
}
Output:
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks
of code called cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
Points to be noted about switch statement:
• The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7
of Java
• Cases cannot be duplicate
322
CITS : IT&ITES - Computer Software Application - Lesson 85 - 93