Operators & Expressions
Goal of this chapter: Learn how Java performs calculations, comparisons, assignments, logical operations, and other transformations on values. Operators are the tools that let a program actually do something with the variables you learned in Chapter 3.
We will go from very simple arithmetic to important Java behavior such as integer division, type promotion, precedence, short-circuit evaluation, bitwise operators, and the ternary operator.
1. What Is an Operator?#
An operator is a symbol or keyword that tells Java to perform an operation.
For example:
int result = 10 + 20;
Here:
10
↓
operand
+
↓
operator
20
↓
operand
The + operator tells Java to add the two values.
Result:
30
So:
Operand + Operator + Operand
forms an expression.
2. What Is an Operand?#
An operand is a value that an operator works on.
Example:
10 + 20
Here:
10 → operand
+ → operator
20 → operand
Another example:
age > 18
Here:
age → operand
> → operator
18 → operand
3. What Is an Expression?#
An expression is a piece of Java code that produces a value.
Examples:
10 + 20
produces:
30
Another:
age > 18
produces:
true
Another:
price * quantity
produces a numeric result.
Expressions are everywhere in Java.
4. Example#
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 20;
int result = a + b;
System.out.println(result);
}
}
Output:
30
The expression:
a + b
produces:
30
which is then assigned to:
result
5. Types of Operators in Java#
Java provides many kinds of operators.
A useful classification is:
Java Operators
│
├── Arithmetic
│
├── Unary
│
├── Assignment
│
├── Relational
│
├── Equality
│
├── Logical
│
├── Bitwise
│
├── Shift
│
├── Conditional / Ternary
│
└── instanceof
Some operators can be used in more than one context.
We will learn them one by one.
6. Arithmetic Operators#
Arithmetic operators are used for mathematical calculations.
Java's basic arithmetic operators are:
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
Example:
int a = 20;
int b = 6;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / b);
System.out.println(a % b);
Output:
26
14
120
3
2
Notice something important:
20 / 6 = 3
20 % 6 = 2
because both operands are integers.
We will study this carefully.
7. Addition +#
The + operator adds values.
int a = 10;
int b = 20;
int result = a + b;
System.out.println(result);
Output:
30
It can also work with floating-point values:
double x = 10.5;
double y = 2.5;
System.out.println(x + y);
Output:
13.0
8. Addition With Characters#
A char can participate in numeric expressions.
Example:
char ch = 'A';
System.out.println(ch + 1);
Output:
66
Why?
Because 'A' has numeric value 65, and:
65 + 1 = 66
If you want the resulting numeric value converted back to a character:
char ch = 'A';
char next = (char) (ch + 1);
System.out.println(next);
Output:
B
9. Subtraction -#
Example:
int a = 20;
int b = 8;
System.out.println(a - b);
Output:
12
Subtraction can also produce negative values:
int result = 5 - 10;
System.out.println(result);
Output:
-5
10. Multiplication *#
Example:
int price = 100;
int quantity = 5;
int total = price * quantity;
System.out.println(total);
Output:
500
Multiplication is especially useful when working with quantities, dimensions, rates, and mathematical calculations.
11. Division /#
Example:
int a = 20;
int b = 5;
System.out.println(a / b);
Output:
4
But integer division has an important rule.
12. Integer Division#
Consider:
int a = 20;
int b = 6;
System.out.println(a / b);
Output:
3
You may expect:
3.333333...
but both operands are integers.
Therefore Java performs integer division.
The fractional part is discarded.
20 / 6
mathematical result:
3.333...
integer result:
3
This is one of the most common beginner mistakes.
13. How to Get a Decimal Result#
At least one operand must be a floating-point value.
Example:
int a = 20;
double b = 6;
System.out.println(a / b);
Output:
3.3333333333333335
Or:
double result = (double) a / b;
Now the calculation is performed in floating-point arithmetic.
14. A Very Common Mistake#
Consider:
int a = 5;
int b = 2;
double result = a / b;
System.out.println(result);
Many beginners expect:
2.5
But the output is:
2.0
Why?
Because:
a / b
is evaluated first.
Both are integers:
5 / 2
↓
2
Then the integer result is converted to double:
2
↓
2.0
Correct:
double result = (double) a / b;
Output:
2.5
15. Remainder Operator %#
The % operator gives the remainder after division.
Example:
int result = 20 % 6;
System.out.println(result);
Output:
2
Because:
20 = 6 × 3 + 2
So:
20 % 6 = 2
16. Why Is % Useful?#
The remainder operator is extremely useful.
For example, to check whether a number is even:
int number = 10;
System.out.println(number % 2 == 0);
Output:
true
Why?
10 % 2 = 0
For an odd number:
int number = 11;
System.out.println(number % 2 == 0);
Output:
false
17. % Can Be Used for Cycles#
Suppose you want values to repeat from 0 to 4.
You can use:
int value = number % 5;
For example:
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0
6 % 5 = 1
7 % 5 = 2
This is useful in:
round-robin systems
circular indexing
repeating patterns
turn-based games
cyclic counters
18. % With Negative Numbers#
Java's integer remainder follows the sign of the dividend.
Example:
System.out.println(-10 % 3);
System.out.println(10 % -3);
Output:
-1
1
This is different from mathematical modulo definitions used in some contexts.
For a mathematical non-negative modulo, methods such as:
Math.floorMod(...)
can be more appropriate.
19. Division by Zero#
Integer division by zero is invalid.
Example:
int x = 10;
int y = 0;
System.out.println(x / y);
This throws:
ArithmeticException
at runtime.
The same applies to integer remainder:
10 % 0
20. Floating-Point Division by Zero#
Floating-point behavior is different.
For example:
double x = 10.0;
double y = 0.0;
System.out.println(x / y);
This produces:
Infinity
rather than an ArithmeticException.
You may also encounter:
NaN
for operations such as:
0.0 / 0.0
This is one reason floating-point arithmetic must be understood separately from integer arithmetic.
21. Unary Operators#
A unary operator works on one operand.
Examples include:
+
-
++
--
!
~
We will focus on the most important ones.
22. Unary Plus +#
Example:
int x = 10;
int y = +x;
System.out.println(y);
Output:
10
Unary + generally does not change a numeric value.
It is rarely needed explicitly.
23. Unary Minus -#
Unary - changes the sign of a numeric expression.
Example:
int x = 10;
int y = -x;
System.out.println(y);
Output:
-10
Another:
int x = -10;
System.out.println(-x);
Output:
10
24. Increment Operator ++#
The increment operator increases a variable by one.
Example:
int x = 10;
x++;
System.out.println(x);
Output:
11
Conceptually:
x++;
is similar to:
x = x + 1;
when used as a standalone statement.
25. Decrement Operator --#
The decrement operator decreases a variable by one.
int x = 10;
x--;
System.out.println(x);
Output:
9
Conceptually:
x--;
is similar to:
x = x - 1;
when used as a standalone statement.
26. Prefix Increment#
Consider:
int x = 10;
int y = ++x;
System.out.println(x);
System.out.println(y);
Output:
11
11
The important idea is:
++x
↓
increment first
↓
then use the value
So:
x = 10
++x
↓
x becomes 11
↓
11 is used
27. Postfix Increment#
Now:
int x = 10;
int y = x++;
System.out.println(x);
System.out.println(y);
Output:
11
10
The idea is:
x++
↓
use old value first
↓
then increment x
So:
x = 10
y = x++
↓
y gets 10
↓
x becomes 11
28. Prefix vs Postfix#
Remember:
++x
↓
increment first
x++
↓
use first, increment after
Similarly:
--x
↓
decrement first
x--
↓
use first, decrement after
29. Example With Prefix and Postfix#
int x = 5;
System.out.println(++x);
System.out.println(x++);
System.out.println(x);
Step by step:
Initially:
x = 5
First:
++x
becomes:
x = 6
output = 6
Second:
x++
outputs the old value:
output = 6
then:
x = 7
Final:
7
Output:
6
6
7
30. Avoid Overcomplicated Increment Expressions#
You may see code such as:
int x = 5;
int result = x++ + ++x;
Although Java defines evaluation rules, such expressions are unnecessarily difficult to read.
Prefer:
x++;
x++;
int result = ...;
Clear code is better than clever code.
This becomes especially important in production code.
31. Assignment Operator =#
The assignment operator:
=
assigns a value to a variable.
Example:
int age = 20;
Here:
20
↓
assigned to
↓
age
Another:
age = 21;
The current value of age becomes:
21
32. Assignment Is Not Equality#
This is extremely important.
In Java:
=
means:
assignment
while:
==
means:
equality comparison
Example:
int x = 10;
assigns 10.
But:
x == 10
asks:
Is
xequal to10?
The result is a boolean.
33. Compound Assignment Operators#
Java provides:
+=
-=
*=
/=
%=
Example:
int x = 10;
x += 5;
Now:
x = 15
Conceptually:
x += 5;
is similar to:
x = x + 5;
34. More Compound Assignment Examples#
int x = 20;
x -= 5;
System.out.println(x);
x *= 2;
System.out.println(x);
x /= 3;
System.out.println(x);
x %= 4;
System.out.println(x);
The operations happen sequentially.
Compound assignments are convenient and also have special implicit-conversion behavior that ordinary assignment does not.
We will see that shortly.
35. Compound Assignment and Casting#
Consider:
byte x = 10;
x += 5;
This is valid.
But:
byte x = 10;
x = x + 5;
does not compile without a cast.
Why?
Because:
x + 5
is promoted to int.
But compound assignment:
x += 5;
includes an implicit conversion back to the type of the left-hand variable, subject to the language rules.
This is convenient but can hide narrowing behavior.
For example:
byte x = 127;
x += 1;
System.out.println(x);
Output:
-128
So compound assignment does not magically prevent overflow.
36. Relational Operators#
Relational operators compare values.
Common relational operators are:
>
<
>=
<=
The result is a boolean.
Example:
int age = 20;
System.out.println(age > 18);
Output:
true
37. Greater Than >#
int a = 20;
int b = 10;
System.out.println(a > b);
Output:
true
Because:
20 > 10
is true.
38. Less Than <#
int a = 10;
int b = 20;
System.out.println(a < b);
Output:
true
39. Greater Than or Equal >=#
int age = 18;
System.out.println(age >= 18);
Output:
true
Because:
18 >= 18
is true.
40. Less Than or Equal <=#
int age = 17;
System.out.println(age <= 18);
Output:
true
41. Equality Operators#
Java uses:
==
!=
== checks equality.
!= checks inequality.
Example:
int a = 10;
int b = 10;
System.out.println(a == b);
System.out.println(a != b);
Output:
true
false
42. Logical Operators#
Logical operators combine boolean expressions.
The most important ones are:
&&
||
!
They are used heavily in conditions.
43. Logical AND &&#
&& means logical AND.
The result is true only when both sides are true.
Truth table:
A B A && B
----------------------
true true true
true false false
false true false
false false false
Example:
int age = 20;
boolean citizen = true;
System.out.println(age >= 18 && citizen);
Output:
true
Both conditions are true.
44. Logical OR ||#
|| means logical OR.
It is true when at least one side is true.
Truth table:
A B A || B
----------------------
true true true
true false true
false true true
false false false
Example:
boolean weekend = false;
boolean holiday = true;
System.out.println(weekend || holiday);
Output:
true
At least one condition is true.
45. Logical NOT !#
! reverses a boolean value.
boolean loggedIn = true;
System.out.println(!loggedIn);
Output:
false
Another:
boolean active = false;
System.out.println(!active);
Output:
true
Think:
!true → false
!false → true
46. Combining Logical Operators#
Example:
int age = 20;
boolean citizen = true;
boolean hasId = true;
boolean allowed = age >= 18 && citizen && hasId;
System.out.println(allowed);
Output:
true
The expression asks:
Is age >= 18?
AND
Is citizen true?
AND
Is hasId true?
All must be true.
47. Short-Circuit Evaluation#
This is an extremely important Java concept.
For:
&&
Java stops evaluating as soon as the left side is false.
For:
||
Java stops evaluating as soon as the left side is true.
This is called short-circuit evaluation.
48. Short-Circuit && Example#
int x = 10;
if (x < 5 && x / 0 > 1) {
System.out.println("Hello");
}
The left side:
x < 5
is:
false
Because && needs both sides to be true, Java does not need to evaluate the right side.
Therefore:
x / 0
is not evaluated.
This prevents an ArithmeticException.
49. Short-Circuit || Example#
int x = 10;
if (x > 5 || x / 0 > 1) {
System.out.println("Hello");
}
The left side:
x > 5
is true.
Because || is already guaranteed to be true, Java does not evaluate the right side.
Output:
Hello
No division-by-zero occurs.
50. Why Short-Circuiting Is Useful#
It is useful for both performance and safety.
A common pattern:
if (user != null && user.isActive()) {
}
Java checks:
user != null
first.
If it is false, the second part is not evaluated.
This prevents trying to call:
user.isActive()
when user is null.
This is one of the most common practical uses of &&.
51. && vs &#
Do not confuse:
&&
with:
&
&& is logical AND with short-circuit behavior.
& is primarily a bitwise AND for integral values and also has a boolean form that evaluates both operands.
Example:
boolean a = false;
boolean b = true;
System.out.println(a && b);
System.out.println(a & b);
Both produce:
false
but their evaluation behavior differs.
52. Demonstrating the Difference#
Consider:
boolean result = false && someMethod();
someMethod() is not called because the left side is already false.
But:
boolean result = false & someMethod();
evaluates both operands.
So:
&&
↓
short-circuit logical AND
&
↓
evaluates both sides
Use && when you mean logical short-circuit AND.
53. || vs |#
Similarly:
||
is short-circuit logical OR.
|
is bitwise OR for integer operands and also has a boolean form that evaluates both operands.
Example:
boolean a = true;
boolean b = false;
System.out.println(a || b);
System.out.println(a | b);
Both produce:
true
But evaluation behavior differs.
54. Relational Operators Return Boolean Values#
Consider:
int age = 20;
boolean adult = age >= 18;
The expression:
age >= 18
produces:
true
and that value is stored in:
adult
This is an important programming pattern:
Expression
↓
boolean result
↓
stored in variable
55. Boolean Variables Make Code Clearer#
Instead of writing:
if (age >= 18 && hasId && citizen) {
}
you can sometimes write:
boolean eligible = age >= 18 && hasId && citizen;
if (eligible) {
}
This can make complex logic easier to understand.
56. Ternary Operator ?:#
The ternary operator is a compact conditional expression.
Syntax:
condition ? valueIfTrue : valueIfFalse
Example:
int age = 20;
String result = age >= 18 ? "Adult" : "Minor";
System.out.println(result);
Output:
Adult
The expression means:
If age >= 18
↓
"Adult"
otherwise
↓
"Minor"
57. Ternary Operator as an Expression#
Unlike an if statement, the ternary operator produces a value.
Example:
int a = 10;
int b = 20;
int max = a > b ? a : b;
System.out.println(max);
Output:
20
This is useful when choosing between two values.
58. Do Not Overuse the Ternary Operator#
This is readable:
String result = age >= 18 ? "Adult" : "Minor";
This is not:
String result = age >= 18
? hasId
? citizen
? "Allowed"
: "Not Citizen"
: "No ID"
: "Minor";
Complex nested ternaries are difficult to read.
Use if/else when the logic becomes complicated.
59. Operator Precedence#
What happens when an expression has multiple operators?
Example:
int result = 10 + 20 * 3;
Does Java calculate:
(10 + 20) * 3 = 90
or:
10 + (20 * 3) = 70
The answer is:
70
because multiplication has higher precedence than addition.
60. Basic Arithmetic Precedence#
A useful simplified order is:
()
↓
unary operators
↓
* / %
↓
+ -
↓
comparisons
↓
==
↓
&&
↓
||
↓
?:
↓
assignment
This is a simplified learning model, not a complete grammar table.
When in doubt, use parentheses.
61. Parentheses Make Intent Clear#
Instead of:
int result = a + b * c;
you can write:
int result = a + (b * c);
Or if you mean addition first:
int result = (a + b) * c;
Parentheses make the intended order obvious.
Good programmers use parentheses when they improve clarity.
62. Example of Precedence#
int result = 10 + 5 * 2;
Multiplication first:
5 * 2 = 10
Then:
10 + 10 = 20
Output:
20
63. Changing Precedence With Parentheses#
int result = (10 + 5) * 2;
First:
10 + 5 = 15
Then:
15 * 2 = 30
Output:
30
So:
10 + 5 * 2 = 20
(10 + 5) * 2 = 30
64. Associativity#
When operators have the same precedence, Java also follows associativity rules.
For many arithmetic operators, evaluation groups from left to right.
Example:
int result = 20 / 5 * 2;
Both / and * have the same precedence.
Evaluate left to right:
20 / 5 = 4
4 * 2 = 8
Result:
8
Not:
20 / (5 * 2)
which would be 2.
65. Assignment Associativity#
Assignment operators associate from right to left.
Example:
int a;
int b;
int c;
a = b = c = 10;
Conceptually:
c = 10
↓
b = 10
↓
a = 10
All three become:
10
Although valid, avoid overly clever chained assignments if they reduce readability.
66. Type Promotion in Expressions#
Java applies numeric promotion during arithmetic expressions.
For example:
byte a = 10;
byte b = 20;
int result = a + b;
The result of:
a + b
is an int.
This is why:
byte result = a + b;
does not compile without casting.
67. char Promotion#
Consider:
char a = 'A';
char b = 'B';
int result = a + b;
System.out.println(result);
Output:
131
because:
'A' = 65
'B' = 66
65 + 66 = 131
Arithmetic promotes the characters to an integer type.
68. long in an Expression#
If an expression contains a long operand, the other integral operands are generally promoted to long.
Example:
int a = 10;
long b = 20;
long result = a + b;
The result is:
long
69. Floating-Point Promotion#
If a floating-point operand is involved, numeric promotion can produce:
float
or:
double
depending on the operands.
Example:
int a = 10;
double b = 2.5;
double result = a + b;
The result is a double.
70. The Important Rule#
When you perform arithmetic, do not only ask:
"What are the values?"
Also ask:
"What are the types of the operands?"
For example:
5 / 2
produces:
2
while:
5.0 / 2
produces:
2.5
The values look similar, but the types change the behavior.
71. Assignment Operators and Expressions#
Assignment itself is an expression in Java.
For example:
int x;
x = 10;
The assignment expression has the assigned value.
This is why chained assignments work:
a = b = 10;
However, do not use assignment inside complicated expressions unless it genuinely improves clarity.
72. Equality: Primitive Values#
For primitive values, == compares their values after the relevant numeric promotions.
Example:
int a = 10;
int b = 10;
System.out.println(a == b);
Output:
true
73. Equality: Reference Types Preview#
When we later work with objects, == behaves differently.
For reference types, == checks whether two references refer to the same object.
Example:
String a = new String("Java");
String b = new String("Java");
System.out.println(a == b);
This can be:
false
because they are different objects.
To compare String contents, you normally use:
a.equals(b)
which gives:
true
Strings will be studied properly later.
This distinction is extremely important in Java.
74. Bitwise Operators#
Java provides bitwise operations for integral types.
The main operators are:
&
|
^
~
They work on individual bits.
These operators are useful in areas such as:
flags
binary protocols
low-level data manipulation
bit masks
performance-sensitive algorithms
Most beginners do not need them every day, but they are important to understand.
75. Binary Representation#
Suppose:
5 = 0101
3 = 0011
A bitwise AND:
0101
0011
----
0001
gives:
1
So:
System.out.println(5 & 3);
outputs:
1
76. Bitwise OR |#
Using:
5 = 0101
3 = 0011
OR:
0101
0011
----
0111
which is:
7
So:
System.out.println(5 | 3);
outputs:
7
77. Bitwise XOR ^#
XOR gives 1 when the two corresponding bits are different.
0101
0011
----
0110
0110 is:
6
So:
System.out.println(5 ^ 3);
outputs:
6
78. Bitwise NOT ~#
~ flips every bit.
For a signed Java integer, the result can look surprising because integers use two's-complement representation.
Example:
System.out.println(~5);
Output:
-6
A useful identity is:
~x = -x - 1
for Java's signed two's-complement integer representation.
So:
~5
= -5 - 1
= -6
79. Shift Operators#
Java provides:
<<
>>
>>>
These shift bits.
Left shift#
<<
Signed right shift#
>>
Unsigned right shift#
>>>
80. Left Shift <<#
Example:
int x = 5;
System.out.println(x << 1);
Output:
10
Binary:
5
0101
5 << 1
1010
which is:
10
For many values, shifting left by one is equivalent to multiplying by two, but overflow and type width matter.
81. Right Shift >>#
Example:
int x = 20;
System.out.println(x >> 2);
Output:
5
Conceptually:
20 / 4 = 5
For positive values, signed right shift behaves similarly to integer division by powers of two, subject to Java's bit-level rules.
82. >> vs >>>#
This is important.
>>
↓
signed right shift
>>>
↓
unsigned right shift
For positive values, they often produce the same result.
For negative values, they can differ dramatically.
Example:
int x = -8;
System.out.println(x >> 2);
System.out.println(x >>> 2);
The first preserves the sign bit.
The second shifts in zeros.
83. instanceof Operator#
The instanceof operator checks whether an object is compatible with a given type.
Example:
String name = "Java";
System.out.println(name instanceof String);
Output:
true
This becomes particularly useful with inheritance and polymorphism.
For example:
Animal animal = new Dog();
if (animal instanceof Dog) {
System.out.println("It is a Dog");
}
We will study instanceof much more deeply in the OOP section.
84. instanceof and null#
An important rule:
String name = null;
System.out.println(name instanceof String);
Output:
false
A null reference does not refer to an object, so the instanceof test is false.
85. Operator Categories — Full Overview#
Arithmetic
+ - * / %
Unary
+ - ++ -- ! ~
Assignment
= += -= *= /= %=
Relational
> < >= <=
Equality
== !=
Logical
&& || !
Bitwise
& | ^ ~
Shift
<< >> >>>
Ternary
?:
Type test
instanceof
Remember that &, |, and ^ can also operate on boolean operands under Java's rules.
86. A Complete Example#
Let's combine several operators.
public class Main {
public static void main(String[] args) {
int age = 20;
int marks = 85;
boolean adult = age >= 18;
boolean passed = marks >= 40;
boolean eligible = adult && passed;
System.out.println("Age: " + age);
System.out.println("Marks: " + marks);
System.out.println("Adult: " + adult);
System.out.println("Passed: " + passed);
System.out.println("Eligible: " + eligible);
}
}
Output:
Age: 20
Marks: 85
Adult: true
Passed: true
Eligible: true
This demonstrates how arithmetic/data values can become boolean decisions.
87. Real-World Example — Shopping Cart#
Suppose:
double price = 500;
int quantity = 3;
double total = price * quantity;
boolean expensive = total > 1000;
System.out.println("Total: " + total);
System.out.println("Expensive: " + expensive);
Output:
Total: 1500.0
Expensive: true
The flow is:
price × quantity
↓
total
↓
total > 1000
↓
boolean
This pattern appears everywhere in software.
88. Real-World Example — Login#
boolean usernameCorrect = true;
boolean passwordCorrect = true;
boolean loginSuccessful =
usernameCorrect && passwordCorrect;
System.out.println(loginSuccessful);
Output:
true
The logic is:
username correct
AND
password correct
↓
login successful
89. Real-World Example — Discount#
double price = 2000;
boolean eligible = price >= 1000;
double discount = eligible ? 200 : 0;
System.out.println(discount);
Output:
200.0
The ternary operator chooses between:
200
and:
0
depending on the condition.
90. Operator Precedence — Practical Advice#
You do not need to memorize the entire precedence table immediately.
Instead:
- Learn the major groups.
- Understand parentheses.
- Use parentheses when the expression could be confusing.
For example, prefer:
boolean result = (age >= 18) && hasId;
over relying on the reader to remember precedence.
91. A Simplified Precedence Table#
From higher to lower:
| Level | Operators |
|---|---|
| 1 | () |
| 2 | postfix ++, -- |
| 3 | unary +, -, ++, --, !, ~ |
| 4 | *, /, % |
| 5 | +, - |
| 6 | <<, >>, >>> |
| 7 | <, <=, >, >=, instanceof |
| 8 | ==, != |
| 9 | & |
| 10 | ^ |
| 11 | ` |
| 12 | && |
| 13 | ` |
| 14 | ?: |
| 15 | assignment operators |
This table is simplified for learning but captures the major ordering.
92. A Critical Difference: = vs ==#
Remember this forever:
=
↓
assignment
==
↓
comparison
Example:
int x = 10;
means:
put 10 into x
But:
x == 10
means:
is x equal to 10?
The result is:
true / false
93. A Critical Difference: && vs &#
Remember:
&&
↓
logical AND
↓
short-circuits
&
↓
bitwise AND
↓
does not short-circuit
For ordinary boolean conditions, use:
&&
94. A Critical Difference: || vs |#
Similarly:
||
↓
logical OR
↓
short-circuits
|
↓
bitwise OR
↓
does not short-circuit
95. A Critical Difference: x++ vs ++x#
Remember:
x++
↓
use old value
then increment
++x
↓
increment
then use new value
If used alone:
x++;
and:
++x;
both increase x by one.
The difference matters when the expression's value is used.
96. A Critical Difference: Integer vs Floating Division#
5 / 2
gives:
2
while:
5.0 / 2
gives:
2.5
Always check operand types.
97. Common Mistakes#
Mistake 1 — Expecting Decimal Integer Division#
double result = 5 / 2;
Result:
2.0
Correct:
double result = 5.0 / 2;
or:
double result = (double) 5 / 2;
Mistake 2 — Confusing = and ==#
Wrong concept:
if (age = 18)
= is assignment, not equality.
Use:
if (age == 18)
Mistake 3 — Forgetting Short-Circuit Behavior#
Understand that:
false && something
does not evaluate something.
And:
true || something
does not evaluate something.
Mistake 4 — Confusing ++x and x++#
int x = 5;
int a = ++x;
gives:
a = 6
x = 6
while:
int x = 5;
int a = x++;
gives:
a = 5
x = 6
Mistake 5 — Ignoring Operator Precedence#
10 + 5 * 2
is:
20
not:
30
Use:
(10 + 5) * 2
if you want 30.
Mistake 6 — Assuming % Means Percentage#
In Java:
%
means remainder.
It does not directly mean percentage.
Mistake 7 — Using double for Exact Money#
Floating-point arithmetic can have representation errors.
For exact decimal monetary calculations, consider:
BigDecimal
rather than blindly using double.
98. Practice Program — Calculator#
Create:
public class Main {
public static void main(String[] args) {
int a = 20;
int b = 6;
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
System.out.println("Remainder: " + (a % b));
}
}
Expected output:
Addition: 26
Subtraction: 14
Multiplication: 120
Division: 3
Remainder: 2
Then change the values and predict the output before running it.
99. Practice Program — Even or Odd#
Write:
int number = 25;
boolean even = number % 2 == 0;
System.out.println(even);
Expected output:
false
Change:
number = 26;
Output:
true
100. Practice Program — Eligibility#
Create:
int age = 21;
boolean hasId = true;
boolean eligible = age >= 18 && hasId;
System.out.println(eligible);
Expected:
true
Test:
age = 17
hasId = true
age = 21
hasId = false
age = 17
hasId = false
Predict the output for each.
101. Practice Program — Maximum of Two Numbers#
Use the ternary operator:
int a = 50;
int b = 30;
int max = a > b ? a : b;
System.out.println(max);
Output:
50
Then test equal values.
102. Practice Program — Increment#
Predict the output:
int x = 5;
int a = ++x;
int b = x++;
System.out.println(a);
System.out.println(b);
System.out.println(x);
Answer:
6
6
7
Trace it manually before executing.
103. Practice Program — Precedence#
Predict:
int result = 10 + 20 * 2;
System.out.println(result);
Then change it to:
int result = (10 + 20) * 2;
System.out.println(result);
Compare:
70
60
This is why parentheses matter.
104. Practice Program — Short Circuit#
Try:
public class Main {
static boolean test() {
System.out.println("test() executed");
return true;
}
public static void main(String[] args) {
boolean result = false && test();
System.out.println(result);
}
}
Output:
false
Notice:
test() executed
does not appear.
Why?
Because:
false && anything
is already false.
Now change:
boolean result = true || test();
Again, test() will not execute.
This demonstrates short-circuit evaluation directly.
105. Practice Questions#
Basic#
- What is an operator?
- What is an operand?
- What is an expression?
- Name the arithmetic operators.
- What does
%do? - What is integer division?
- What is the difference between
++xandx++? - What is the difference between
--xandx--? - What does
=mean? - What does
==mean?
Logical Operators#
- What does
&&mean? - What does
||mean? - What does
!do? - What is short-circuit evaluation?
- Why is short-circuiting useful?
- Difference between
&&and&? - Difference between
||and|?
Arithmetic#
- What is the result of
20 / 6when both values are integers? - How can you get a decimal result from integer values?
- What is the result of
20 % 6? - What happens when integer division is performed by zero?
- What happens when floating-point division is performed by zero?
Precedence#
- What is operator precedence?
- What is associativity?
- What is the result of:
10 + 5 * 2
- What is the result of:
(10 + 5) * 2
- Why are parentheses useful?
Advanced#
- What is numeric promotion?
- Why does
byte + byteproduce anintresult? - Why can
x += valuework whenx = x + valuedoes not? - What are bitwise operators?
- What is the difference between
>>and>>>? - What does
instanceofdo? - Why does
instanceofreturn false for a null reference? - How does
==differ for primitive values and object references?
106. Interview Questions#
Q1. What is the difference between = and ==?#
=
↓
assignment
==
↓
equality comparison
Example:
int x = 10;
System.out.println(x == 10);
Output:
true
Q2. What is the difference between ++x and x++?#
++x
↓
increment first, then use
x++
↓
use first, then increment
Example:
int x = 5;
System.out.println(++x);
prints:
6
while:
int x = 5;
System.out.println(x++);
prints:
5
After the second statement, x becomes 6.
Q3. Why does 5 / 2 produce 2?#
Both operands are integers.
Therefore Java performs integer division:
5 / 2 = 2
The fractional part is discarded.
To obtain 2.5:
5.0 / 2
or:
(double) 5 / 2
Q4. What is short-circuit evaluation?#
Java's:
&&
||
operators can stop evaluating once the final result is already known.
For:
false && X
X is not evaluated.
For:
true || X
X is not evaluated.
Q5. What is operator precedence?#
Operator precedence determines which operators are evaluated before others.
For example:
10 + 5 * 2
performs multiplication first:
10 + 10
= 20
Parentheses can explicitly change the order.
Q6. What is the difference between && and &?#
&& is short-circuit logical AND.
& performs bitwise AND for integral operands and evaluates both operands for boolean expressions.
Q7. What is the ternary operator?#
The ternary operator:
condition ? value1 : value2
chooses one of two values.
Example:
int max = a > b ? a : b;
107. A Useful Operator Cheat Sheet#
ARITHMETIC
+ add
- subtract
* multiply
/ divide
% remainder
UNARY
+x unary plus
-x unary minus
++ increment
-- decrement
! logical NOT
~ bitwise NOT
ASSIGNMENT
= assign
+= add and assign
-= subtract and assign
*= multiply and assign
/= divide and assign
%= remainder and assign
COMPARISON
> greater than
< less than
>= greater than or equal
<= less than or equal
== equal
!= not equal
LOGICAL
&& AND
|| OR
! NOT
BITWISE
& AND
| OR
^ XOR
~ NOT
SHIFT
<< left shift
>> signed right shift
>>> unsigned right shift
CONDITIONAL
?: ternary
TYPE TEST
instanceof
108. Final Mental Model#
Operators connect values and logic.
Think:
Variables
↓
contain data
↓
Operators
↓
work with that data
↓
Expressions
↓
produce results
↓
Variables / Conditions / Output
For example:
int age = 20;
then:
age >= 18
produces:
true
then:
age >= 18 && hasId
combines multiple boolean values.
And:
price * quantity
performs arithmetic.
So a Java program is constantly doing:
DATA
↓
OPERATIONS
↓
RESULTS
↓
MORE OPERATIONS
↓
PROGRAM BEHAVIOR
109. Final Challenge#
Build a small "student result calculator".
Create variables:
student name
marks of 3 subjects
Calculate:
total marks
average marks
Then create booleans:
passed
excellent
Rules:
passed:
average >= 40
excellent:
average >= 80
Then print:
Student: Rahul
Total: 240
Average: 80.0
Passed: true
Excellent: true
Use:
+
/
>=
&& or ||
and other appropriate operators.
Do not copy the final result blindly.
Build the expressions yourself.
110. Chapter Summary#
Operators allow Java programs to perform work on values.
Arithmetic operators:
+ - * / %
perform mathematical operations.
/ behaves differently for integer and floating-point operands.
5 / 2
↓
2
5.0 / 2
↓
2.5
% gives the remainder.
Unary operators include:
+ - ++ -- ! ~
++x increments before the value is used.
x++ uses the old value before incrementing.
Assignment:
=
is different from equality:
==
Compound assignments include:
+=
-=
*=
/=
%=
Relational operators compare values:
>
<
>=
<=
Equality operators:
==
!=
Logical operators:
&&
||
!
&& and || use short-circuit evaluation.
The ternary operator:
condition ? a : b
provides a compact way to choose between two values.
Operator precedence determines evaluation order.
Parentheses can make the intended order explicit.
Bitwise operators work at the bit level:
&
|
^
~
Shift operators include:
<<
>>
>>>
instanceof tests whether an object is compatible with a given type.
Finally, remember the most important practical lesson:
Always pay attention to the types of your operands.
The expression:
5 / 2
and:
5.0 / 2
look almost identical, but Java produces different results because the operand types are different.
Understanding operators means understanding not just the symbols, but how Java's type system and evaluation rules affect those symbols.
Next Chapter#
Chapter 5 — Input & Output
We will learn how Java communicates with the outside world:
System.outprint()println()printf()- Formatting output
- Escape sequences
- Reading input
Scanner- Reading integers
- Reading decimals
- Reading strings
next()vsnextLine()- Input-buffer problems
- Command-line arguments
- Basic input validation
- Common
Scannermistakes - Building interactive programs
- Practical exercises