Java like most programming languages uses the boolean data type to create variables iwth either true or false.
With this type we can use relational operators/comparison operators to compare twi two values. Say you want to compare whether a value is greater than another value.
A variable holding a boolean value is called a Boolean variable.
A boolean variable can hold only either of these two values:
- true
- false
boolean engineStared = true;
boolean planeLiftedOff = false;
The true
and false
are literals, just like say number 20
. Furthermore they are reserved for use by Java so you cannot use them as identifiers.
Let’s look at simple quiz program. This program generates two random numbers using System.currentTimeMillis()
. You then provide the answer. Then we compare your answer with what the true result. This returns true or false.
package info.tutorialsloop;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int firstNum = (int) (System.currentTimeMillis()%10);
int secondNum = (int) (System.currentTimeMillis()/6%10);
int total=firstNum+secondNum;
Scanner input=new Scanner(System.in);
System.out.print("Calculate "+firstNum+" + "+secondNum+" = ");
int answer=input.nextInt();
System.out.println(firstNum+" + "+secondNum + " = "+ answer+" is "+(total == answer));
}
}
You type the answer then press enter to see result.
Here are some interesting answers:
Calculate 3 + 2 = 5
3 + 2 = 5 is true
Calculate 5 + 9 = 12
5 + 9 = 12 is false
Calculate 6 + 9 = 15
6 + 9 = 15 is true
Calculate 1 + 1 = 0
1 + 1 = 0 is false