Java if statement syntax

   Posted September 7, 2004 by David Kirk in Java programming

The if statement is a fundamental programming contruct. If allows a program to execute different blocks of code, depending on the result of a test. This tech-recipe describes the variations of the if statement in Java.


The general form of a Java if statement is as follows:

if (statement) {
code_block_true;
} else {
code_block_false;
}

where statement is anything that evaluates as a boolean value. If the statement is true, then the Java code in the “code_block_true” block is executed. Otherwise, the code in “code_block_false” is executed. The else statement is optional, so the simplest example of the if statement is the following:

if ( x == 1 ) {
System.out.println("yep, x is one.");
}

A block of code is either a single line of code or several lines of code contained in curly braces. Note that, in this example, enclosing the code in curly braces is not required. However, some programmers prefer to use them anyway since it makes it clearer what code is exectued.

Multiple else if conditions can be chained together as follows:

if ( x == 1 )
System.out.println("one");
else if ( x > 1 ) {
y = x*2;
System.out.println("many");
} else {
y = -x;
System.out.println("negative");
}

 

About David Kirk

David Kirk is one of the original founders of tech-recipes and is currently serving as editor-in-chief. Not only has he been crafting tutorials for over ten years, but in his other life he also enjoys taking care of critically ill patients as an ICU physician.
View more articles by David Kirk

The Conversation

Follow the reactions below and share your own thoughts.