Skip to main content

Variable

Variables in Java are used to store data that can be used and changed throughout a program.

Java has two main categories of variables:

  • Primitive types (e.g., int, double, boolean)
  • Reference types (e.g., String, arrays, objects)

Primitive Types

There are 8 primitive types in Java, divided into four categories:

  1. Integer Types
TypeSizeDescriptionExample
byte1 byteVery small integersbyte b = 100;
short2 bytesSmall integersshort s = 1000;
int4 bytesDefault integer typeint i = 12345;
long8 bytesLarge integerslong l = 123456789L; (note the L)
  1. Floating-Point Types
TypeSizeDescriptionExample
float4 bytesSingle precisionfloat f = 3.14f;
double8 bytesDouble precisiondouble d = 3.14159;
  1. Character Type
TypeSizeDescriptionExample
char2 bytesA single Unicode characterchar c = 'A';
  1. Boolean Type
TypeValuesDescriptionExample
booleantrue/falseLogical true/false valuesboolean isValid = true;

int and double are the default types for numbers.

var a = 11; //int
var b = 11.0; //double

You cannot assign null to primitive types.

Primitive types are not objects, but Java provides wrapper classes (Integer, Double, etc.) if you need object behavior.

Wrapper Classes for Primitives

PrimitiveWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

Java automatically converts between primitives and wrapper objects (Autoboxing and Unboxing). Wrapper Classes can be null.

Integer i1 = 135; // Autoboxing
int i2 = i1; // Unboxing
Integer i3 = null;

This is useful when working with generic types or collections:

List<Integer> list = new ArrayList<>();
list.add(10); // primitive 10 is autoboxed to Integer

Casting of Primitive

Widening (Implicit Casting):

Smaller data type can be casted to larger one automatically and implicitly. Widening is safe and automatic.

byte → short → int → long → float → double

char
byte b = 10;
int i = b;
double d = b;
long l = i;

char ch = 'B';
int ascii = ch; // 66

Narrowing (Explicit Casting):

In contrary, larger data type can be explicitly cast to smaller data type, this may cause data loss or overflow.

short s = 130;
byte b = (byte) s; // Overflow: 130 → -126

int i = 65;
char c = (char) i; // A

int i1 = (int) 1.2f;
int i2 = (int) 2.3d;
int i3 = (int) 34L;
float f1 = (float) 3.14;
byte b1 = (byte)

boolean cannot be cast to or from any other primitive type.

When you do arithmetic with mixed types, the smaller type is promoted to the largest type in the expression.

int i = 10;
double d = 5.5;
double result = i + d; // int → double

Reference Types

Reference types store references to objects instead of raw values.

String name = "Alice";
Scanner input = new Scanner(System.in);
Integer i = 123;

In Java, reference types refer to objects, rather than storing raw values like primitive types do. They store a reference (memory address) pointing to the actual data in the heap.

You can declare a variable and assign a value in one line:

int x = 10;

Or separately:

int x;
x = 10;

Java is strongly typed. Java requires the variable type to match the assigned value.

Integer x = 5;
x = "hello"; // ❌ Error

example

public class VariablesExample {
public static void main(String[] args) {
int age = 30;
double height = 1.75;
boolean isStudent = false;
String name = "John";

System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Student: " + isStudent);
}
}

var and final

Java provides features like var and final to make code more expressive and safe.

var (Local Variable Type Inference)

Introduced in Java 10, var lets you declare a local variable without specifying its type explicitly.

var message = "Hello, Java"; // Automatically inferred as String
var number = 123; // Inferred as int

Rules for var:

  • Only works for local variables (inside methods, blocks)
  • The variable must be initialized immediately
  • Still strongly typed — the type is just inferred by the compiler
var name = "Alice";      // OK
var age; // ❌ Error: missing initializer
name = 123; // ❌ Error: type mismatch (not a String)

final (Constant Reference)

Use final to declare a variable that cannot be reassigned after it’s set.

final int x = 10;
x = 20; // ❌ Error: cannot assign a value to final variable

You can still mutate the contents of final objects:

final List<String> list = new ArrayList<>();
list.add("hello"); // ✅ Allowed
list = new ArrayList<>(); // ❌ Error

You Can Combine Them

final var score = 100; // Inferred as int, cannot be reassigned