Conditional Statements in Java
The below article goes through the Conditional Statements in Java. It covers if, if-else, nested if-else, and switch statements with examples.
Contents
Best-suited Java courses for you
Learn Java with these high-rated online courses
Introduction
Conditional Statements come under Control Structures in Java. As the same suggests, it controls the flow of the execution of the program. Controlling here means branching, decision-making, and iterating.
Generally, there are 3 types of Control Structures in Java:
- Conditional Statements or Decisional Statements (if, if-else, switch)
- Iteration Statements or Loops (for, while, do-while, for-each)
- Jump Statements (break, continue, return)
In this article, we aim to explain conditional statements in Java and their working with examples.
Conditional Statements in Java
Conditional statements in Java are the executable block of code (or branch to a specific code) dependent on certain conditions. These statements are also known as decision statements or selection statements in Java.
Following are the statements covered under conditional statements in Java:
If Statement
If a statement executes a set of statements based upon certain conditions. The condition statement follows the if keyword.
Syntax:
if (condition) { //Statements to be executed }
Working of if statement:
The if clause accepts a condition and executes the set of statements falling under it only when the condition evaluated is true.
Instance: displaying a number as positive (statement) if the number is greater than zero (condition).
Example:
class if_condition { public static void main(String[] args) { double a = 0.5; if (a>0) { System.out.println(a + " is a Positive Number!"); } }}
Output:
Also read: Variables in Java
If-Else Statement
If-Else statement is a control structure that selects or chooses a set of statements depending upon certain conditions.
If statements are like a subset of if-else statements.
Syntax:
if (condition) { //Statements to be executed if condition satisfies } else { //Statements to be executed if the condition is not satisfied }
Working of if-else statements:
Here, the if clause evaluates the expression. If it comes out as true, statements under if block gets executed. Else, statements under the else block get executed. As you can observe here, depending upon the condition some sets of statements are executed and some are bypassed.
Note: An else clause should always come after the if clause. If not, then the compiler will generate an error stating โmisplaced elseโ.
Read: Difference between JDK, JVM and JRE.
Instance: Display a number as positive or negative based upon the condition: if the number is greater than 0 or not.
Example:
class if_else_condition { public static void main(String[] args) { double a = -0.5; if (a>0) { System.out.println(a + " is a Positive Number!"); } else { System.out.println(a + " is a Negative Number!"); } }}
Output:
Also Read: Java Hello World Program
Nested If-Else Statements
The nested if-else statements are statements that incorporate more than one if-else clause.
Syntax:
if (condition) { //Statements set 1 } else if (condition 2) { //Statements set 2 } . . . else { //Statements to be executed if no condition is satisfied. }
Example:
class nested_if_else_condition { public static void main(String[] args) { double total_marks = 382; char grade; double perc = (total_marks/500)*100; if (perc >= 80) { grade = 'A'; } else if ((perc >=70) && (perc <80)) { grade = 'B'; } else if ((perc >=60) && (perc <70)) { grade = 'c'; } else { grade = 'D'; } System.out.println("The percentage of the student is: " +perc); System.out.println("\n The grade of the student is: " +grade); }}
Output:
Go for Best Courses on Java Programming.
Switch Statement
Unlike the if-else statement, the switch has multiple paths of execution. Moreover, it evaluates the expression based on some of the primitive types or class types and matches their value with its cases.
A switch can work well with a byte, char, short, and int primitive data types.
Syntax:
switch (Expression) { case value 1: Statement 1; case value 2: Statement 2; case value 3: Statement 3; . . . case value n: Statement n; Default: default statement; }
Example:
class Switch_Case { public static void main(String[] args) { char a = 'C'; switch (a) { case 'A': System.out.println("Letter A"); break; case 'C': System.out.println("Letter C"); break; default: System.out.println("Default case: NO Letter Matched!"); } }}
Output:
Note: The break statement used in the above program is a jump statement that alters the flow of execution and jumps to a new set of statements. Here, a break jump statement bypasses all the other cases and jumps out of a switch.
Also Read: Java Operators Explained
Multiple case labels in a switch
We can have multiple case labels in a switch statement. This type of switch case label is required when we want to perform the same task for a set of cases.
Example:
class Multiple_Case_Label { public static void main(String[] args) { char a = 'c'; switch (a) { case 'B': case 'b': System.out.println("Letter B"); break; case 'C': case 'c': System.out.println("Letter C"); break; default: System.out.println("Default case: NO Letter Matched!"); } }}
Output:
Read: Arrays in Java
If-Else vs. Switch statements
The below table shows you the differences between if-else and switch statements in Java.
If-Else | Switch | |
---|---|---|
Flow of Execution | Can have only two possible paths of execution either if or else. | Can have multiple paths of execution in the forms of different cases. |
Type of Outcome | Always evaluates an expression to a boolean value. | Can evaluate an expression to a byte, short, char, and int primitive type values. |
Readability | Less readable in case of multiple if-else. | More readable in case of multiple cases. |
Efficiency | It becomes less efficient in case of multiple if-else. Since it checks for every if/else and evaluates the corresponding statements. | More efficient working because once a valid match is found, the other cases are bypassed if handled carefully with a break statement. |
Conclusion
Hope you enjoyed reading the above article and learned something new about conditional statements in Java. Share your thoughts and queries in the link below.
For more, Read: 8 Most Important Data Structures a Programmer Must Know
Recently completed any professional course/certification from the market? Tell us what liked or disliked in the course for more curated content.
Click here to submit its review with Shiksha Online.
FAQs
What are Control Statements in Java?
It controls the flow of the execution of the program. Controlling here means branching, decision-making, and iterating.
What are Conditional Statements in Java?
Conditional statements in Java are the executable block of code (or branch to a specific code) dependent on certain conditions.
How does the break statement work with the switch case?
The break statement used in the above program is a jump statement that alters the flow of execution and jumps to a new set of statements. In the switch case, a break jump statement bypasses all the other cases and jumps out of a switch.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio