Java Basics
Operators
Complete lesson for Operators using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Operators
Section: Java Basics. Arithmetic, relational, logical, bitwise, assignment, ternary, instanceof, escapes, and precedence.
What are operators?
- Operators compute a value from one or more operands. Java has no pointer-dereference, address-of, or scope-resolution operator (
*/&/::as in C++). - Integer
/and%truncate toward zero.%works for integers; floating%is legal but rarely used in interviews. - String
+concatenates. If either operand is aString, the other is converted withString.valueOf. - Escape sequences inside string and char literals format output:
\nnewline,\ttab,\\backslash,\"quote.
Java operators & escape sequences
Operators compute values from operands. The chart groups arithmetic, relational, logical,
bitwise (including Java’s >>>), assignment, and other operators
(?:, instanceof, new). The right side lists
String escapes such as \n and \t. Java has no pointer or
sizeof operators.
String output
- Arithmetic / relational / logical: everyday math and decisions;
&&short-circuits. - Bitwise:
& | ^ ~ << >> >>>—>>>zero-fills. - Other:
?:,instanceof,new, cast,.,[]. - Escapes:
\n,\t,\\,\"inside strings.
Classification (overview)
| Category | Operators | Purpose |
|---|---|---|
| Arithmetic | + - * / % ++ -- | Math and increment |
| Relational | == != > < >= <= | Compare values |
| Logical | && || ! | Boolean combine (short-circuit) |
| Bitwise / shift | & | ^ ~ << >> >>> | Bit operations on integers |
| Assignment | = += -= *= /= %= &= |= ^= <<= >>= >>>= | Store or update |
| Other | ?:, instanceof, (), new, ., [] | Ternary, type test, cast, allocate, member, index |
Arithmetic, relational, logical
+ - * / %follow usual math; unary-negates.++/--as prefix return the updated value; as postfix they return the old value.- Relational operators produce
boolean. You cannot writeif (x)for anintlike C — the condition must be boolean. &&and||short-circuit: the right operand is skipped if the result is already known.&and|on booleans always evaluate both sides.!inverts a boolean.==on primitives compares values; on references it compares identity (use.equalsforStringcontent).
public class OperatorBasics {
public static void main(String[] args) {
int a = 10, b = 3;
System.out.println(a / b); // 3
System.out.println(a % b); // 1
System.out.println(a > b && b != 0);
int max = (a > b) ? a : b;
System.out.println(max);
System.out.println("Line1\nLine2");
}
} Bitwise operators
- Work on two’s-complement integers.
>>>is unsigned right shift (fills with zeros) — a Java-only spelling compared with C++. n & 1tests odd;n << 1multiplies by 2 for non-overflowing values;n ^ nis 0.~flips every bit. Combined with masks,&clears,|sets,^toggles.
| Op | Name | Example idea |
|---|---|---|
& | AND | Clear / test bits |
| | OR | Set bits |
^ | XOR | Toggle bits; find unique number |
~ | NOT | Flip all bits |
<< | Left shift | Shift toward high bits |
>> | Signed right shift | Keeps sign bit |
>>> | Unsigned right shift | Fills with 0 |
Assignment, ternary, and instanceof
=is assignment, not equality. Compound forms+=,-=,*=,/=,%=(and the bitwise ones) update in place.condition ? a : bchoosesaif the condition is true. Both branches must be assignment-compatible.obj instanceof Typeisfalsefornulland does not throw. Pattern matching (if (obj instanceof String s)) is standard from Java 16.
Advanced — Operators
Precedence, associativity, and String +
- Unary > arithmetic > shift > relational > equality > bitwise AND/XOR/OR > logical &&/|| > ternary > assignment.
- When unsure, use parentheses. Interviewers love
i = i++style traps — the value ofi++is the oldi, then assignment overwrites. - String
+concatenates and is left-associative:"a" + 1 + 2is"a12";1 + 2 + "a"is"3a". - Do not use
+to build strings in a tight loop — useStringBuilder.
Short-circuit, side effects, and escapes
x != null && x.isEmpty()is safe becauseisEmptyis skipped whenxis null.x != null & x.isEmpty()can NPE.++/--on the same variable twice in one expression is a readability trap; Java defines left-to-right evaluation, but interviews still ask you to avoid it.- Common escapes: newline
\n, tab\t, backslash\\, double quote, single quote, and Unicode\uplus four hex digits.printf("%n")is a portable newline.
Tricky Interview Points
Q1) What is the difference between && and & for booleans?
Answer && short-circuits; & always evaluates both operands. Use && in conditions to avoid NPEs and extra work.
Q2) What does >>> do?
Answer Unsigned right shift: bits move right and vacated high bits become 0, even for negative ints. >> keeps the sign bit.
Q3) What is 7 / 2 and 7 % 2 in Java?
Answer 3 and 1. Integer division truncates toward zero.
Q4) Does instanceof work on null?
Answer null instanceof AnyType is false and does not throw.
Q5) Why is i = i++ a trap?
Answer The postfix expression yields the old value, then i is incremented, then the assignment writes the old value back. i stays the same.
Q6) Can you overload operators in Java?
Answer No, except that + is overloaded by the language for String concatenation. You cannot define your own operator overloads.
Q7) What is the difference between == and equals for String?
Answer == compares references (identity). equals compares character content. Always use equals for text unless you truly mean the same object.
Q8) What does "a" + 1 + 2 print?
Answer a12. Left-to-right concatenation: ("a" + 1) is "a1", then + 2 is "a12". Contrast 1 + 2 + "a" which is "3a".
Q9) Name four Java escape sequences.
Answer \n newline, \t tab, \\ backslash, \" quote. \uXXXX is a Unicode escape.
Q10) Does Java have a pointer or sizeof operator?
Answer No. There is no * dereference, no & address-of, no ->, and no sizeof. Use . and [] on objects and arrays.
Q11) Which operator tests odd vs even with bits?
Answer n & 1. If the result is 1, n is odd. n << 1 doubles (until overflow); n >> 1 halves toward negative infinity for negatives — be careful.
Simple Programs
Bitwise demo
public class BitwiseDemo {
public static void main(String[] args) {
int a = 12; // 1100
int b = 10; // 1010
System.out.println(a & b); // 8
System.out.println(a | b); // 14
System.out.println(a ^ b); // 6
System.out.println(a << 1); // 24
int n = 7;
System.out.println((n & 1) == 1 ? "odd" : "even");
}
} Short-circuit vs both sides
public class ShortCircuit {
static boolean ping(String label, boolean value) {
System.out.println(label);
return value;
}
public static void main(String[] args) {
System.out.println("&& :");
boolean a = ping("L", false) && ping("R", true);
System.out.println("|| :");
boolean b = ping("L", true) || ping("R", false);
System.out.println(a + " " + b);
}
} Ternary max and escape output
public class TernaryEscapes {
public static void main(String[] args) {
int x = 9, y = 4, z = 11;
int max = (x > y) ? ((x > z) ? x : z) : ((y > z) ? y : z);
System.out.println("max = " + max);
System.out.println("Name:\tAda\nLang:\tJava");
}
} instanceof and String + order
public class InstanceConcat {
public static void main(String[] args) {
Object o = "hello";
System.out.println(o instanceof String);
System.out.println(null instanceof String);
System.out.println("a" + 1 + 2);
System.out.println(1 + 2 + "a");
}
} Problem Solving Tricks
- Use
&&/||inifconditions; reserve&/|for bit masks (or rare non-short-circuit needs). - Parenthesize mixed shift and arithmetic expressions.
n & (n - 1)clears the lowest set bit — a common interview trick.- Do not use
+for heavy string building in a loop; useStringBuilder. - Memorise
>>>as “zero-fill right shift” — that one word separates Java from C++ interviews. ==onIntegercan lie because of the -128..127 cache; preferequalsorintValue.- Write
"\n"in source when you want a real newline in the string;"%n"inprintfis OS-correct. - Put the boolean test first in
x != null && x.method()so the method never runs on null.
Practice Programs List
- Print AND, OR, XOR, left shift, and both right shifts of two integers.
- Write a program that finds the maximum of three ints using only the ternary operator.
- Demonstrate short-circuit: skip a method call on the right of
&&when the left is false. - Check whether an int is a power of two using
n > 0 && (n & (n - 1)) == 0. - Predict
int i = 5; i = i++;then run it. - Print
"a" + 1 + 2and1 + 2 + "a"and explain the difference. - Print a two-line label using
\nand a column using\t. - Test
null instanceof Stringand a realStringwithinstanceof. - Rewrite nested if-else that picks a grade as a chain of ternary operators (then prefer if-else in real code).
- Use
>>>on-1and compare the result with>>.