The general form is:
if(b) { action,b is true } else { action.b is false }
Where b is anything or expression that should be a boolean value.
if(condition) statement1; else statement2;
Here each statement may be a single statement or compound statement enclosed in a block. The condition is any expression that returns a Boolean value and else part is optional. The mechanism is if the condition is true, then statement1 is executed, otherwise statement2 will be executed. Consider an example :
class IfElseDemo { public static void main(String args[ ]) { int x=15; if(x<20) System.out.println("JavaRace"); else System.out.println("JavaExcellence"); } }
Download Code
Output
JavaRace
There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop. A loop is defined as the repetition of instruction till the condition is satisfied.
class IfElseDemo1 { public static void main(String[] args) { int x=0; if(x) { System.out.println("Silan Software"); } else { System.out.println("JavaRace"); } } }
Output
Compilation Error: incompitible types
found : int
required : boolean
class IfElseDemo2 { public static void main(String[]args) { int x=10; if(x=20) { System.out.println("Silan Software"); } else { System.out.println("JavaRace"); } }
Output
Compilation Error
Compilation Error: incompitible types
found : int
required : boolean
let's see some other example for better clarity:
1. intx=50; if(x==50) { s.o.p("Hi"); } else { s.o.p("Hello"); }
Output:
Hi
2. boolean b=false; if(b) { s.o.p("Hi"); } else { s.o.p("Hello"); }
Output:
Hello
3. boolean b=false; if(b==false) { s.o.p("Hi"); } else { s.o.p("Hello"); }
Output:
Hi
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc