Java Conditional Expressions Fundamentals

JavaJavaBeginner
Practice Now

Introduction

In this lab, we learned basic data types of Java and operators. In this lab, we'll begin to learn to write procedure-oriented programs. The main idea is to use paradigm of controlling structures: conditional expressions.

Conditional Expressions

To write useful programs, we almost always need to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability.

If-Else Conditional Expression

The simplest form is the if-else statement:

Example:

Write the following code in the /home/labex/project/ifelseTest.java file:

public class ifelseTest{
    public static void main(String[] args){
        int x = 1;
        if (x > 0) {
            System.out.println("x is positive");
        }
        else{
            System.out.println("x is non-positive");
        }
    }
}

Output:

Run the ifelseTest.java file using the following commands in the terminal:

javac /home/labex/project/ifelseTest.java
java ifelseTest

See the output:

x is positive

The expression in parentheses is called condition. If it is true, then the statements in braces following if get executed. If the condition is not true, the statements in the braces following else get executed. If no else is pending to visit and the if condition is false, the statements, if any, following the if-else are executed. The condition can contain any of the comparison operators, also called relational operators:

Example:

if (x == y){ }               // x equals y
if (x != y){ }               // x is not equal to y
if (x > y) { }               // x is greater than y
if (x < y) { }               // x is less than y
if (x >= y){ }               // x is greater than or equal to y
if (x <= y){ }               // x is less than or equal to y

Although these operations are probably familiar to you, the syntax Java uses is a little different from mathematical symbols like =, ≠ and ≤. A common error is to use a single equals sign (=) instead of a double equals sign (==). Remember that = is the assignment operator and == is a comparison operator. Also, there is no such thing as =< or =>.

The two sides of a conditional operator have to be the same type. You can only compare ints to ints and doubles to doubles. The operators == and != work with Strings, but they don’t do what you expect. And, the other relational operators don’t operate on strings at all.

An example: If the remainder when x is divided by 2 is 0, then we know that x is even and this code prints a message to that effect. If the condition is false, the second print statement is executed. Since the condition must be true or false, exactly one of the alternatives will be executed. If you think you might want to check the parity (evenness or oddness) of numbers often, you might want to “wrap” this code up in a method, as follows:

Example:

Write the following code in the /home/labex/project/conditionTest.java file:

public class conditionTest
{
    public static void printParity(int x) {
        if (x%2 == 0) {
            System.out.println(x + " is even");
        } else {
              System.out.println(x + " is odd");
        }
    }
    public static void main(String[] args){
        printParity(17);
        printParity(18);
    }
}

Output:

Run the conditionTest.java file using the following commands in the terminal:

javac /home/labex/project/conditionTest.java
java conditionTest

See the output:

17 is odd
18 is even

Now you have a method named printParity that will print an appropriate message for any integer you want to provide. In main, you would invoke this method. Always remember that, when you invoke a method, you do not have to declare the types of the arguments you provide. Java can figure out what types they are. You should resist the temptation to write things like: printParity(int 3). In addition, you can also nest one conditional within another.

Example:

Write the following code in the /home/labex/project/nestedConditionTest.java file:

public class nestedConditionTest{
    public static void main(String[] args){
        int x = 0;  // you can try x = 1, x = -1
        if (x == 0) {
            System.out.println("x is zero");
        }
        else {
            if (x > 0) {
                System.out.println("x is positive");
            }
            else {
                System.out.println("x is negative");
            }
        }
    }
}

Output:

Run the nestedConditionTest.java file using the following commands in the terminal:

javac /home/labex/project/nestedConditionTest.java
java nestedConditionTest

See the output:

x is zero

There is now an outer conditional that contains two branches. The first branch contains a simple print statement, but the second branch contains another conditional statement which has two branches of its own. Both of those branches are print statements, but they could have been conditional statements as well.

Indentation helps make the structure pretty and comprehensible, but nevertheless nested conditionals get difficult to read very quickly. Avoid them when you can. On the other hand, this kind of nested structure is common, and we will see it again. So, you better get used to it.

Switch-Case Conditional Expression

Switch-case statement is another conditional expression. The syntax of switch-case statement is like this:

Example:

// value type can be byte, short, int, char, String, but long type is not correct.
switch (variable or an value expression)
{
    // case value must be a constant value
    case value1:
    // code
    ;
    case value2:
    // code
    ;
    default:
    // code
    ;
}

Example:

Write the following code in the /home/labex/project/switchTest.java file:

public class switchTest
{
    public static void main(String[] args){
    // you can change i = 2, then try again
    int i = 2;
    switch(i)
    {
        case 1:
            System.out.println(1);
            break;
        case 2:
            System.out.println(2);
            // if no break expression, sometimes you'll get a confusing answer.
            // you can try deleting the break expression and see what happens.
            break;
        // if none of the above matches, execute the default statements
        default:
            System.out.println("default");
            break;
        }
    }
}

Output:

Run the switchTest.java file using the following commands in the terminal:

javac /home/labex/project/switchTest.java
java switchTest

See the output:

2

Summary

In this lab, we learned conditional expressions and two styles of conditionals. They are very useful for programming. In the next lab, we'll learn another control structures: recursion and loops.

Other Java Tutorials you may like