Skip to main content

Ch 2.1 What Are Variables?

In mathematics, a variable is defined as a "changing quantity," but in programming the meaning is a bit different.

1. Definition of a Variable​

In programming, a variable is "a memory space that can store exactly one value."

The Relationship Between Memory and Variables​

A computer's memory (RAM) is like a giant chest of drawers with countless compartments. Each compartment has a unique address (memory address), and we store data in these compartments. However, working directly with memory addresses is very cumbersome (who wants to memorize something like 0x7FFEEFBFF5A0?). Java lets us work with memory conveniently through variable names, which act as labels.

Memory (RAM)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Address: 0x100 β”‚ Value: 25 ← age β”‚
β”‚ Address: 0x104 β”‚ Value: 0 β”‚
β”‚ Address: 0x108 β”‚ Value: 175.5 ← heightβ”‚
β”‚ ... β”‚ ... β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Box analogy: A variable is like a labeled box. Put a label (age, height) on the outside, and you can retrieve or change the value inside just by calling its name.

note

A variable stores only one value. When you store a new value, the previous one is gone.

2. Declaring and Initializing Variables​

Before you can use a variable, you must declare it by specifying its type and name.

Variable Declaration Syntax​

// Syntax: type variableName;
int age; // declare variable age of type int
double height; // declare variable height of type double
String name; // declare variable name of type String

When a variable is declared, a storage space of the appropriate size for the type is allocated in memory, and it becomes accessible through the variable name.

Variable Initialization​

After declaring a variable, you must initialize it (assign a first value) before using it.

int age;        // Step 1: declare (allocate memory)
age = 25; // Step 2: initialize (store value in memory)

int year = 2024; // Declare and initialize on one line!
warning

In Java, local variables(declared inside a method) must be initialized before use β€” otherwise you get a compile error!

int score;
System.out.println(score); // Error: variable score might not have been initialized

Declaring Multiple Variables on One Line​

Variables of the same type can be declared together, separated by commas.

int x, y, z;              // declaration only
int a = 1, b = 2, c = 3; // declaration + initialization

3. Types of Variables: Classified by Location​

Variables fall into three categories based on where they are declared.

TypeDeclared LocationLifecycleDefault Value
Local variableInside a methodMethod start ~ endNone (must initialize manually)
Instance variableInside a class, outside methodsObject creation ~ garbage collectionType-specific default
Class variable (static)With static keywordProgram start ~ endType-specific default
public class Student {
// Instance variables: each Student object has its own copy
String name; // default: null
int grade; // default: 0
double gpa; // default: 0.0

// Class variable: shared by all Student objects
static int totalStudents = 0;

public void study() {
// Local variable: only accessible inside study()
int studyHours = 3; // must be initialized manually
System.out.println(name + " studied for " + studyHours + " hours.");
}
}

4. Scope and Lifecycle of Variables​

Scope is the region of code where a variable can be accessed. A variable is only usable within the block ({...}) where it was declared.

public class ScopeExample {
static int classVar = 10; // class scope: accessible anywhere in the class

public static void main(String[] args) {
int outerVar = 20; // main method scope

if (outerVar > 10) {
int innerVar = 30; // if-block scope
System.out.println(classVar); // OK: 10
System.out.println(outerVar); // OK: 20
System.out.println(innerVar); // OK: 30
}

System.out.println(classVar); // OK: 10
System.out.println(outerVar); // OK: 20
// System.out.println(innerVar); // Error! not accessible outside if-block
}
}
tip

Declare variables in the narrowest scope possible. This improves readability and reduces bugs.

5. Constants β€” the final Keyword​

A variable whose value cannot be changed after the first assignment is a constant. Add the final keyword before the type. By convention, constant names are written in UPPER_CASE_WITH_UNDERSCORES.

public class ConstantExample {
public static void main(String[] args) {
final double PI = 3.14159265358979;
final int MAX_SCORE = 100;
final String APP_NAME = "MyJavaApp";

System.out.println("Pi: " + PI);
System.out.println("Max score: " + MAX_SCORE);
System.out.println("App name: " + APP_NAME);

// PI = 3.14; // Compile error! Cannot reassign a final variable.
}
}

Why use constants?

  • Prevent mistakes: Protect important values from accidental modification
  • Readability: PI is much clearer than 3.14159...
  • Maintainability: Change the value in one place, and it reflects everywhere

6. The var Keyword (Java 10+) β€” Type Inference​

Since Java 10, the var keyword lets the compiler infer the type from the assigned value. Only usable with local variables.

public class VarExample {
public static void main(String[] args) {
var age = 25; // compiler infers int
var name = "Alice"; // compiler infers String
var pi = 3.14159; // compiler infers double
var isStudent = true; // compiler infers boolean

System.out.println(age); // 25
System.out.println(name); // Alice
System.out.println(pi); // 3.14159
System.out.println(isStudent); // true

// var must be initialized at the point of declaration
// var x; // Error! var requires an initializer
}
}
note

Using var does not make Java a dynamically typed language. It is still strongly typed; the type is fixed at compile time.

7. Variable Naming Rules and Reserved Words​

Mandatory Rules (violation causes a compile error)​

  1. Case-sensitive.(Age and age are different variables)
  2. Cannot use reserved keywords.(int, class, for, etc.)
  3. Cannot start with a digit.(age10 is OK; 10age is not)
  4. Only _ and $ are allowed as special characters.
TargetRuleExample
Variables, methodsLowercase start, camelCasestudentName, totalScore
ClassesUppercase start, PascalCaseStudentRecord, MathUtil
ConstantsAll uppercase, underscoresMAX_VALUE, PI
PackagesAll lowercasecom.example.app

Java Reserved Words​

abstract  assert    boolean   break     byte
case catch char class const
continue default do double else
enum extends final finally float
for goto if implements import
instanceof int interface long native
new package private protected public
return short static strictfp super
switch synchronized this throw throws
transient try void volatile while
warning

true, false, and null are not reserved words but are treated as literals and therefore cannot be used as variable names.

8. Overflow and Underflow​

Each primitive type has a fixed range of values. Exceeding the maximum causes overflow; going below the minimum causes underflow. Critically, no error is thrown β€” the value silently wraps around to the other end of the range!

public class OverflowExample {
public static void main(String[] args) {
// Check int max and min
System.out.println("int MAX: " + Integer.MAX_VALUE); // 2147483647
System.out.println("int MIN: " + Integer.MIN_VALUE); // -2147483648

// Overflow: add 1 to the maximum value
int maxVal = Integer.MAX_VALUE;
System.out.println("MAX + 1 = " + (maxVal + 1)); // -2147483648 (wraps to MIN!)

// Underflow: subtract 1 from the minimum value
int minVal = Integer.MIN_VALUE;
System.out.println("MIN - 1 = " + (minVal - 1)); // 2147483647 (wraps to MAX!)

// byte overflow
byte b = 127; // byte max
b++;
System.out.println("byte 127 + 1 = " + b); // -128
}
}
byte range visualization:
... -130 -129 [-128 ......... 127] 128 129 ...
↑ ↑
MIN MAX
└────── overflow wraps to MIN β”€β”€β”€β”€β”€β”€β”˜
warning

Be especially careful about overflow in financial calculations. Use long or BigInteger for safety.

9. Practical Example: Student Grade Management​

public class StudentGrade {
// Constants: values that never change
static final int MAX_SCORE = 100;
static final int SUBJECT_COUNT = 5;
static final String SCHOOL_NAME = "Java Academy";

// Class variable: shared across all instances
static int totalStudents = 0;

public static void main(String[] args) {
// Student basic info
String studentName = "Alice Java";
int studentAge = 20;
char grade = 'A'; // letter grade (A, B, C, D, F)
boolean isEnrolled = true; // enrollment status

// Subject scores
int koreanScore = 95;
int mathScore = 88;
int englishScore = 92;
int scienceScore = 78;
int historyScore = 85;

// Calculate total and average
int totalScore = koreanScore + mathScore + englishScore
+ scienceScore + historyScore;
double average = (double) totalScore / SUBJECT_COUNT; // cast required!

totalStudents++;

// Print results
System.out.println("=== " + SCHOOL_NAME + " Report Card ===");
System.out.println("Name: " + studentName);
System.out.println("Age: " + studentAge);
System.out.println("Grade: " + grade);
System.out.println("Enrolled: " + isEnrolled);
System.out.printf("Total: %d / %d%n", totalScore, MAX_SCORE * SUBJECT_COUNT);
System.out.printf("Average: %.2f%n", average);
System.out.println("Total students: " + totalStudents);
}
}

Output:

=== Java Academy Report Card ===
Name: Alice Java
Age: 20
Grade: A
Enrolled: true
Total: 438 / 500
Average: 87.60
Total students: 1

10. Swapping Two Variables​

A classic programming pattern. Use a temporary variable (temp).

public class SwapExample {
public static void main(String[] args) {
int x = 10;
int y = 20;

System.out.println("Before swap: x=" + x + ", y=" + y); // x=10, y=20

// Swap using a temporary variable
int temp = x; // temp = 10
x = y; // x = 20
y = temp; // y = 10

System.out.println("After swap: x=" + x + ", y=" + y); // x=20, y=10

// Swap using arithmetic (integers only, no temp needed)
int a = 100, b = 200;
a = a + b; // a = 300
b = a - b; // b = 100
a = a - b; // a = 200
System.out.println("Arithmetic swap: a=" + a + ", b=" + b); // a=200, b=100
}
}
tip

Pro tip: XOR-based swap is also possible but hurts readability. The temp variable approach is the standard in practice.

Summary​

  • A variable is a named memory space for storing one value
  • Declaration: type variableName; / Initialization: variableName = value;
  • Variable categories: local (inside method), instance (inside class), class (static)
  • Scope: a variable is valid only within the block {...} where it was declared
  • final: creates a constant β€” the value cannot be changed after assignment
  • var: Java 10+, type inference for local variables
  • Overflow: exceeds range β†’ silently wraps to the opposite end (no error!)