Turning Learners Into Developers
Codekilla
CODEKILLA
back to course
Lesson 05 / 806%· free preview
Variables & Data1/7

Java Variables & Data Types

Primitives vs reference types, and when to use each.

int age = 25;nameagetype / sizeint (4B)address0x7ffe18value25
Visual explanation diagram · click steps to walk through it
What is a Variable?

A variable is a named storage location that holds a value. Think of it as a labelled box.

java
int 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;
Declaring Variables

Syntax:

java
type name = value;   // declare + initialise
type name;           // declare only (allowed for fields, not local vars)
java
int score = 95;
double price = 49.99;
char grade = 'A';
boolean isPro = true;
String username = "codekilla";
The 8 Primitive Types

Java has exactly 8 primitive types — they store values directly (not references).

TypeSizeRangeDefaultExample
byte1 byte-128 to 1270byte b = 100;
short2 bytes-32 768 to 32 7670short s = 30000;
int4 bytes±2.1 billion0int n = 42;
long8 bytes±9.2 quintillion0Llong big = 9_000_000_000L;
float4 bytes~7 decimal digits0.0ffloat pi = 3.14f;
double8 bytes~15 decimal digits0.0double e = 2.71828;
char2 bytes (Unicode)'\u0000' to '\uffff''\u0000'char c = 'A';
boolean(JVM-defined)true / falsefalseboolean ok = true;

Tip: Use _ in numeric literals for readability — 1_000_000 is the same as 1000000.

Reference Types (everything else)

String, arrays, classes, interfaces — all are reference types. They store a reference (pointer) to the actual object on the heap.

java
String name = "Ada";          // reference to a String object
int[] xs = {1, 2, 3};         // reference to an int array
Primitive vs Reference (visual)
int a = 5;       →   [a | 5]              (value lives in 'a')
String s = "Hi"; →   [s | * ] ──→ "Hi"     ('s' holds a reference)
`String` — Special But Useful

String is a class, not a primitive, but feels like one because of literal syntax ("...") and + concatenation.

java
String greet = "Hello, " + name + "!";
int len = greet.length();
String upper = greet.toUpperCase();
Constants — `final`

A final variable cannot be reassigned after initialisation:

java
final double PI = 3.14159;
PI = 3.14;   // ERROR: cannot assign a value to final variable PI

Convention: final constants use UPPER_SNAKE_CASE.

`var` — Local-Variable Type Inference (Java 10+)

Let the compiler figure out the type:

java
var 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.

Type Casting
Implicit (widening) — automatic
java
int n = 100;
long big = n;        // int → long, safe
double d = big;      // long → double, safe
Explicit (narrowing) — you ask for it
java
double pi = 3.14;
int truncated = (int) pi;     // 3 — fractional part dropped
long huge = 5_000_000_000L;
int may = (int) huge;         // overflow! gives 705032704
Naming Conventions
  • camelCase for variables and methods: userName, totalPrice.
  • PascalCase for classes and interfaces: BankAccount, Runnable.
  • UPPER_SNAKE_CASE for final constants: MAX_USERS, PI.
  • Avoid single letters except short loops (i, j, k).
Output Formatting
java
double 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
A Complete Example
java
public 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
Common Mistakes
  • Uninitialised local variable — Java refuses to compile int x; System.out.println(x); (unlike C). Always assign before use.
  • Integer overflowint x = Integer.MAX_VALUE + 1; silently wraps to negative. Use long for big numbers.
  • == on Strings — compares references, not content. Use .equals().
  • Forgetting L / flong big = 9_000_000_000; overflows int first. Use 9_000_000_000L.
  • Comparing floats with == — floats are imprecise (0.1 + 0.2 != 0.3). Use Math.abs(a - b) < 1e-9.
Interview Questions

Practice Exercises
  1. Profile — Declare and print: name (String), age (int), height (double), grade (char), isStudent (boolean). Hint: 5 declarations + 1 printf.
  2. Fix the overflowint big = 1_000_000 * 1_000_000; overflows. Print and fix. Hint: change to long and add L.
  3. final constants — Compute the area of a circle with final double PI = 3.14159; and a user-input radius. Hint: area = PI * r * r;.
  4. var magic — Use var to 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 int for counts, long for IDs/timestamps, double for measurements, BigDecimal for money — never float/double for currency.

AI-powered recap

Quick recap quiz?

We'll generate 5 MCQs from this lesson and check your understanding instantly. Takes ~30 seconds.

# program

Program

Java
public class Main {
    public static void main(String[] args) {
        int year = 1995;
        String lang = "Java";
        System.out.println(lang + " was born in " + year);
    }
}
Ready to move on?
// example library
Want more hands-on snippets in Java?
Browse 100 runnable examples · across 10 chapters · short, copy-paste-friendly · grouped by topic
Explore examples
// glossary lookup
Every term you just saw, explained
Quick definitions for variables, pointers, loops, functions and every concept in one searchable page.
Open Terminology
// feedback.matters()
Did this lesson help you?