Logical operators in java with example

Operator Meaning
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
&& logical AND
|| logical OR
! logical NOT

The above 1st 6 are relational operators in java and last 3 are logical operators

The relation operators are used to compare 2 values. The output of relational operators is either true (1) or false (0)

Syntax:-

value1 relational_operator value2


Example:-

2 < 10     True
3 > 8       False
7.5>=5    True

value1 and value2 are can be constants, variable or combination of them.

Relation operator are used in if-else or in loop statement.

Example:-

Program to find Greatest number between 2

import java.util.Scanner;

class group{
public static void main(String arg[]){
int num1, num2;
Scanner grest = new Scanner(System.in);
System.out.println("Enter 1st number");
num1 = grest.nextInt();
System.out.println("Enter 2nd number");
num2 = grest.nextInt();
if(num1 < num2)
System.out.println("Greatest number"+num1);
else
System.out.println("Greatest number"+num2);
}
}

Logical operators:-

logical operators && and || are used to when we want to check 2 or more condition statement.

Example

8 > 7 && 5 < 8      True
8 < 5 || 8 < 9           False
7 > 2 && 19 < 2    False

AND (&&) operator output is true only when either condition statement is true.
OR (||) operator output is false only when either condition statement is false.

Truth table:-


A B AND
0 0 0
0 1 0
1 0 0
1 1 1


A B OR
0 0 0
0 1 1
1 0 1
1 1 1



NOT (!)  logical operator is used for compliment condition statement outputs.

Truth table:-

A NOT
0 1
1 0


Example:-

Program to solve following problem
The candidate is selected if his age and height is 18 and 5 and more respectively.

import java.util.Scanner;
class group{
public static void main(String arg[]){
int age, height;
Scanner data = new Scanner(System.in);
System.out.println("Enter candidate age");
age = data.nextInt();
System.out.println("Enter cadidate height");
height = data.nextInt();
if((age >= 18) && (height >= 5))
System.out.println("The cadidate is selected");
else
System.out.println("sorry, candidate not selected");
}
}

Java program for logical NOT
Program to find max number between 2

import java.util.Scanner;
class group{
public static void main(String arg[]){
int num1,num2;
Scanner data = new Scanner(System.in);
System.out.println("Enter 1st number");
num1 = data.nextInt();
System.out.println("Enter 2nd number");
num2 = data.nextInt();
if(!(num1>num2))
System.out.println("max nuber between 2 is:"+num2);
else
System.out.println("max nuber between 2 is:"+num1);
}
}




Previous Code:-
Arithmetic operators

List Code:-
Java codes

Next Code:-
Bitwise operators

Java Programs:-
List of Java Programs

Leave reply

Add your comments here

Back to Top