Java operators are symbols that are used to perform operations on variables and values. They are classified into different categories based on their functionality.
Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, and division. The following table shows the arithmetic operators in Java:
Operator | Description | Example |
---|---|---|
Addition | int result = 10 5; | |
- | Subtraction | int result = 10 - 5; |
* | Multiplication | int result = 10 * 5; |
/ | Division | int result = 10 / 5; |
% | Modulus | int result = 10 % 5; |
Assignment operators are used to assign values to variables. The following table shows the assignment operators in Java:
Operator | Description | Example |
---|---|---|
= | Assign | int x = 10; |
= | Add and assign | x = 5; |
-= | Subtract and assign | x -= 5; |
*= | Multiply and assign | x *= 5; |
/= | Divide and assign | x /= 5; |
%= | Modulus and assign | x %= 5; |
Comparison operators are used to compare two values. The result of a comparison operator is a boolean value (true or false). The following table shows the comparison operators in Java:
Operator | Description | Example |
---|---|---|
== | Equal to | if (x == y) |
!= | Not equal to | if (x != y) |
> | Greater than | if (x > y) |
< | Less than | if (x < y) |
>= | Greater than or equal to | if (x >= y) |
<= | Less than or equal to | if (x <= y) |
Logical operators are used to combine two or more conditions. The following table shows the logical operators in Java:
Operator | Description | Example |
---|---|---|
&& | Logical AND | if (x > 5 && y < 10) |
|| | Logical OR | if (x > 5 || y < 10) |
! | Logical NOT | if (!(x > 5)) |
Bitwise operators are used to perform operations on individual bits of a number. The following table shows the bitwise operators in Java:
Operator | Description | Example |
---|---|---|
& | Bitwise AND | int result = 10 & 5; |
| | Bitwise OR | int result = 10 | 5; |
^ | Bitwise XOR | int result = 10 ^ 5; |
~ | Bitwise NOT | int result = ~10; |
<< | Left shift | int result = 10 << 2; |
>> | Right shift | int result = 10 >> 2; |
The conditional operator (?:) is used to assign a value to a variable based on a condition. The syntax of the conditional operator is:
variable = (condition) ? value1 : value2;
If the condition is true, value1 is assigned to the variable. If the condition is false, value2 is assigned to the variable.
The instanceof operator is used to check if an object is an instance of a particular class. The syntax of the instanceof operator is:
object instanceof class
If the object is an instance of the class, the result is true. Otherwise, the result is false.
Java operators are an essential part of the Java programming language. They are used to perform various operations on variables and values. Understanding the different types of operators and their functionality is crucial for writing efficient and effective Java code.