Conditional Statements in Java

Last updated on Dec 15 2022
Prabhas Ramanathan

Table of Contents

Java If-else Statement

The Javaif statement is used to test the condition. It checks boolean condition: true or false. There are various types of if statement in Java.
• if statement
• if-else statement
• if-else-if ladder
• nested if statement

Java if Statement

The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
1. if(condition){
2. //code to be executed
3. }

java 9 4

Example:
1. //Java Program to demonstate the use of if statement.
2. public class IfExample {
3. public static void main(String[] args) {
4. //defining an ‘age’ variable
5. int age=20;
6. //checking the age
7. if(age>18){
8. System.out.print(“Age is greater than 18”);
9. }
10. }
11. }
Output:
Age is greater than 18

Java if-else Statement

The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.
Syntax:
1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }

java 10

Example:
1. //A Java Program to demonstrate the use of if-else statement.
2. //It is a program of odd and even number.
3. public class IfElseExample {
4. public static void main(String[] args) {
5. //defining a variable
6. int number=13;
7. //Check if the number is divisible by 2 or not
8. if(number%2==0){
9. System.out.println(“even number”);
10. }else{
11. System.out.println(“odd number”);
12. }
13. }
14. }

Output:
odd number

Leap Year Example:

A year is leap, if it is divisible by 4 and 400. But, not by 100.
1. public class LeapYearExample {
2. public static void main(String[] args) {
3. int year=2020;
4. if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
5. System.out.println(“LEAP YEAR”);
6. }
7. else{
8. System.out.println(“COMMON YEAR”);
9. }
10. }
11. }
Output:
LEAP YEAR

Using Ternary Operator

We can also use ternary operator (? 🙂 to perform the task of if…else statement. It is a shorthand way to check the condition. If the condition is true, the result of ? is returned. But, if the condition is false, the result of : is returned.
Example:
1. public class IfElseTernaryExample {
2. public static void main(String[] args) {
3. int number=13;
4. //Using ternary operator
5. String output=(number%2==0)?”even number”:”odd number”;
6. System.out.println(output);
7. }
8. }
Output:
odd number

Java if-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. …
10. else{
11. //code to be executed if all the conditions are false
12.java 11
13. }
Example:
1. //Java Program to demonstrate the use of If else-if ladder.
2. //It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
3. public class IfElseIfExample {
4. public static void main(String[] args) {
5. int marks=65;
6.
7. if(marks<50){
8. System.out.println(“fail”);
9. }
10. else if(marks>=50 && marks<60){
11. System.out.println(“D grade”);
12. }
13. else if(marks>=60 && marks<70){
14. System.out.println(“C grade”);
15. }
16. else if(marks>=70 && marks<80){
17. System.out.println(“B grade”);
18. }
19. else if(marks>=80 && marks<90){
20. System.out.println(“A grade”);
21. }else if(marks>=90 && marks<100){
22. System.out.println(“A+ grade”);
23. }else{
24. System.out.println(“Invalid!”);
25. }
26. }
27. }
Output:
C grade
Program to check POSITIVE, NEGATIVE or ZERO:
1. public class PositiveNegativeExample {
2. public static void main(String[] args) {
3. int number=-13;
4. if(number>0){
5. System.out.println(“POSITIVE”);
6. }else if(number<0){
7. System.out.println(“NEGATIVE”);
8. }else{
9. System.out.println(“ZERO”);
10. }
11. }
12. }
Output:
NEGATIVE

Java Nested if statement

The nested if statement represents the if block within another if block. Here, the inner if block condition executes only when outer if block condition is true.
Syntax:
1. if(condition){
2. //code to be executed
3. if(condition){
4. //code to be executed
5. }
6. }

java 12

Example:
1. //Java Program to demonstrate the use of Nested If Statement.
2. public class JavaNestedIfExample {
3. public static void main(String[] args) {
4. //Creating two variables for age and weight
5. int age=20;
6. int weight=80;
7. //applying condition on age and weight
8. if(age>=18){
9. if(weight>50){
10. System.out.println(“You are eligible to donate blood”);
11. }
12. }
13. }}
Output:
You are eligible to donate blood
Example 2:
1. //Java Program to demonstrate the use of Nested If Statement.
2. public class JavaNestedIfExample2 {
3. public static void main(String[] args) {
4. //Creating two variables for age and weight
5. int age=25;
6. int weight=48;
7. //applying condition on age and weight
8. if(age>=18){
9. if(weight>50){
10. System.out.println(“You are eligible to donate blood”);
11. } else{
12. System.out.println(“You are not eligible to donate blood”);
13. }
14. } else{
15. System.out.println(“Age must be greater than 18”);
16. }
17. } }
Output:
You are not eligible to donate blood

 

Java Switch Statement

The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
In other words, the switch statement tests the equality of a variable against multiple values.
Points to Remember
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only. The case value must be literal or constant. It doesn’t allow variables.
• The case values must be unique. In case of duplicate value, it renders compile-time error.
• The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and string.
• Each case statement can have a break statement which is optional. When control reaches to the break statement, it jumps the control after the switch expression. If a break statement is not found, it executes the next case.
• The case value can have a default label which is optional.
Syntax:
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ……
9.
10. default:
11. code to be executed if all cases are not matched;
12. }

java 13

Example:
1. public class SwitchExample {
2. public static void main(String[] args) {
3. //Declaring a variable for switch expression
4. int number=20;
5. //Switch expression
6. switch(number){
7. //Case statements
8. case 10: System.out.println(“10”);
9. break;
10. case 20: System.out.println(“20”);
11. break;
12. case 30: System.out.println(“30”);
13. break;
14. //Default case statement
15. default:System.out.println(“Not in 10, 20 or 30″);
16. }
17. }
18. }
Output:
20

Finding Month Example:
1. //Java Program to demonstrate the example of Switch statement
2. //where we are printing month name for the given number
3. public class SwitchMonthExample {
4. public static void main(String[] args) {
5. //Specifying month number
6. int month=7;
7. String monthString=””;
8. //Switch statement
9. switch(month){
10. //case statements within the switch block
11. case 1: monthString=”1 – January”;
12. break;
13. case 2: monthString=”2 – February”;
14. break;
15. case 3: monthString=”3 – March”;
16. break;
17. case 4: monthString=”4 – April”;
18. break;
19. case 5: monthString=”5 – May”;
20. break;
21. case 6: monthString=”6 – June”;
22. break;
23. case 7: monthString=”7 – July”;
24. break;
25. case 8: monthString=”8 – August”;
26. break;
27. case 9: monthString=”9 – September”;
28. break;
29. case 10: monthString=”10 – October”;
30. break;
31. case 11: monthString=”11 – November”;
32. break;
33. case 12: monthString=”12 – December”;
34. break;
35. default:System.out.println(“Invalid Month!”);
36. }
37. //Printing month of the given number
38. System.out.println(monthString);
39. }
40. }
Output:
7 – July
Program to check Vowel or Consonant:
If the character is A, E, I, O, or U, it is vowel otherwise consonant. It is not case-sensitive.
1. public class SwitchVowelExample {
2. public static void main(String[] args) {
3. char ch=’O’;
4. switch(ch)
5. {
6. case ‘a’:
7. System.out.println(“Vowel”);
8. break;
9. case ‘e’:
10. System.out.println(“Vowel”);
11. break;
12. case ‘i’:
13. System.out.println(“Vowel”);
14. break;
15. case ‘o’:
16. System.out.println(“Vowel”);
17. break;
18. case ‘u’:
19. System.out.println(“Vowel”);
20. break;
21. case ‘A’:
22. System.out.println(“Vowel”);
23. break;
24. case ‘E’:
25. System.out.println(“Vowel”);
26. break;
27. case ‘I’:
28. System.out.println(“Vowel”);
29. break;
30. case ‘O’:
31. System.out.println(“Vowel”);
32. break;
33. case ‘U’:
34. System.out.println(“Vowel”);
35. break;
36. default:
37. System.out.println(“Consonant”);
38. }
39. }
40. }
Output:
Vowel
Java Switch Statement is fall-through
The Java switch statement is fall-through. It means it executes all statements after the first match if a break statement is not present.
Example:
1. //Java Switch Example where we are omitting the
2. //break statement
3. public class SwitchExample2 {
4. public static void main(String[] args) {
5. int number=20;
6. //switch expression with int value
7. switch(number){
8. //switch cases without break statements
9. case 10: System.out.println(“10”);
10. case 20: System.out.println(“20”);
11. case 30: System.out.println(“30”);
12. default:System.out.println(“Not in 10, 20 or 30″);
13. }
14. }
15. }
Output:
20
30
Not in 10, 20 or 30
Java Switch Statement with String
Java allows us to use strings in switch expression since Java SE 7. The case statement should be string literal.
Example:
1. //Java Program to demonstrate the use of Java Switch
2. //statement with String
3. public class SwitchStringExample {
4. public static void main(String[] args) {
5. //Declaring String variable
6. String levelString=”Expert”;
7. int level=0;
8. //Using String in Switch expression
9. switch(levelString){
10. //Using String Literal in Switch case
11. case “Beginner”: level=1;
12. break;
13. case “Intermediate”: level=2;
14. break;
15. case “Expert”: level=3;
16. break;
17. default: level=0;
18. break;
19. }
20. System.out.println(“Your Level is: “+level);
21. }
22. }
Output:
Your Level is: 3

Java Nested Switch Statement

We can use switch statement inside other switch statement in Java. It is known as nested switch statement.
Example:
1. //Java Program to demonstrate the use of Java Nested Switch
2. public class NestedSwitchExample {
3. public static void main(String args[])
4. {
5. //C – CSE, E – ECE, M – Mechanical
6. char branch = ‘C’;
7. int collegeYear = 4;
8. switch( collegeYear )
9. {
10. case 1:
11. System.out.println(“English, Maths, Science”);
12. break;
13. case 2:
14. switch( branch )
15. {
16. case ‘C’:
17. System.out.println(“Operating System, Java, Data Structure”);
18. break;
19. case ‘E’:
20. System.out.println(“Micro processors, Logic switching theory”);
21. break;
22. case ‘M’:
23. System.out.println(“Drawing, Manufacturing Machines”);
24. break;
25. }
26. break;
27. case 3:
28. switch( branch )
29. {
30. case ‘C’:
31. System.out.println(“Computer Organization, MultiMedia”);
32. break;
33. case ‘E’:
34. System.out.println(“Fundamentals of Logic Design, Microelectronics”);
35. break;
36. case ‘M’:
37. System.out.println(“Internal Combustion Engines, Mechanical Vibration”);
38. break;
39. }
40. break;
41. case 4:
42. switch( branch )
43. {
44. case ‘C’:
45. System.out.println(“Data Communication and Networks, MultiMedia”);
46. break;
47. case ‘E’:
48. System.out.println(“Embedded System, Image Processing”);
49. break;
50. case ‘M’:
51. System.out.println(“Production Technology, Thermal Engineering”);
52. break;
53. }
54. break;
55. }
56. }
57. }
Output:
Data Communication and Networks, MultiMedia
Java Enum in Switch Statement
Java allows us to use enum in switch statement.
Example:
1. //Java Program to demonstrate the use of Enum
2. //in switch statement
3. public class JavaSwitchEnumExample {
4. public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }
5. public static void main(String args[])
6. {
7. Day[] DayNow = Day.values();
8. for (Day Now : DayNow)
9. {
10. switch (Now)
11. {
12. case Sun:
13. System.out.println(“Sunday”);
14. break;
15. case Mon:
16. System.out.println(“Monday”);
17. break;
18. case Tue:
19. System.out.println(“Tuesday”);
20. break;
21. case Wed:
22. System.out.println(“Wednesday”);
23. break;
24. case Thu:
25. System.out.println(“Thursday”);
26. break;
27. case Fri:
28. System.out.println(“Friday”);
29. break;
30. case Sat:
31. System.out.println(“Saturday”);
32. break;
33. }
34. }
35. }
36. }
Output:
Sunday
Monday
Twesday
Wednesday
Thursday
Friday
Saturday

Java Wrapper in Switch Statement

Java allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement.
Example:
1. //Java Program to demonstrate the use of Wrapper class
2. //in switch statement
3. public class WrapperInSwitchCaseExample {
4. public static void main(String args[])
5. {
6. Integer age = 18;
7. switch (age)
8. {
9. case (16):
10. System.out.println(“You are under 18.”);
11. break;
12. case (18):
13. System.out.println(“You are eligible for vote.”);
14. break;
15. case (65):
16. System.out.println(“You are senior citizen.”);
17. break;
18. default:
19. System.out.println(“Please give the valid age.”);
20. break;
21. }
22. }
23. }

Output:
You are eligible for vote.
So, this brings us to the end of blog. This Tecklearn ‘Conditional Statements in Java’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

 

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Conditional Statements in Java"

Leave a Message

Your email address will not be published. Required fields are marked *