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.7K+ Learners
    4.55  (287)
    Become Full Stack Developer
    1 hrs
    Beginner
    66.1K+ Learners
    4.26  (1348)
    Bitcoin for Beginners
    1 hrs
    Beginner
    6.9K+ Learners
    4.54  (438)
    Pygame Basics
    1 hrs
    Beginner
    5.8K+ Learners
    4.37  (206)
    Inheritance in Java
    1 hrs
    Beginner
    4.6K+ Learners
    4.49  (285)
    Tic Tac Toe Python
    1 hrs
    Beginner
    2.7K+ Learners
    4.51  (81)
    Anaconda Python
    2 hrs
    Beginner
    3.8K+ Learners
    4.37  (310)
    Operators in MySQL
    2 hrs
    Beginner
    8.2K+ Learners
    4.5  (477)
    Advanced SQL
    1 hrs
    Intermediate
    29.1K+ Learners
    4.48  (2250)