JAVA OPERATORS |
A Comprehensive Guide to Java Operators
Java operators are special symbols in Java that perform specific operations on
one, two, or three operands, and then return a result. In this blog, we will
be discussing the different types of operators in Java and their usage with
examples.
There are several types of operators in Java, including:
1) Arithmetic Operators: These operators are used for mathematical operations such as addition, subtraction, multiplication, and division.
2) Comparison Operators: These operators are used to compare two values and return a boolean value based on the comparison. Examples include the equal to (==) operator and the not equal to (!=) operator.
3) Logical Operators: These operators are used to combine multiple Boolean expressions and return a single Boolean result. Examples include the AND (&&) operator and the OR (||) operator.
4) Ternary Operator: This operator is used as a shorthand for an if-else statement. It takes three operands and returns the second operand if the first operand is true, and the third operand if the first operand is false.
5) Bitwise Operators: These operators are used to perform operations on the individual bits of a number. Examples include the AND (&) operator and the OR (|) operator.
6) Assignment Operators: These operators are used to assign values to variables. The most basic assignment operator is the equal (=) operator.
7) Unary Operators: These operators perform operations on only one operand. Examples include the increment (++) operator and the decrement (--) operator.
8) Shift Operators: These operators are used to shift the bits of a number left or right.
Examples include the left shift (<<) operator and the right shift
(>>) operator.
Table:
1) Arithmetic Operators:
int x = 5, y = 2; System.out.println(x + y); // 7 System.out.println(x - y); // 3 System.out.println(x * y); // 10 System.out.println(x / y); // 2 System.out.println(x % y); // 1
2) Comparison Operators:
int x = 5, y = 2; System.out.println(x == y); // false System.out.println(x != y); // true System.out.println(x > y); // true System.out.println(x < y); // false System.out.println(x >= y); // true System.out.println(x <= y); // false
boolean a = true, b = false; System.out.println(a && b); // false System.out.println(a || b); // true
int x = 5, y = 2; int max = (x > y) ? x : y; System.out.println(max); // 5
5) Bitwise Operators:
int x = 5, y = 2; System.out.println(x & y); // 0 System.out.println(x | y); // 7
6) Assignment Operators:
int x = 5, y = 2; x += y; System.out.println(x); // 7
7) Unary Operators:
int x = 5; System.out.println(++x); // 6 System.out.println(x--); // 6
8) Shift Operators:
int x = 8; System.out.println(x << 1); // 16
Please note that the examples are for demonstration purpose and
might not serve any practical use in a real-world scenario.
Tags