Conditional Statements Homepage « Learn Java5 « Conditional Statements
In this lesson we look at the conditional statements available in Java. Conditional statements allow us to evaluate an expression and execute some code dependant upon the outcome. There are two conditional statements we
can use with Java, the if
statement and the switch
statement; the choice of which to use really depends on the expression being evaluated. There is also the tenary ? :
special operator
which acts like an if
statement and which we will cover after looking in detail at the if
statement.
The if
Statement
Top
Create a conditional expression using one of the relational operators available in Java to test one operand against another or test the result of a logical operation. We can execute one set of statements if the boolean result of the expression evaluates to true
and another if the expression evaluates to false
.
The relational and logical operators are discussed in more detail in the Operators lesson.
The following table shows the different forms of the if
construct that can be used. We are using blocks of code to wrap statements which is optional, but good practice and will be used here.
Construct | Description |
---|---|
Simple if | |
if (condition) { | Execute statements in statement1 if condition expression evaluates to true . |
if....else | |
if (condition) { | Execute statements in statement1 if condition expression evaluates to true ,otherwise execute statements in statement N . |
Nested if | |
if (condition) { | Execute statements in statement1 if condition expression evaluates to true ,Execute statements in statement2 if condition2 expression evaluates to
true ,otherwise execute statements in statement3 if condition2 expression evaluates to false , otherwise execute statements in statement N if condition expression evaluates to false . |
Multiple if....else if | |
if (condition) { | Execute statements in statement1 if condition expression evaluates to true ,
Execute statements in statement2 if condition2 expression evaluates to true , Execute statements in statement3 if condition3
expression evaluates to true etc..., otherwise execute statements in statement N . |
We will go through the different forms of the if
construct one at a time, using some code to make understanding of the above table easier.
Simple if
Construct
Top
In its simplest form, the if
statement will execute the statement or block of code following the conditional expression when the expression evaluates to true
, otherwise execution will continue
after the statement or block of code. Lets look at some code to illustrate how this works:
/*
Simple If Construct
*/
public class SimpleIf {
public static void main (String[] args) {
if (args[0].length() > 0) System.out.println("Command input was: " + args[0]);
if (args[0].length() > 0) {
System.out.println("Command input was: " + args[0]);
}
}
}
Save, compile and run the file in directory c:\_BeginningJava5 in the usual way, but when running the interpreter add a number to the end; for instance java SimpleIf 24

If you have entered something when running the intepreter you should see 2 lines of output as in the screenshot above. We will talk about what args.length
means in the Arrays lesson
but for now it's enough to know that we are checking the args[] string array for input. The first if
construct above doesn't use a block and therefore is limited to a single statement. The second
if
construct above uses a block and therefore can have multiple statements. We are just showing the first if
construct for information purposes. We recommend always using a block
when using any conditional as in the second example as it makes code easier to read, easier to maintain and is not limited to single statements.
if....else
Construct
Top
In this form, the if
statement will execute the statement or block of code following the conditional expression when the expression evaluates to true
, otherwise will execute the statement
or block of code following the else
when the expression evaluates to false
. Lets look at some code to see this in action:
/*
if...else Construct
*/
public class IfElse {
public static void main (String[] args) {
if (args.length > 0) System.out.println("Command input was: " + args[0]);
else System.out.println("No command input was entered");
if (args.length > 0) {
System.out.println("Command input was: " + args[0]);
} else {
System.out.println("No command input was entered");
}
}
}
Save, compile and run the file in directory c:\_BeginningJava5in the usual way, then run the interpreter and add a number to the end; for instance java IfElse 48

If you have run the program twice with and without a parameter you should see 4 lines of output similar to the screenshot above. The first if....else
construct above doesn't use a block and therefore is
limited to a single statement for the if
and else
. The second if....else
construct above uses a block and therefore can have multiple statements for the if
and else
.
We are just showing the first if...else
construct for information purposes. We recommend always using a block
when using any conditional as in the second example as it makes code easier to read,
easier to maintain and is not limited to single statements. We will not be using the first simpler form in any more examples but you can now see how to code the construct this way.
Nested if
Construct
Top
A nested if
statement is the target of another if
or else
statement. With nested if
s the else
statement always refers to the nearest if
statement
that is within the same block of code as the else
and is not already associated with an else
. Lets look at some code:
/*
Nested if Construct
*/
public class NestedIf {
public static void main (String[] args) {
if (args.length > 0) {
int num = Integer.parseInt(args[0]);
if (num > 50) {
if (num > 75) {
System.out.println("Command input was over 75: " + args[0]);
} else {
System.out.println("Command input was over 50 but less than 76: " + args[0]);
}
} else {
System.out.println("Command input was less than 51: " + args[0]);
}
} else {
System.out.println("No command input was entered");
}
}
}
Save, compile and run the file in directory c:\_BeginningJava5in the usual way, then run the intepreter and add a number to the end; for instance java NestedIf 51

If you have run the program twice with and without a parameter you should see 2 lines of output similar to the screenshot above. The message displayed depends which branch of the nested if
construct we branch to. As you can
see we can go in as many levels as we like but even with all that lovely indentation coding multiple nested if
constructs can get complex and confusing although the example above is a bit contrived :).
Multiple if....else
Construct
Top
The nested if
statement can get confusing and out of hand and generally in programming if something looks too complicated there is an easier way to do it.
Lets rewrite part of the nested if
construct above using the multiple if....else if
construct:
/*
Multiple if....else Construct
*/
public class MultipleIfElse {
public static void main (String[] args) {
if (args.length > 0) {
int num = Integer.parseInt(args[0]);
if (num > 75) {
System.out.println("Command input was over 75: " + args[0]);
} else if (num > 50) {
System.out.println("Command input was over 50 but less than 76: " + args[0]);
} else {
System.out.println("Command input was less than 51: " + args[0]);
}
} else {
System.out.println("No command input was entered");
}
}
}
Save, compile and run the file in directory c:\_BeginningJava5in the usual way, then run the intepreter and add a number to the end; for instance java MultipleIfElse 50

If you have run the program twice with and without a parameter you should see 2 lines of output similar to the screenshot above. The message displayed depends which branch of the multiple if....else if
construct
we branch to. This example is easier to follow than the multiple nested if
of the previous example and also illustrates how we can mix the various if
constructs.
The ? :
Operator
Top
The ? :
tenary (takes three operands) operator can be used to replace an if....else
construct of the following form:
Construct | Description |
---|---|
if....else | |
if (condition) { | Assign result of expression1 to
var if condition evaluates to true ,otherwise assign result of expression2 to var. |
? : Operator | |
expression1 ? expression2 : expression3 |
If expression1 returns true evaluate expression2 ,
otherwise evaluate expression3 , |
Lets examine some code to see how the ? :
operator works:
/*
The ? : Operator
*/
public class QuestionMarkOperator {
public static void main (String[] args) {
int int1 = 1234, int2 = 5678, maxInt;
if (int1 > int2) {
maxInt = int1;
}
else {
maxInt = int2;
}
System.out.println("Using an if...else construct maxInt holds a value of: " + maxInt);
maxInt = (int1 > int2) ? int1 : int2;
System.out.println("Using the ? : operator maxInt holds a value of: " + maxInt);
}
}
Save, compile and run the file in directory c:\_BeginningJava5 in the usual way.

You should see 2 lines of output with the same values showing how we can replace this form of the if....else
construct with the ? :
operator.
The switch
Statement
Top
The switch
statement can be used instead of the multiple if....else if
construct above when we are doing a multiway test on the same value. When this scenario arises the switch
statement
is often a more efficient and elegant way to write our code
The switch
statement is where we put the expression we are going to evaluate. Each case
constant is evaluated against the switch
expression and the statements within
the case
are processed on a match. We have the option to break
from the switch
after this if required. We can also code an optional default
statement,
which can act as a kind of catch all and is normally placed, at the end, after the case
statements.
Construct | Description |
---|---|
switch | |
switch (expression) { |
expression can be of type char , byte , short or int .constant1 must be a literal of a type compatible with the
switch expression .Execute statements1 on match.Optional break from switch statement.
constant2 must be a literal of a type compatible with the switch expression .Execute statements2 on match.Optional break from switch statement.constantN must be a literal of a type compatible with the switch expression .Execute statementsN on match.Optional break from switch statement. Optional default statement (catch all).Execute defaultStatements .Optional break from switch statement. |
nested switch | |
switch (expression1) { |
This is perfectly legal. |
Lets examine some code to see how the switch
statement works:
/*
switch Statement
*/
public class UsingSwitch {
public static void main (String[] args) {
int intValue = 33;
// A switch where a case matches.
switch (intValue) {
case 11:
System.out.println("11 matched");
break;
case 22:
System.out.println("22 matched");
break;
case 33:
System.out.println("33 matched");
break;
default:
System.out.println("Default as no case matches");
}
int intValue2 = 4;
// A switch where no case matches.
switch (intValue2) {
case 1:
System.out.println("1 matched");
break;
case 2:
System.out.println("2 matched");
break;
case 3:
System.out.println("3 matched");
break;
default:
System.out.println("Default as no case matches");
}
}
}
Save, compile and run the file in directory c:\_BeginningJava5 in the usual way.

You should see 2 lines of output with the same values as the screenshot above. Its worth mentioning the break
statement and what it does. The break
statement causes the program flow to exit from
the switch
statement and resume at the next statement following the switch
construct. The default
statement is also optional and acts as a bucket to catch anything not covered by the
case
statements; thus the default
statement is generally coded as the last case
within the switch
construct, but can be coded anywhere.
As mentioned the break
statement is optional, so what happens when statement execution within a case
is not ended by a break
statement? Well in this scenario all statements following
the matching case
will be executed until a break
statement or the end of the switch
construct is encountered. Lets see some code examples to clarify this:
/*
switch Statement (break impact)
*/
public class SwitchBreak {
public static void main (String[] args) {
int intValue = 11;
// A switch where a case matches.
switch (intValue) {
case 11:
System.out.println("11 matched");
case 22:
System.out.println("22 matched");
case 33:
System.out.println("33 matched");
default:
System.out.println("Default as no case matches");
}
int intValue2 = 1;
// A switch where no case matches.
switch (intValue2) {
case 1:
System.out.println("1 matched");
case 2:
System.out.println("2 matched");
break;
case 3:
System.out.println("3 matched");
break;
default:
System.out.println("Default as no case matches");
}
}
}
Save, compile and run the file in directory c:\_BeginningJava5 in the usual way.

You should see several lines of output with the same values as the screenshot above. In the first example there are no break
statements in the switch
construct at all. So after hitting the matched case, processing
continues with the next case and proceeds through each case in the switch
construct. In the second example processing continues after the first matched case until the break
statement is encountered at
which point control is passed to the statement following the switch
construct.
Conditional Statements Quiz
Top
Try the quiz below to test your knowledge of this lesson
boolean a = false; if (a = true) {System.out.println("true");} else {System.out.println("false");}
What's Next?
The next lesson is all about the loop statements available in Java.