Variables and Data Types

Site Admin · 11 Sep 2026 · 12 views

What Is a Variable?

A variable is a named box in memory that holds a value while the program runs. Every variable in Java has a declared type, which decides how much memory it uses and which operations are allowed on it.

Declaring and Assigning

int count;          // declaration
count = 10;         // assignment
int total = 5;      // declaration + assignment in one step
double price = 99.5;
char grade = 'A';
boolean isDone = true;
String name = "Anjali";

The Eight Primitive Types

TypeSizeExample
byte1 byte127
short2 bytes32000
int4 bytes2000000
long8 bytes10000000000L
float4 bytes3.14f
double8 bytes2.71828
char2 bytes'A'
boolean1 bittrue/false

Primitives vs Reference Types

  • Primitives store the actual value directly.
  • Reference types (classes, arrays, interfaces) store a reference to an object stored on the heap. String is a reference type.
int a = 5;
int b = a;    // b gets a copy of the value 5

String x = "hello";
String y = x; // x and y reference the same object

Local Variables Must Be Initialised

int n;
System.out.println(n); // compile error: n may not be initialised

Declaring a variable

Reference types in Java

Reference type example

Key Points

  • Java is statically typed: every variable has a fixed type.
  • Eight primitives cover numbers, characters and booleans.
  • Use L and f suffixes for long and float literals.
Share this post:

Comments (0)

Please login or register to comment.