if else in java
previous NextWhenever we have to check any condition and take the decision, if that condition is correct. Then only the statement runs. So in that condition we use if
Syntax for if in java
if(argument){ //code to be exucuted }
The argument to the if statement should be Boolean. and the if statement also known as conditional statment.
code for if statement
class IfElseProgram{
public static void main(String[] args) {
int a = 10;
if(a==10){
System.out.println("a is equal b");
}
}
}
Output :
true
if we are trying to give any other than boolean in the argument of the if statement then we will get compile time error.
Example 2
class IfElseProgram{
public static void main(String[] args) {
int a = 20;
if(a){ // a is a int now we will get compiler time error
System.out.println("a is greater b");
}
}
}
Output :
error: incompatible types: int cannot be converted to boolean if(a){ // a is a int now we will get compiler time error ^ 1 error
if else statement in java
If-else statement is same as if statement but in this statement if condition is true then if statement will execute and if statement false then else block will execute.
Syntax for if else statement java
if(condition){ //code to be exucuted true }else{ //code to be exucuted false }
Example for if else
import java.util.Scanner;
class Aman{
public static void main(String[] args) {
Scanner scr = new Scanner(System.in);
System.out.println("Enter the age");
int age = scr.nextInt();
if(age>=18){
System.out.println("worth voting");
}else{
System.out.println("not worth voting");
}
}
}
Output :
enter the age 20 worth voting
java if statement multiple conditions
Syntax for java if statement multiple conditions
if(condition1 && condition2 && condition3){ //code to be exucuted true }
import java.util.Scanner;
class MultipleConditionIfElse{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter username");
String username = sc.nextLine();
System.out.println("Enter password");
String password = sc.nextLine();
if(username.equals("b2eprogrammers")&&password.equals("b2e@123")){
System.out.println("Login success");
}else{
System.out.println("Login fail");
}
}
}
Enter username b2eprogrammers Enter password b2e@123 Login success

if we want to check all condition as true then we should go with && operator with all condition.
Example
else if ladder in java
Syntax
if(condition)
{code to be exucuted true
}
else if(condition)
{
code to be exucuted true
}
else if(condition)
{
code to be exucuted true
}
else{
code to be exucuted false
}
Defination if else if statement
Example
class Aman{
public static void main(String[] args) {
int a = 50;
int b = 100;
int c = 30;
int d = 5;
if(a>b&&a>c&&a>d){
System.out.println("a is greater");
}else if(b>a&&b>c&&b>d){
System.out.println("b is greater");
}else if(c>a&&c>b&&c>d){
System.out.println("c is greater");
}else{
System.out.println("d is greater");
}
}
}
Output :
b is greater