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 Statementgo to top of page 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) {
    statement1
}

Execute statements in statement1  if condition expression evaluates to true.
if....else
if (condition) {
    statement1
} else {
    statementN
}

Execute statements in statement1  if condition expression evaluates to true,

otherwise execute statements in statement N.
Nested if
if (condition) {
    statement1
    if (condition2) {
        statement2
    } else {
        statement3
    }
} else {
    statement N
}

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) {
    statement1

} else if (condition2) {
    statement2

} else if (condition3) {
    statement3
   ...
} else {
    statement N
}

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 Constructgo to top of page 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

run simple if

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 Constructgo to top of page 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

run if else

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 Constructgo to top of page Top

A nested if statement is the target of another if or else statement. With nested ifs 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

run nested if

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 Constructgo to top of page 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

run multi if else

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 ? : Operatorgo to top of page 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) {
    var = expression1;
} else {
    var = expression2;
}

Assign result of expression1 to var  if condition evaluates to true,

otherwise assign result of expression2 to var.
? : Operator
expression1 ? expression2 : expression3
  • expression1 can be any expression that returns a boolean value.
  • expression2 and expression3 can be any returned type apart from void.
  • expression2 and expression3 must be of the same type.

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.

run ? operator

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 Statementgo to top of page 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) {
   case constant1:
      statements1
      [break;]

   case constant2:
      statements2
      [break;]
   ...

   case constantN:
      statementsN
      [break;]

   default:
      defaultStatements
      [break;]
}
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) {
   case constant1:
      switch (expression2) {
         case constant1:
         statements1
         [break;]
          ...
      } // end of inner switch

      [break;]
   ...
   default:
       defaultStatements
      [break;]
}


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.

run switch 2

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.

run switch 1

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 Quizgo to top of page Top

Try the quiz below to test your knowledge of this lesson

Question 1 : What will be output from this code snippet?

boolean a = false; if (a = true) {System.out.println("true");} else {System.out.println("false");}
- The snippet will output true. This is because if ( a = true) actually assigns true to 'a'.<br />if ( a == true) would check 'a' for equality and return false.
Question 2 : When would we branch to else in an simple if...else construct?
- When the condition expression returns 'false' we branch to 'else'.
Question 3 : What will be output from this code snippet?

long intValue = 1;
switch (intValue) {
case 1:
System.out.print(" 1 matched");
case 2:
System.out.print(" 2 matched");
break;
default:
System.out.println(" Default as no case matches");
}
- The snippet will not compile as <code>long</code> is not a valid type for a <code>switch</code> expression.
Question 4 : What will be output from this code snippet?

int intValue = 3;
// A switch where a case matches.
switch (intValue) {
default:
System.out.print(" Default as no case matches");
case 1:
System.out.print(" 1 matched");
case 2:
System.out.print(" 2 matched");
}
- The <code>default</code> statement can appear anywhere.<br />In this case it appears first and as no <code>break</code> the rest of the <code>switch</code> is processed
Question 5 : What will be output from this code snippet?

int a = 20, b = 20; if (a & b) {System.out.println("Result was true");}
- The result of an <code>if</code> conditional expression must be a boolean and therefore requires use of a relation operator or logical operands. <br />In this case <code>(a & b)</code> returns an <code>int</code> from a bitwise operation.
Question 6 : What will be output from this code snippet?

char charValue = 'C';
switch (charValue) {
case A:
System.out.print(" A matched");
case B:
System.out.print(" B matched");
break;
default:
System.out.print(" Default as no case matches");
}
- This will not compile as the <code>case</code> checks need to be integers or enclosed in single quotes to compare against the <code>char</code> type.
Question 7 : How many operands does the ? : operator take?
- The <code>? :</code> operator is known as a <code>tenary</code> operator as it takes three operands.
Question 8 : What will be be the value of maxInt after this code snippet is run?

int int1 = 1234, int2 = 5678, maxInt; maxInt = (int1 > int2) ? 111 : 222;
- <code>maxInt</code> will hold the value 222 as the result of <code>(int1 > int2)</code> is <code>false</code> and therefore 222 gets assigned.
Status Bar Please select an answer

What's Next?

The next lesson is all about the loop statements available in Java.

<<  Bitwise Operators                    Loop Statements  >>

go to home page Java5 Tutor Homepage go to top of page Top