OPERATORS IN JAVA
1. Operators
• Operators are symbols used to perform operations on variables and values.
• Example: + , - , * , / , %
2. Arithmetic Operators
Operator Use
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)
Use of % with int and float
• With int → gives integer remainder
• 10 % 3 = 1
• With float → gives decimal remainder
• 10.5 % 2 = 0.5
3. Types of Operators Based on Operands
Unary Operator
• Works on one operand
Example:
++a, --a,
-a, +a(positive and negative numbers)
Binary Operator
• Works on two operands
Example:
a + b, x > y
Ternary Operator
• Works on three operands
• Also called conditional operator
Syntax
condition ? value1 : value2
Conversion
if–else
if(a > b)
max = a;
else
max = b;
Ternary
max = (a > b) ? ((a>c)?a:c) : (b>c)?b:c;
Conversion
if (a > b && a > c)
max = a;
else if (b > c)
max = b;
else
max = c;
4. Unary Increment and Decrement Operators
Operator Meaning
++ Increment by 1
-- Decrement by 1
Prefix Notation
• Value changes before use
++a;
Postfix Notation
• Value changes after use
a++;
5. Counter
• Variable used to count occurrences
• Uses increment or decrement
Example:
count++;
6. Accumulator
• Variable used to store total or sum
• Uses + or other arithmetic operators
Example:
sum = sum + n;
7. Shorthand Notation
• Short form of assignment and arithmetic operators
Shorthand Meaning
+= a=a+b
-= a=a-b
*= a=a*b
/= a=a/b
8. Relational Operators
• Used to compare two values
• Result is always true or false
Operators
> , < , >= , <= , == , !=
Syntax
a>b
9. Logical Operators
• Used to combine conditions
• Result is true or false
Operator Meaning Example
&& AND a>5 && b<10
|| OR a>5 || b<10
! NOT !(a>b)
10. Dot (.) Operator
• Used to access members of a class
Example:
[Link]();
11. new Operator
• Used to create an object
• Allocates memory at runtime
Example:
Student s = new Student();
12. Precedence of Operators
(Order of execution)
1. Parentheses ( )
2. Arithmetic * / %
3. Arithmetic + -
4. Relational < > <= >= == !=
5. Logical !
6. Logical &&
7. Logical ||
8. Assignment =
13. + Operator as Concatenation
• Used to join string with values
Example:
[Link]("Sum = " + total);
14. Assignment Operator
• Used to assign value to a variable
Example:
a = 10;
15. Difference Between == and =
= ==
Assignment operator Relational operator
Assigns value Compares values
Example: a = 5; Example: a == b