Foundation

02 — Variables & Types

Previous: 01 Getting Started · Next: 03 Operators & Casting

▶️ java pkg1core/core2Variables.java · java pkg1core/core3DataTypes.java


Variables store data

A variable is a named container for a value.

java
1int age = 30;2double price = 19.99;3boolean active = true;4String name = "Ravi";
Part Meaning
int Type — what kind of data
age Name — how you refer to it
30 Value — what's stored

The 8 primitive types

Primitives store raw values directly (fast, no object overhead).

Type Size Example Use for
byte 8-bit 127 Rare; binary protocols
short 16-bit 32000 Rare
int 32-bit 42 Whole numbers (default choice)
long 64-bit 9_000_000_000L Big integers; suffix L
float 32-bit 3.14f Rare; suffix f
double 64-bit 3.14159 Decimals (default choice)
char 16-bit 'A' Single character
boolean 1-bit true true / false

💡 Use int for integers and double for decimals unless you have a specific reason not to.


Reference types

Everything that is not a primitive is an object (stored on the heap; variable holds a reference).

java
1String greeting = "Hello";     // String object2int[] numbers = {1, 2, 3};     // array object3Scanner sc = new Scanner(System.in);

Wrappers & autoboxing

Each primitive has a wrapper class for use in generics/collections:

Primitive Wrapper
int Integer
double Double
boolean Boolean
java
1Integer boxed = 42;    // autoboxing: int → Integer2int unboxed = boxed;   // unboxing: Integer → int

⚠️ Gotcha: Integer cache for -128..127 — Integer.valueOf(127) == Integer.valueOf(127) is true, but 128 is false.


Variable kinds

Kind Where Example
Local Inside a method int x = 5;
Instance Per object String name; in a class
Static Per class (shared) static int count;
Final Cannot reassign final int MAX = 100;

`var` — type inference (Java 10+)

java
1var message = "Hello";        // inferred as String2var list = new ArrayList<String>();

Rules: local variables only, must have an initializer, still statically typed.


Casting & overflow

java
1long big = 9_000_000_000L;2int small = (int) big;           // narrowing cast — may lose data3 4int max = Integer.MAX_VALUE;5System.out.println(max + 1);     // overflows to Integer.MIN_VALUE

Practice

  1. Run core2Variables and core3DataTypes.
  2. Declare one variable of each primitive type and print them.
  3. Try var for a List<String>.

Interview drill → 01 Core Java (questions 1–7)

Next → 03 Operators & Casting