Operators in Java
Operators in Java are special symbols that perform specific operations on one, two, or three operands and then return a result. Here is a comprehensive overview of the different types of operators in Java:
Arithmetic Operators in Java
These operators are used to perform basic mathematical operations.
+
: Addition-
: Subtraction*
: Multiplication/
: Division%
: Modulus (remainder of division)
Unary Operators in Java
Unary operators require only one operand.
+
: Unary plus (Indicates positive value)-
: Unary minus (Negates an expression)++
: Increment (Increases value by 1)++a
: Pre-incrementa++
: Post-increment
--
: Decrement (Decreases value by 1)--a
: Pre-decrementa--
: Post-decrement
!
: Logical complement (Inverts boolean value)
Assignment Operators in Java
These operators are used to assign values to variables.
=
: Simple assignment+=
: Add and assign-=
: Subtract and assign*=
: Multiply and assign/=
: Divide and assign%=
: Modulus and assign&=
: Bitwise AND and assign|=
: Bitwise OR and assign^=
: Bitwise XOR and assign<<=
: Left shift and assign>>=
: Right shift and assign>>>
: Unsigned right shift and assign
Relational Operators in Java
These operators are used to compare two values.
==
: Equal to!=
: Not equal to>
: Greater than<
: Less than>=
: Greater than or equal to<=
: Less than or equal to
Logical Operators in Java
Logical operators are used to combine multiple boolean expressions.
&&
: Logical AND||
: Logical OR!
: Logical NOT
Bitwise Operators in Java
Bitwise operators perform operations on individual bits of integer data types.
&
: Bitwise AND|
: Bitwise OR^
: Bitwise XOR~
: Bitwise complement<<
: Left shift>>
: Right shift>>>
: Unsigned right shift
Ternary Operator in Java
The ternary operator is a shorthand for if-else
statements.
? :
: Ternary (conditional) operator
Syntax:
variable = (condition) ? expressionTrue : expressionFalse;
Instanceof Operator in Java
This operator is used to test whether an object is an instance of a specific class or subclass.
instanceof
: Tests if an object is an instance of a class
Example:
if (obj instanceof String) {
// obj is a String
}
Type Cast Operator in Java
This operator is used to convert data from one type to another.
Syntax:
dataType variableName = (dataType) value;
Example:
int num = (int) 3.14; // Cast double to int
Understanding these operators is crucial for writing efficient and effective Java code.