Write a java program to demonstrate all the logical and relational operators. Mention the output. Explain in proper way
Answers
Answer:
Java Operators
In this tutorial, you'll learn about different types of operators in Java, their syntax and how to use them with the help of examples.
Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while * is also an operator used for multiplication.
Operators in Java can be classified into 5 types:
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Unary Operators
Bitwise Operators
1. Java Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For example,
a + b;
Here, the + operator is used to add two variables a and b. Similarly, there are various other arithmetic operators in Java.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder after division)
Example 1: Arithmetic Operators
class Main {
public static void main(String[] args) {
// declare variables
int a = 12, b = 5;
// addition operator
System.out.println("a + b = " + (a + b));
// subtraction operator
System.out.println("a - b = " + (a - b));
// multiplication operator
System.out.println("a * b = " + (a * b));
// division operator
System.out.println("a / b = " + (a / b));
// modulo operator
System.out.println("a % b = " + (a % b));
}
}
Output
a + b = 17
a - b = 7
a * b = 60
a / b = 2
a % b = 2
In the above example, we have used +, -, and * operators to compute addition, subtraction, and multiplication operations.
/ Division Operator
Note the operation, a / b in our program. The / operator is the division operator.
If we use the division operator with two integers, then the resulting quotient will also be an integer. And, if one of the operands is a floating-point number, we will get the result will also be in floating-point.
In Java,
(9 / 2) is 4
(9.0 / 2) is 4.5
(9 / 2.0) is 4.5
(9.0 / 2.0) is 4.5
% Modulo Operator
The modulo operator % computes the remainder. When a = 7 is divided by b = 4, the remainder is 3.
Note: The % operator is mainly used with integers.