Java provides six comparison operators (also known as relational operators), which can be used to compared two values. The result of the comparison is a Boolean value; true or false.
double radius = 1;
System.out.println(radius >0);
The above statement will displays true.
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 value; either true or false.
boolean lightsOn = true;
lightsOn is a Boolean variable.
Boolean operators, also known as logical operators, operate on Boolean values to create a new Boolean value.
p
true
false
!P
false
true
import java.util.Scanner;
public class TestBoolean {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("Is " + number);
System.out.println("divisible by 2 and 3? " + (number%2 == 0 && number%3 == 0));
System.out.println("divisible by 2 or 3? " + (number%2 == 0 || number%3 == 0));
System.out.println("divisible by 2 or 3, but not both? " + (number%2 == 0 ^ number%3 == 0));
}
}
Try compile and run the above program. What is the output?
Write a program to determine the leap year. A year is a leap year if it is divisible by 4 but not by 100, or if it is divisible by 400.
public class LeapYear{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a year: ");
// read the input
int year = input.nextInt();
// check if the year is a leap year
boolean isLeapYear =
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
// display the result
if (isLeapYear)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");
}
}