Articles → Java → Conditional Statements in Java

Conditional Statements in Java






What are conditional statements?













Types of conditional statements in Java













If statement




if (condition) {
    code to be executed
    if condition is true;
}




Boolean is_client_call = true;

if (is_client_call == true) {
    System.out.println("I will go for movie");
}





If..else statement




if (condition) {
    code to be executed
    if condition is true;
} else {
    code to be executed
    if condition is false;
}




Boolean wish_to_play_game = true;
if (wish_to_play_game == true) {
    System.out.println("Go to gaming zone");
} else {
    System.out.println("Go Home");
}





If..elseif..else statement




if (condition) {
    code to be executed
    if condition is true;
}
elseif(condition) {
    code to be executed
    if condition is true;
} else {
    code to be executed
    if condition is false;
}




Boolean cheap_air_tickets = false;
Boolean train_tickets_available = true;

if (cheap_air_tickets == true) {
    System.out.println("Go by flight");
} else if (train_tickets_available == true) {
    System.out.println("Go by train");
} else {
    System.out.println("Hire a cab");
}





Switch statement




switch (n) {
    case label1:
        code to be executed
        if n = label1;
        break;
    case label2:
        code to be executed
        if n = label2;
        break;
    case label3:
        code to be executed
        if n = label3;
        break;
        ...
    default:
        code to be executed
        if n is different from all labels;
}




String mode = "FLIGHT";
switch (mode) {
    case "FLIGHT":
        System.out.println("I will go by flight");
        break;
    case "CAB":
        System.out.println("I will go by Cab");
        break;
    default:
        System.out.println("I will go by Train");
}





Difference between if..else and switch statement











Posted By  -  Karan Gupta
 
Posted On  -  Sunday, September 18, 2016

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250