2. Conditional Statement if else:
When should we use if else statement?
- if you want to do either one thing or another thing then you have
to choose if-else statement.
syntax:
if (expression)
{
if block statements
}
else
{
else block statements
}
- if statement holds an
expression.
- expression gives the result either true or false.
- if
the result is true then if block
statements will executes.
- if
the result is false then else
block statements will executes.
--------------------------------------------------------------------------------
Program
: Basic program on if
else statement
Program name : IfElseDemo1.java
Output :
value of x==y is :true
inside if block
class IfElseDemo1
{
public static void main(String args[])
{
int
x = 100;
int y = 100;
System.out.println("value of
x==y is :"+(x==y));
if(x==y)
{
System.out.println("inside if block");
}
else
{
System.out.println("inside else block");
}
}
}
Compile : javac IfElseDemo1.java
Run : java IfElseDemo1
Output :
value of
x==y is :true
inside if block
--------------------------------------------------------------------------------
Program
: Basic program on if
else statement
Program name : IfElseDemo2.java
Output :
value of x==y is :false
inside elseblock
class IfElseDemo2
{
public static void main(String args[])
{
int
x = 100;
int y = 200;
System.out.println("value of x==y is :"+(x==y));
if(x==y)
{
System.out.println("inside if block");
}
else
{
System.out.println("inside else block");
}
}
}
Compile : javac IfElseDemo2.java
Run : java IfElseDemo2
Output :
value of
x==y is :false
inside else
block
--------------------------------------------------------------------------------
Thanks for your time.
-Nireekshan