Unary Operators
Unary operators are operators that work on a single operand. Java provides several unary operators:
Increment (++)
Increases the value of the operand by 1.
Example
int a = 5;
a++; // a = 6
Decrement (--)
Decreases the value of the operand by 1.
Example
int a = 5;
a--; // a = 4
Unary plus (+)
Indicates a positive value (has no effect on the operand).
Example
int a = +5; // a = 5
Unary minus (-)
Negates the value of the operand.
Example
int a = 5;
int b = -a; // b = -5
Logical NOT (!)
Inverts the boolean value of the operand.
Example
boolean isTrue = true;
boolean isFalse = !isTrue; // isFalse = false
Note: Unary operators are applied to a single operand & can be used to perform simple operations like incrementing, decrementing, or negating a value.
Assignment Operator
The assignment operator (=) is used to assign a value to a variable. It takes the value on the right side of the operator & assigns it to the variable on the left side.
Example
int age = 25;
In this example, the value 25 is assigned to the variable age using the assignment operator.
Java also provides compound assignment operators that combine an arithmetic operation with an assignment. These operators perform the specified operation on the variable & then assign the result back to the variable.
Compound assignment operators include:
Addition assignment (+=)
Example
int a = 5;
a += 3; // a = 8 (equivalent to a = a + 3)
Subtraction assignment (-=)
Example
int a = 10;
a -= 4; // a = 6 (equivalent to a = a - 4)
Multiplication assignment (*=)
Example
int a = 4;
a *= 2; // a = 8 (equivalent to a = a * 2)
Division assignment (/=)
Example
int a = 10;
a /= 2; // a = 5 (equivalent to a = a / 2)
Modulus assignment (%=)
Example
int a = 10;
a %= 3; // a = 1 (equivalent to a = a % 3)
Note: Assignment operators are essential for storing & updating values in variables throughout your Java programs.
Relational Operators
Relational operators are used to compare two values & determine the relationship between them. They return a boolean value (true or false) based on the comparison result.
Java provides the following relational operators:
Equal to (==)
Checks if two operands are equal.
Example
int a = 5;
int b = 5;
boolean isEqual = (a == b); // isEqual = true
Not equal to (!=)
Checks if two operands are not equal.
Example
int a = 5;
int b = 7;
boolean isNotEqual = (a != b); // isNotEqual = true
Greater than (>)
Checks if the first operand is greater than the second operand.
Example
int a = 10;
int b = 5;
boolean isGreater = (a > b); // isGreater = true
Less than (<)
Checks if the first operand is less than the second operand.
Example
int a = 3;
int b = 7;
boolean isLess = (a < b); // isLess = true
Greater than or equal to (>=)
Checks if the first operand is greater than or equal to the second operand.
Example
int a = 5;
int b = 5;
boolean isGreaterOrEqual = (a >= b); // isGreaterOrEqual = true
Less than or equal to (<=)
Checks if the first operand is less than or equal to the second operand.
Example
int a = 4;
int b = 4;
boolean isLessOrEqual = (a <= b); // isLessOrEqual = true
Note: Relational operators are commonly used in conditional statements & loops to make decisions based on comparisons between values.
Logical Operators
Logical operators are used to combine or negate boolean expressions. They operate on boolean values (true or false) & return a boolean result.
Java provides three logical operators:
Logical AND (&&)
Returns true if both operands are true.
Example
boolean isRaining = true;
boolean isWindy = true;
boolean stayIndoors = isRaining && isWindy; // stayIndoors = true
Logical OR (||)
Returns true if at least one of the operands is true.
Example
boolean isHungry = true;
boolean isThirsty = false;
boolean eatOrDrink = isHungry || isThirsty; // eatOrDrink = true
Logical NOT (!)
Negates the boolean value of the operand.
Example
boolean isLightOn = true;
boolean isDark = !isLightOn; // isDark = false
Logical operators are often used in combination with relational operators to create more complex conditions.
Example
int age = 25;
boolean isStudent = true;
boolean isEligible = (age >= 18) && isStudent; // isEligible = true
In this example, the logical AND operator (&&) is used to check if both conditions (age >= 18 & isStudent) are true.
Note: Logical operators are essential for creating conditional statements & making decisions based on multiple conditions in your Java programs.
Ternary Operator
The ternary operator, also known as the conditional operator, is a shorthand way of writing an if-else statement. It is the only operator in Java that takes three operands.
The syntax of the ternary operator is:
condition ? expression1 : expression2
If the condition evaluates to true, expression1 is evaluated & returned. If the condition evaluates to false, expression2 is evaluated & returned.
Example
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println(status);
Output:
Adult
In this example, the ternary operator checks if age is greater than or equal to 18. If the condition is true, the string "Adult" is assigned to the status variable. If the condition is false, the string "Minor" is assigned to the status variable.
The ternary operator is useful for simple conditional assignments & can make your code more concise & readable.
However, it's important to use the ternary operator judiciously. If the expressions or conditions become too complex, it's often better to use a traditional if-else statement for clarity & maintainability.
Example
int number = 7;
String result = (number % 2 == 0) ? "Even" : "Odd";
System.out.println(result);
Output:
Odd
In this example, the ternary operator is used to determine if a number is even or odd based on the remainder when divided by 2.
Bitwise Operators
Bitwise operators perform operations on individual bits of integer values. They manipulate the binary representation of numbers.
Java provides the following bitwise operators:
Bitwise AND (&)
Performs a bitwise AND operation on each corresponding bit of the operands.
Example
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int result = a & b; // Binary: 0001, Decimal: 1
Bitwise OR (|)
Performs a bitwise OR operation on each corresponding bit of the operands.
Example
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int result = a | b; // Binary: 0111, Decimal: 7
Bitwise XOR (^)
Performs a bitwise XOR (exclusive OR) operation on each corresponding bit of the operands.
Example
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int result = a ^ b; // Binary: 0110, Decimal: 6
Bitwise complement (~)
Inverts all the bits of the operand.
Example
int a = 5; // Binary: 0101
int result = ~a; // Binary: 1010, Decimal: -6
Bitwise operators are often used for low-level operations, such as manipulating flags, masks, or performing bit-level optimizations.
Example:
int flags = 0b0110; // Binary: 0110
int mask = 0b0100; // Binary: 0100
// Check if a specific flag is set
boolean isSet = (flags & mask) != 0; // isSet = true
// Set a specific flag
flags = flags | mask; // Binary: 0110
// Clear a specific flag
flags = flags & ~mask; // Binary: 0010
In this example, bitwise operators are used to perform operations on individual bits of the flags variable, such as checking if a specific flag is set, setting a flag, or clearing a flag.
Note: Bitwise operators can be challenging to understand initially, but they provide powerful capabilities for working with bits & optimizing certain operations.
Shift Operators
Shift operators are used to shift the bits of a number left or right by a specified number of positions. They are useful for performing quick multiplication or division by powers of two.
Java provides three shift operators:
Left shift (<<)
Shifts the bits of the first operand to the left by the number of positions specified by the second operand.
Example
int a = 5; // Binary: 0101
int result = a << 2; // Binary: 010100, Decimal: 20
In this example, the left shift operator (<<) shifts the bits of a to the left by 2 positions, effectively multiplying a by 2^2 (4).
Signed right shift (>>)
Shifts the bits of the first operand to the right by the number of positions specified by the second operand, preserving the sign bit.
Example
int a = -10; // Binary: 11111111111111111111111111110110
int result = a >> 2; // Binary: 11111111111111111111111111111101, Decimal: -3
In this example, the signed right shift operator (>>) shifts the bits of a to the right by 2 positions, effectively dividing a by 2^2 (4) while preserving the sign.
Unsigned right shift (>>>)
Shifts the bits of the first operand to the right by the number of positions specified by the second operand, filling the leftmost positions with zeros.
Example
int a = -10; // Binary: 11111111111111111111111111110110
int result = a >>> 2; // Binary: 00111111111111111111111111111101, Decimal: 1073741821
In this example, the unsigned right shift operator (>>>) shifts the bits of a to the right by 2 positions, filling the leftmost positions with zeros, resulting in a positive value.
Shift operators are commonly used for efficient multiplication or division by powers of two, as well as for manipulating bits in low-level programming.
Note: It's important to note that the second operand of the shift operators should be non-negative and less than 32 for int values (or less than 64 for long values) to avoid undefined behavior.
Frequently Asked Questions
What is the difference between the logical AND (&&) and the bitwise AND (&) operator?
The logical AND (&&) operator evaluates the boolean expressions and returns a boolean result, while the bitwise AND (&) operator performs a bitwise operation on the individual bits of the operands.
Can the ternary operator be nested?
Yes, the ternary operator can be nested, meaning you can use another ternary operator as the expression for the true or false condition. However, nesting ternary operators can reduce code readability, so it should be used sparingly.
What happens if you try to divide an integer by zero using the division operator?
If you try to divide an integer by zero using the division operator, it will throw an ArithmeticException at runtime. It's important to handle division by zero cases appropriately in your code to avoid exceptions.
Conclusion
In this article, we saw various types of operators available in Java. We learned about arithmetic operators for performing mathematical calculations, unary operators for working with a single operand, and the assignment operator for assigning values to variables. We also covered relational operators for comparing values, logical operators for combining boolean expressions, and the ternary operator for concise conditional statements. Additionally, we looked into bitwise operators for manipulating individual bits and shift operators for efficient bit shifting.
You can refer to our guided paths on Code 360. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.