Java if-else statement

The if else statement has the following syntax.

if ( condition ) {
// statements 1
} else {
// statements 2
}

If the condition is true, then the first set of statements ( statements 1 ) are executed. Otherwise, the second set of statements ( statements 2 ) are executed.

Here is an example :

if ( num < 3 ) {
System.out.println ( "num is less than 3");
} else {
System.out.println ( "num is greater than or equal to 3");
}

If num is less than 3, the statement “num is less than 3″ is printed on the screen. Otherwise, the statement “num is greater than or equal to 3″ is printed.

If, we have only one statement in the if or else part, we can remove the curly braces. So, the above if-else code can also be qritten in the following three ways.

if ( num < 3 )
System.out.println ( "num is less than 3");
else
System.out.println ( "num is greater than or equal to 3");
if ( num < 3 ) 
System.out.println ( "num is less than 3");
else {
System.out.println ( "num is greater than or equal to 3");
}
if ( num < 3 ) {
System.out.println ( "num is less than 3");
} else
System.out.println ( "num is greater than or equal to 3");

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>