if-else are very important control statement. We use if-else to make our program follow some rules. We define a condition or expression for if-else and if the condition associated with "if" is true then the "if" block is executed and if the condition is false then the execution goes to the "else" block. We can use "if" statement alone with no "else" but we can not use "else" alone. A very simple program is depicted here to show how if-else works.
public class IF_Else_Demo
{
public static void main(String[] args)
{
int var = 10;
if(var == 10)
{
System.out.println("INSIDE IF BLOCK");
}
else
{
System.out.println("INSIDE ELSE BLOCK");
}
}
}
In the above program, we have a variable "var" and we have assigned it a value of ten (10). When the execution goes to the "if" block it checks if the value of "var" is equal to 10, yes it is, it goes inside the "if" block and prints the given texts on the screen.
If you change the value of "var" other than 10, the "if" block will not be running because the condition of the "if" will be "false" and the "else" part will be running and it will print "INSIDE ELSE BLOCK" on the screen.
Subscribe to:
Post Comments (Atom)

0 comments:
Post a Comment