Java if statement syntax

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");
}

David Kirk
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.
RELATED ARTICLES

12 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments

Cleveland Furia on How to Clear Google Activity
Sid Wohlfarth on How to Clear Google Activity
Riley Magsayo on How to Clear Google Activity
สมัครรับเครดิตฟรี ทันที on How to improve Remote Desktop Protocol Performance
Neal Wangstad on How to Clear Google Activity
Slavcho Andov on How to install Ubuntu
Slavcho Andov on How to fix bad sectors
Sheraz Ali on How to Backup Android