- Java Tutorial
- Java Introduction
- Java Features
- Java Simple Program
- JVM, JDK and JRE
- Java Syntax
- Java Comments
- Java Keywords
- Java Variables
- Java Literals
- Java Separators
- Java Datatypes
- Java Operators
- Java Statements
- Java Strings
- Java Arrays
- Control Statement
- Java If
- Java If-else
- Java If-else-if
- Java Nested If
- Java Switch
- Iteration Statement
- Java For Loop
- Java For Each Loop
- Java While Loop
- Java Do While Loop
- Java Nested Loop
- Java Break/Continue
- Java Methods
- Java Methods
- Java Method Parameters
- Java Method Overloading
- Java Recursion
- Java OOPS
- Java OOPs
- Java Classes/Objects
- Java Inheritance
- Java Polymorphism
- Java Encapsulation
- Java Abstraction
- Java Modifiers
- Java Constructors
- Java Interface
- Java static keyword
- Java this keyword
- Java File Handling
- Java File
- Java Create File
- Java Read/Write File
- Java Delete File
- Java Program To
- Add Two Numbers
- Even or Odd Numbers
- Reverse a String
- Swap Two Numbers
- Prime Number
- Fibonacci Sequence
- Palindrome Strings
- Java Reference
- Java String Methods
- Java Math Methods
Java If-else Statement
In Java, the if-else statement is used for decision-making based on conditions. Here's an overview:
Syntax:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
Simple If-else Statement:
- Executes one block of code if the condition is true, and another block if the condition is false.
- Example:
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is not greater than 5");
}
Chained If-else Statement:
- Allows multiple conditions to be checked sequentially.
- Example:
int age = 20;
if (age < 18) {
System.out.println("You are a minor");
} else if (age >= 18 && age < 65) {
System.out.println("You are an adult");
} else {
System.out.println("You are a senior citizen");
}
Nested If-else Statement:
- An if-else statement inside another if-else statement.
- Example:
int num = -5;
if (num >= 0) {
if (num == 0) {
System.out.println("Number is zero");
} else {
System.out.println("Number is positive");
}
} else {
System.out.println("Number is negative");
}
Summary
The if-else statement in Java provides a way to execute different blocks of code based on whether a condition is true or false. It allows for decision-making in Java programs, enabling the creation of more dynamic and responsive applications. Understanding how to use if-else statements is essential for controlling program flow and implementing logic in Java.