← Java roadmap

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

TypeSizeDefault
byte1 byte0
int4 bytes0
long8 bytes0L
double8 bytes0.0
char2 bytes'\u0000'
booleanJVM-dependentfalse

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.5

Remember

  • 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.

Practise Java with the AI mentor

Lesson test

Take an 8-question test on “Variables, Data Types & Operators” — concepts, output prediction, bug spotting and interview questions.

Can't find a Java topic you need for exams or placements? Request it and we'll add it.