Cookies Psst! Do you accept cookies?

We use cookies to enhance and personalise your experience.
Please accept our cookies. Checkout our Cookie Policy for more information.

Selections

The program can decide which statements to execute based on a condition. Like all high-level programming languages, Java provides selection statements: statements that let you choose actions with alternative courses. If you enter a negative value for radius, the program displays an invalid result. If the radius is negative, you don’t want the program to compute the area. How can you deal with this situation?

if (radius < 0) {
 System.out.println("Incorrect input");
}
else {
 area = radius * radius * 3.14159;
 System.out.println("Area is " + area);
}

Selection statements use conditions that are Boolean expressions. A Boolean expression is an expression that evaluates to a Boolean value: true or false.

boolean Data Type

The boolean data type declares a variable with the value either true or false. How do you compare two values, such as whether a radius is greater than 0, equal to 0, or less than 0? Java provides six relational operators (also known as comparison operators), which can be used to compare two values.

Image description

The equality testing operator is two equal signs (==), not a single equal sign (=). The latter symbol is for assignment.

The result of the comparison is a Boolean value: true or false. For example, the following statement displays true:

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

A variable that holds a Boolean value is known as a Boolean variable. The boolean data type is used to declare Boolean variables. A boolean variable can hold one of the two values: true or false. For example, the following statement assigns true to the variable lightsOn:

boolean lightsOn = true;

true and false are literals, just like a number such as 10. They are treated as reserved words and cannot be used as identifiers in the program.

Suppose you want to develop a program to let a first-grader practice addition. The program randomly generates two single-digit integers, number1 and number2, and displays to the student a question such as “What is 1 + 7?.” After the student types the answer, the program displays a message to indicate whether it is true or false.

Image description

Last Stories

What's your thoughts?

Please Register or Login to your account to be able to submit your comment.