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
1 2 |
boolean engineStared = true; boolean planeLiftedOff = false; |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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)); } } |
Here are some interesting answers:
1 2 3 4 5 6 7 8 9 10 11 12 |
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 |
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT