TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Java If-Else Conditions
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Java Flow ControlJava Tutorials

Java If-Else Conditions

Last updated: Sep 30, 2023 6:31 pm
By Meenakshi Agarwal
Share
5 Min Read
Java If, If-Else-If Conditions
SHARE

This tutorial will guide you on how to add conditions in Java programs. You will see different types of if, if-else statements to implement decision-making.

Contents
Simple if statementDescription:Example:Nested if statementDescription:Example:If-else statementDescription:Example:If-else-if statementDescription:Example:

If you want your program to execute some code based on a condition or a different block otherwise, then you need to use control flow statements like if or if-else. Take an example; you have to print whether a year is a leap year or not.

If the days are 366, then you should display “A Leap Year” otherwise print “Not a Leap Year.” So, you need two print statements in the program, but only one of them will run at a time based on the “days” value.

Today, we’ll teach how can you add such types of conditions in your programs using if-else statements.

Basics of If-else in Java

There are four variations of if-else statements available in Java.

  • if statement
  • Nested if statement
  • if-else statement
  • if-else-if statement

Simple if statement

Description:

This if statement denotes a condition joined by one or more statements enclosed in curly braces.

If the block has one statement, then there is no need for the curly braces.

if ( test_condition or expr ) {
    statement(s);
}
Java If Condition

The block runs only when the condition evaluates to true. If the result is false, then the instructions inside if block ignore execution.

Please note that while forming a condition, you can join multiple expressions or boolean values using operators like AND (&&), OR (||), NOT (!), etc.

Example:

public class SimpleIfStatement {

   public static void main(String args[]) {
      int days = 366;
      if( days == 366 ) {
	  System.out.println("A Leap Year!");
          return;
      }
      System.out.println("Not a Leap Year.");
   }
}

Output:

The above program would print the following:

A Leap Year

Nested if statement

Description:

It means you have a conditional block that has another if condition. This chain can go on and on. That’s why we call it a nested if statement.

In reality, a nested if would look like the following:

if(expr_1) {
   outer_statements;

   if(expr_2) {
       inner_statement(s);
   }
}

If you review the example, you will understand that the outer statement would run first if the expr_1 returns true. The inner_statement will run if both the expressions ( expr_1/2) evaluate to true.

Example:

public class NestedIfProgram {

   public static void main(String args[]){
        int days = 366;
        int month = 2;

	if( days == 366 ){ 
           System.out.println("A Leap Year!"); 

           if(month == 2){
	      System.out.println("Month is Feb with 29 days.");
	   }
	}
   }
}

Output:

A Leap Year!

Month is Feb with 29 days.

If-else statement

Description:

This statement caters to both parts, one is the if block which executes upon matching the condition and the second is the else code block which runs when the condition doesn’t match.

if ( test condition ) {
   statement(s);
} else {
   statement(s);
}

The above statements inside “if” will run if the condition evaluates to true, and the code inside the “else” block executes if the condition fails.

Java If-Else Condition

Example:

public class IfElseProgram {

   public static void main(String args[]){
     int days = 365;
     if( days == 366 ){
	System.out.println("A Leap Year!");
     }
     else {
	System.out.println("Not a Leap Year.");
     }
   }
}

Output:

Not a Leap Year.

If-else-if statement

Description:

When you have to handle a use case that has multiple conditions, you would need one starting if and the other following else-if statements.

The standard technical name for this construct is if else if ladder.

if ( test condition 1) {
   statement(s);
} else if ( test condition 2) {
   other statement(s);
else if ( test condition 3) {
   More statement(s);
}
Java If-Else-If-Else Condition

Please note that if a condition is found as true, then the corresponding set of statements executes leaving others as is. If no condition matches, then instructions inside the “else” part execute.

Example:

public class IfElseIfProgram {

   public static void main(String args[]){
	int day = 1;
	if(day == 1) {
	  System.out.println("Monday");
	} else if(day == 2) {
	  System.out.println("Tuesday");
	} else if(day == 3) {
	  System.out.println("Wednesday");
	} else if(day == 4) {
	  System.out.println("Thrusday");			
	} else if(day == 5) {
	  System.out.println("Friday");			
	} else if(day == 6) {
	  System.out.println("Saturday");			
	} else if(day == 7) {
	  System.out.println("Sunday");			
	} else {
	  System.out.println("Invalid day!");			
	}
   }
}

Output:

Monday

Must Read – Switch Case Statement in Java

You Might Also Like

A Simple Guide to Exception Handling in Java

Difference Between Spring and Spring Boot

How to Use Java String Format with Examples

Java IRC Bot with Sample Code

Generate Random Number in Java – 10 Ways

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python IRC Bot Client Learn to Build an IRC Bot in Python 3
Next Article Java Switch Case with Examples Switch-Case in Java

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x