Java Variables & Data Types
Primitives vs reference types, and when to use each.
A variable is a named storage location that holds a value. Think of it as a labelled box.
javaint age = 21; // box labelled 'age' holds 21 String name = "Aarav"; // box labelled 'name' holds the text
You can:
- Read the value:
System.out.println(age); - Update it:
age = 22; - Use it in expressions:
int next = age + 1;
Syntax:
javatype name = value; // declare + initialise type name; // declare only (allowed for fields, not local vars)
javaint score = 95; double price = 49.99; char grade = 'A'; boolean isPro = true; String username = "codekilla";
Java has exactly 8 primitive types — they store values directly (not references).
| Type | Size | Range | Default | Example |
|---|---|---|---|---|
byte | 1 byte | -128 to 127 | 0 | byte b = 100; |
short | 2 bytes | -32 768 to 32 767 | 0 | short s = 30000; |
int | 4 bytes | ±2.1 billion | 0 | int n = 42; |
long | 8 bytes | ±9.2 quintillion | 0L | long big = 9_000_000_000L; |
float | 4 bytes | ~7 decimal digits | 0.0f | float pi = 3.14f; |
double | 8 bytes | ~15 decimal digits | 0.0 | double e = 2.71828; |
char | 2 bytes (Unicode) | '\u0000' to '\uffff' | '\u0000' | char c = 'A'; |
boolean | (JVM-defined) | true / false | false | boolean ok = true; |
Tip: Use
_in numeric literals for readability —1_000_000is the same as1000000.
String, arrays, classes, interfaces — all are reference types. They store a reference (pointer) to the actual object on the heap.
javaString name = "Ada"; // reference to a String object int[] xs = {1, 2, 3}; // reference to an int array
int a = 5; → [a | 5] (value lives in 'a')
String s = "Hi"; → [s | * ] ──→ "Hi" ('s' holds a reference)
String is a class, not a primitive, but feels like one because of literal syntax ("...") and + concatenation.
javaString greet = "Hello, " + name + "!"; int len = greet.length(); String upper = greet.toUpperCase();
A final variable cannot be reassigned after initialisation:
javafinal double PI = 3.14159; PI = 3.14; // ERROR: cannot assign a value to final variable PI
Convention: final constants use UPPER_SNAKE_CASE.
Let the compiler figure out the type:
javavar x = 10; // int var y = 3.14; // double var name = "Ada"; // String var list = new ArrayList<String>(); // ArrayList<String>
Local variables only — not for class fields, parameters, or return types.
javaint n = 100; long big = n; // int → long, safe double d = big; // long → double, safe
javadouble pi = 3.14; int truncated = (int) pi; // 3 — fractional part dropped long huge = 5_000_000_000L; int may = (int) huge; // overflow! gives 705032704
- camelCase for variables and methods:
userName,totalPrice. - PascalCase for classes and interfaces:
BankAccount,Runnable. - UPPER_SNAKE_CASE for
finalconstants:MAX_USERS,PI. - Avoid single letters except short loops (
i,j,k).
javadouble price = 99.95; System.out.printf("Price: $%.2f%n", price); // Price: $99.95 System.out.printf("%-10s %5d%n", "Apples", 12); // left-pad string, right-pad int
javapublic class Profile { public static void main(String[] args) { String name = "Aarav"; int age = 21; double height = 1.78; char grade = 'A'; boolean isStudent = true; final double PI = 3.14159; System.out.printf("%s is %d, %.2f m tall, grade %c, student=%b, PI=%.5f%n", name, age, height, grade, isStudent, PI); } }
Aarav is 21, 1.78 m tall, grade A, student=true, PI=3.14159
- Uninitialised local variable — Java refuses to compile
int x; System.out.println(x);(unlike C). Always assign before use. - Integer overflow —
int x = Integer.MAX_VALUE + 1;silently wraps to negative. Uselongfor big numbers. ==on Strings — compares references, not content. Use.equals().- Forgetting
L/f—long big = 9_000_000_000;overflowsintfirst. Use9_000_000_000L. - Comparing floats with
==— floats are imprecise (0.1 + 0.2 != 0.3). UseMath.abs(a - b) < 1e-9.
- Profile — Declare and print: name (String), age (int), height (double), grade (char), isStudent (boolean). Hint: 5 declarations + 1
printf. - Fix the overflow —
int big = 1_000_000 * 1_000_000;overflows. Print and fix. Hint: change tolongand addL. finalconstants — Compute the area of a circle withfinal double PI = 3.14159;and a user-input radius. Hint:area = PI * r * r;.varmagic — Usevarto declare 3 variables (int, double, String). Print each with its inferred type using.getClass().getSimpleName(). Hint: only works on wrapper types.
💡 Think Like a Programmer: Choose types carefully. Use
intfor counts,longfor IDs/timestamps,doublefor measurements,BigDecimalfor money — neverfloat/doublefor currency.
Quick recap quiz?
We'll generate 5 MCQs from this lesson and check your understanding instantly. Takes ~30 seconds.
Program
public class Main {
public static void main(String[] args) {
int year = 1995;
String lang = "Java";
System.out.println(lang + " was born in " + year);
}
}