Java if example : Using if statement in java


“if” statement, is the simplest form of conditional branching in java. The” if” statement consist of a condition and block of statements. If the condition returns true the statement block is executed or if condition return false the statement block is ignored.

Syntax :
If(condition)
{
Statement 1;
Statement 2;
……….
}

Example :
public class SimpleIfExample
{
public static void main(String args[])
{
char ch=(char)-1;
System.out.println("Enter a alphabet : ");
try
{
ch=(char)System.in.read();
}
catch(Exception e)
{
e.getStackTrace();
}
if(ch=='a')
{
System.out.println("Hello World");
}
System.out.println("Learn java with examples.");
}
}
When you will run the above program you will be prompt to enter an alphabet.

Enter an alphabet :

At this point if you type “a” you will get the following output,

Hello World
Learn java with examples.

Instead of typing “a”, if you type any other character you will get the following output,

Learn java with examples.

The java if statement is one of most commonly used type of conditional branching.

No comments:

Post a Comment