Operators in Java
Operators in Java
Operators in Java
Operands are data values, which are involved in the operation. They can be
variables or constants.
Example: x*y+z
Unary Operators
These operators operate on only one operand.
Ex: +y, x++, --m, -r
Unary Plus (+): The Operator unary plus (+) is written before the operand. This
operator results in the same value of the variable.
Unary Minus (˗): The Operator unary minus(-) is also written before the operand.
This operator inverts the value of an operand, i.e., if an operand is a positive value,
it converts the value of that operand to its negative value and vice versa.
Postfix Decrement (x--): It evaluates the expression, and then decreases the value
of operand by 1.
Ex: int p=10; r=p--; r will store the value 10
the original value of p i.e., 10 will be assigned to variable r and then p will be
decreased by 1.
Types of Operators:
• Arithmetic Operator
• Relational Operator
• Logical Operator
• Assignment Operator
• Increment Decrement
• Short Hand Operators
Binary Arithmetic Operators: Operators that act upon two operands are known as
Binary Operators.
Result:
Operator Symbol Meaning Examples
If x=12 and y=4
Addition + Adds two operands x+y 16
Subtraction - Subtract right operand from the left x-y 8
Multiplication * Multiply two operands x*y 48
Division / Divide left Operand by the right one x/y 3
Remainder of the division of left
Modulus % x%y 0
operand by the right
Relational Operators: Relational Operators are used to show the relationship
between the operands. These Operators compare the values of variables and
determine the result in the boolean expression format, which means either true or
false. Java provides 6 types of relational operators.
Logical Operators in Java
Shorthand Operators/Compound Assignment Operators.
Ternary operator
The Ternary Operator (?:) is also known as a conditional operator. This operator
needs three operands to perform an operation.
Here, test condition is evaluated first. If it evaluates to true then the variable
contains the value of Expression 1, otherwise, it will contain the value of
expression 2.
res=(a>b)? a:b;
Precedence of Operator
() []
++ -- !
== !=
&&
||
?: