Java if statement syntax

Contributor Icon Contributed by Rex Date Icon September 7, 2004  
Tag Icon Tagged: 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 recipe describes the variations of the if statement in Java.


The general form of a Java if statement is:

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:

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, although some programmers prefer to use them anyway since it makes it clearer what code is exectued.

Multiple else if conditions can be chained together:

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

Previous recipe | Next recipe |
 
  • Anonymous
    nice job
  • Anonymous
    what about the pipe | in an if statement and other things? I think this leaves out a lot to be had.
  • richie
    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");
    }
  • richie
    thanks and what are the output?
blog comments powered by Disqus