Java-class-3
Java-class-3
Keywords are
particular words that act as a key to a code. These are predefined
words by Java so they cannot be used as a variable or object name or
class name.
Loop statements
do while loop
while loop
for loop
for-each loop
Jump statements
break statement
continue statement
1) Simple if statement:
if(condition) {
statement 1; //executes when condition is
true
}
if(condition) {
statement 1; //executes when condition is
true
}
else{
statement 2; //executes when condition is
false
}
if(condition 1) {
statement 1; //executes when condition 1 i
s true
}
else if(condition 2) {
statement 2; //executes when condition 2 i
s true
}
else {
statement 2; //executes when all the condi
tions are false
}
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}
4. Nested if-statement
if(condition 1) {
statement 1; //executes when condition 1 i
s true
if(condition 2) {
statement 2; //executes when condition 2 i
s true
}
else{
statement 2; //executes when condition 2 i
s false
}
}
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 I
ndia");
}
}
}
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.