Menu
Courses / Java Basic / operators

operators

03 / 10 Part of Java Basic

What Are Operators?


Operators are special symbols that perform operations on variables and values. Java groups operators into several categories: arithmetic, assignment, comparison, logical, and unary operators.



Arithmetic Operators



   
   
       
       
       
       
       
   
OperatorDescriptionExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division10 / 33 (integer division)
%Modulus (remainder)10 % 31



    Important: When both operands are integers, / performs integer division and truncates the decimal part. 10 / 3 gives 3, not 3.33. To get a decimal result, make at least one operand a double: 10.0 / 3 gives 3.333....


Assignment Operators


int x = 10;
x += 5;   // x = x + 5  -> 15
x -= 3;   // x = x - 3  -> 12
x *= 2;   // x = x * 2  -> 24
x /= 4;   // x = x / 4  -> 6
x %= 4;   // x = x % 4  -> 2


Comparison (Relational) Operators


These always evaluate to a booleantrue or false.



   
   
       
       
       
       
       
       
   
OperatorMeaningExample
==Equal to5 == 5 → true
!=Not equal to5 != 3 → true
>Greater than5 > 3 → true
<Less than5 < 3 → false
>=Greater than or equal to5 >= 5 → true
<=Less than or equal to3 <= 5 → true


Logical Operators


Used to combine multiple boolean expressions.



   
   
       
       
       
   
OperatorMeaningExample
&&AND — true only if both sides are true(5 > 3) && (2 < 4) → true
||OR — true if at least one side is true(5 > 3) || (2 > 4) → true
!NOT — reverses the boolean value!(5 > 3) → false


Unary Operators


int a = 5;
a++;   // post-increment, a becomes 6
a--;   // post-decrement, a becomes 5 again
-a;    // negation, gives -5
!true; // logical negation, gives false



    Note: a++ (post-increment) returns the original value before incrementing, while ++a (pre-increment) increments first and then returns the new value. This distinction matters when used inline in expressions.


Operator Precedence


Just like in math, some operators are evaluated before others. Multiplication and division happen before addition and subtraction unless parentheses say otherwise:


int result = 2 + 3 * 4;   // 14, not 20
int result2 = (2 + 3) * 4; // 20



    Coming up next: Learn how to make decisions in your code using if-else statements and switch expressions.