Topic 2 of 30 · Beginner
Variables, Data Types & Operators
Primitives, references, casting and operators.
Concept
Java is statically typed: each variable has a fixed type. There are 8 primitives — byte, short, int, long, float, double, char, boolean — and everything else is a reference to an object.
Widening (int → long) is automatic; narrowing (double → int) needs an explicit cast and may lose data.
Integer division drops the decimal (7 / 2 = 3). Use == for primitives but .equals() for objects such as String.
Cheat sheet
| Type | Size | Default |
|---|---|---|
| byte | 1 byte | 0 |
| int | 4 bytes | 0 |
| long | 8 bytes | 0L |
| double | 8 bytes | 0.0 |
| char | 2 bytes | '\u0000' |
| boolean | JVM-dependent | false |
Code (Java 21)
int age = 21;
long views = 3_000_000_000L;
double cgpa = 8.6;
char grade = 'A';
boolean placed = true;
var city = "Hyderabad"; // type inferred as String
int whole = (int) cgpa; // 8 (narrowing cast)
System.out.println(7 / 2); // 3
System.out.println(7 / 2.0); // 3.5Remember
- 8 primitives; everything else is an object reference.
- Integer overflow wraps silently.
- var is local type inference, still static typing.
Interview questions
Is Java pass-by-value or pass-by-reference?
Always pass-by-value. For objects, the value passed is a copy of the reference, so the method can change the object but not reassign the caller's variable.
== vs equals()?
== compares primitive values or reference identity. equals() compares logical content when overridden, as in String.
Lesson test
Take an 8-question test on “Variables, Data Types & Operators” — concepts, output prediction, bug spotting and interview questions.