boolean operatoer conditional relational java

2.1 Java | Using Relational Operators & Booleans

Table of Contents

Introduction to Selections

Java programs have the power to choose which statements to execute depending on conditions.

Let’s start with a situational example. If you remember our Java program for computing the area of a circle, the program should display an invalid result if a negative radius is used. However, if you add a negative number in place of the radius; you’ll find that the program still works. So how do we force the program to reject a negative number for the radius?

We can use selections statements, which are statements that allow you to choose an action depending on a condition. For our previously mentioned situation, let’s try using the if else selection statements:

import java.util.Scanner;

public class ComputeCircleAreaIfPositiveDouble {
    public static void main(String[] args) {
        double radius; //Making variable called radius
        double area; //Making variable called area

        //assign a radius
        System.out.println("Enter a radius for the circle ");
        Scanner input = new Scanner(System.in);
        radius = input.nextDouble();

        // Allow evaluation is radius is positive number
        if (radius < 0) {
            System.out.println("Incorrect input; radius cannot be negative");
        }
        else {
            area = radius * radius * 3.14;
            System.out.println("Circle Radius is " + radius);
            System.out.println("Circle Area is " + area);
        }
    }
}

Output:

Enter a radius for the circle 5 Circle Radius is 5.0 Circle Area is 78.5

Enter a radius for the circle -5 Incorrect input; radius cannot be negative

Note that other than if else statements, selection statements can also use Boolean expressions (true / false) as conditions:

Relational Operators & Boolean Data Type

The boolean data type allows you declare a variable with either true or false values.

You can compare two values by using Java’s 6 relational (or comparison) operators.

Java Operator |  Math Symbol Equiv. | Name                  | Example (Let's say height = 3) | Results
<             |  <                  | less than             | height < 0                     | false
<=            |  ≤                  | less than equal to    | height <= 0                    | false
>             |  >                  | greater than          | height > 0                     | true
>=            |  ≥                  | greater than equal to | height >= 0                    | true
==            |  =                  | equal to              | height == 0                    | false
!=            |  ≠                  | not equal to          | height != 0                    | true

*Note that the relational operator == is not a =. The former is for comparisons, the later is for assignment.

When you use relational/comparison operators, you be given back either a true or false value. For example, the statement below will output a true value:

double height = 1;
System.out.println( height > 0);

Know that a Boolean variable is a variable that carries a Boolean value. A variable is declared as Boolean by using the boolean data type. And these boolean variables can hold either a true or false value. For example, boolean lightsOff = false; assigns false to the variable lightsOff.

Know that just like 11, both true and false are literals. Also know that these two Boolean literals are treated as reserved keywords and therefore cannot take the role of identifiers in Java code.

Example: Addition Quiz True or False

Making a Conditional Addition Quiz Return True or False

Purpose: Let’s say that you are developing a program that allows elementary schoolers practice addition. This program is required to randomly generate 2 single digit integers, num1 & num2. These 2 single digit integers are displayed in the form of a question like “What is 4 + 5?”. After an answer is typed and submitted, the program should return feedback to the user as to whether the submission is true or false.

The first thing we need to figure out is how to randomly generate numbers. One way is to use System.currentTimeMillis() % 10 for the first integer and System.currentTimeMillis() /7 % 10 for the second integer.

Then we can check the user’s answer using the equal to == operator to return feedback true or false.

// import the scanner class so that you Java can read user input
import java.util.Scanner;

// main class
public class TrueOrFalseAdditionQuiz {

	// main method
    public static void main(String[] args) {
	
		// generate random numbers
		// numer 0-1 divided by 10; take remainder
        int num1 = (int)(System.currentTimeMillis() % 10);
		// number 0-1 divided by 7 divided by 10; take remainder
        int num2 = (int)(System.currentTimeMillis() / 7 % 10);
        
        // Make a Scanner object to read user input
        Scanner input = new Scanner(System.in);
        
		// question; prompt user input
        System.out.print("What is " + num1 + " + " + num2 + "? ");
        
		// store user input into answer variable
        int answer = input.nextInt();
        
		// show addition equation and return to user whether the answer is true or false
        System.out.println( num1 + " + " + num2 + " = " + answer + " is " + (num1 + num2 == answer));
    }
}

Extra Notes

= not ==

Just a small memory bridge:

Note that the relational operator == is not a =. the former is for comparisons, the later is for assignment.

  • you = bob; –> “I am Bob”
  • you == bob –> “Am I Bob?”

Read More about = not ==

Yoda Code

A common trick to prevent using the assignment operator instead of the comparison operator is to use “Yoda code”, i.e. to put the literal left of the comparison:

Instead of:

if(x == 2)

use

if(2 == x)

Should you confuse assignment with comparison, the compiler will complain. [Source]


◄◄◄BACK | NEXT►►►

What's Your Opinion?