Java

Decision Making in Java

Decision Making in Java

Decision-Making statements are used to make decisions based on certain conditions. The following are the decision-making statements. 

If-Else Statements 

If the condition specified in the if block is true, then the logic inside the if block will be executed, otherwise it enters the else block and executes the logic in it 
if(condition) { 
// This code executes if the condition is true 
} else { 
// This code executes if the condition is false 
} 


Example: 

int x = 5; 
if(x > 0) { 
System.out.println("x is positive"); 
} else { 
System.out.println("x is non-positive"); 
}

 

Here, the output will be “x is positive”, since the value of x is 5 and the condition in the if block is true. 

If-Else-If Statements 
In if -else we do not mention the condition in the else block, so if one wants to check against multiple conditions, use if-else-if statements. 
Syntax: 

if(condition1) { 
/ this code executes if condition1 is true 
} else if(condition2) { 
/ this code executes if condition1 is false and condition2 is true 
} else if(condition3) { 
/ this code executes if condition1 and condition2 are false and condition3 is true } ... 
else { 
/ this code executes if all conditions are false 
}

 Example: 

int y = 10; 
if(y > 0) { 
System.out.println("y is positive"); 
} else if(y < 0) { 
System.out.println("y is negative"); 
} else { 
System.out.println("y is zero"); 
} 

Switch case: 
A switch-case statement is used to execute a block of code based on the value of a variable. 
Syntax: 

switch(variable) { 
case value1: 
/ code to be executed if the variable is equal to value1 
break; 
case value2: 
/ this code executes if the variable is equal to value2 
break; 
... 
default: 
/ this code executes if the variable does not match any of the values 
} 

Example: 

int day = 3; 
switch(day) { 
case 1: 
System. out.println("Monday"); 
break; 
case 2: 
System.out.println("Tuesday"); 
break; 
case 3: 
System.out.println("Wednesday"); 
break; 
... 
default: 
System.out.println("Invalid day"); 
} 

This switch-case statement will print "Wednesday" to the console 

Top course recommendations for you

    Backtracking Algorithm
    1 hrs
    Beginner
    2.8K+ Learners
    4.57  (327)
    Become Full Stack Developer
    1 hrs
    Beginner
    68.7K+ Learners
    4.27  (1394)
    Bitcoin for Beginners
    1 hrs
    Beginner
    7.1K+ Learners
    4.54  (474)
    Pygame Basics
    1 hrs
    Beginner
    5.9K+ Learners
    4.4  (228)
    Inheritance in Java
    1 hrs
    Beginner
    4.7K+ Learners
    4.52  (320)
    Tic Tac Toe Python
    1 hrs
    Beginner
    2.8K+ Learners
    4.5  (96)
    Anaconda Python
    2 hrs
    Beginner
    4K+ Learners
    4.37  (349)
    Operators in MySQL
    2 hrs
    Beginner
    8.4K+ Learners
    4.51  (519)
    Advanced SQL
    1 hrs
    Intermediate
    30.2K+ Learners
    4.5  (2548)