3.4 Logical Operators
There are three logical operators in Java: AND, OR and NOT, which are denoted by the symbols &&, || and !. Logical operators can simplify nested conditional statements. For example, following programs determines the greatest of three numbers :
import java.util.Scanner; // Needed for the Scanner class
/**
* This program demonstrates the logical && operator.
*/
public class Maximum
{
public static void main(String[] args)
{
int num1, num2, num3; // holds three integers
int max; // holds maximum value
// Create a Scanner object for keyboard input.
Scanner console = new Scanner(System.in);
// Get theee integers.
System.out.print("Enter three integers : ");
num1 = console.nextInt();
num2 = console.nextInt();
num3 = console.nextInt();
// Determine the maximum number
if ((num1 > num2) && (num1 > num3))
{
max = num1;
}
else if (num2 > num3)
{
max = num2;
}
else
{
max = num3;
}
// Display the maximum number
System.out.println("Maximum is " + max);
}
}
Output:Enter three integers : 10 15 6
Maximum is 15
Maximum is 15
We have solved leap year problem using nested if in previous section. We can simplify the program using logical operators.
import java.util.Scanner; // Needed for the Scanner class
/**
* This program demonstrates &&, || and ! operator.
*/
public class Leapyear
{
public static void main(String[] args)
{
int year; // holds a year
// Create a Scanner object for keyboard input.
Scanner console = new Scanner(System.in);
// Get the year.
System.out.print("Enter a year : ");
year = console.nextInt();
// Determine whether the year is leap year.
if ((year % 4 == 0) && ((year % 400 == 0) || (year % 100 != 0)))
{
System.out.println("A leap year");
}
else
{
System.out.println("Not a leap year");
}
}
}
Output 1
Enter a year : 1992
A leap year
A leap year
Output 2
Enter a year : 2000
A leap year
A leap year
Output 3
Enter a year : 1900
Not a leap year
Not a leap year
Output 4
Enter a year : 2015
Not a leap year
Not a leap year
No comments:
Post a Comment