Chapter 516 min read

Java Variables & Data Types

Understanding memory scopes, primitive types, reference data types, and console I/O in Java.

Released1995
Core MottoStatically-Typed Memory Management
CreatorsOracle / Sun Microsystems

1. What is a Java Variable?

A variable provides named memory storage that programs can manipulate.
The declared data type determines memory size, layout, value range, and legal operations.

Declaration & Initialization Syntax

Strict Declaration:Variables must be declared before use with a specified data type.
Initialization:Use the assignment operator (=) to set initial values. Statements must end with a semicolon (;).
java
// Standard Syntax: data_type variableName = value;
int age = 18;
double pi = 3.14159;
char grade = 'A';
int x, y, z; // Declaration of multiple variables of the same type

2. The Three Java Variable Scopes

Java variables are categorized by scope and lifetime:Local, Instance, and Class/Static variables.

1. Local Variables

Scope & Lifetime:Declared inside methods, constructors, or blocks. Created on method entry and destroyed on exit.
Stack Storage:Implemented internally on the stack.
Strict Rule:No default values. Must be initialized before reading, or compilation fails.
java
public class LocalExample {
    public void calculateAge() {
        int age = 0; // MUST be initialized
        age = age + 7;
        System.out.println("Puppy age is: " + age);
    }
}

2. Instance Variables

Scope & Lifetime:Declared inside a class but outside methods/blocks. Created when an object is instantiated with 'new' (stored in Heap memory).
Default Values:Numeric types default to 0, booleans to false, and object references to null.
java
public class Employee {
    public String name;    // Visible to child classes
    private double salary; // Visible inside Employee class only

    public Employee(String empName) {
        name = empName;
    }

    public void setSalary(double empSal) {
        salary = empSal;
    }
}

3. Class / Static Variables

Single Shared Copy:Declared with the 'static' keyword. Only one copy exists in static memory regardless of object instances.
Constants:Frequently combined with 'public static final' (written in UPPERCASE).
java
public class DepartmentInfo {
    private static double avgSalary;
    public static final String DEPARTMENT = "Development"; // Constant

    public static void main(String args[]) {
        avgSalary = 1000;
        System.out.println(DEPARTMENT + " Avg Salary: " + avgSalary);
    }
}
Classroom Discussion Starter
Why do local variables require explicit initialization while instance variables automatically default to zero or null?
Takeaway Goal: Instance variables are allocated in heap memory during object creation where JVM safety defaults apply, whereas local variables reside on short-lived stack frames where uninitialized reads present memory risk.

3. Primitive Data Types

Java supports 8 built-in primitive data types divided into integers, decimals, characters, and booleans.

8 Built-in Primitive Types

byte:8-bit signed integer (-128 to 127). Default: 0
short:16-bit signed integer (-32,768 to 32,767). Default: 0
int:32-bit signed integer (-2,147,483,648 to 2,147,483,647). Default: 0
long:64-bit signed integer (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807). Default: 0L
float:32-bit single-precision IEEE 754 decimal. Default: 0.0f
double:64-bit double-precision decimal (default for floating point). Default: 0.0d
boolean:Represents 1 bit of truth value (true or false). Default: false
char:Single 16-bit Unicode character ('\u0000' to '\uffff'). Default: '\u0000'
java
public class PrimitiveDemo {
    public static void main(String[] args) {
        byte b = 100;
        short s = 10000;
        int i = 100000;
        long l = 100000L;
        float f = 234.5f;
        double d = 123.4;
        boolean isJavaFun = true;
        char letter = 'A';

        System.out.println("Int: " + i + ", Double: " + d + ", Char: " + letter);
    }
}

4. Reference (Non-Primitive) Data Types

Reference types hold memory pointers/references to objects created on the heap rather than raw values.

Reference Type Categories

Strings:Sequences of characters provided by the java.lang.String class.
Arrays:Fixed-size heap objects storing uniform element sequences.
Classes & Interfaces:Custom user-defined dynamic structures.
Default State:All unassigned reference variables hold a default null reference.
java
// Reference Variable Demonstrations
String greeting = new String("Hello, World!");
int[] numbers = {1, 2, 3, 4, 5};
Employee emp = new Employee("Ransika"); // Object Reference

5. User Input with the Scanner Class

The Scanner class (java.util.Scanner) enables console programs to read dynamic user input from System.in.
Essential for parsing primitives and strings interactively during program execution.

Scanner Setup & Essential Parsing Methods

Import Directive:Requires 'import java.util.Scanner;' at the top of the file.
Instantiation:Create a reference object with 'Scanner input = new Scanner(System.in);'.
Primitive Methods:Use nextInt(), nextDouble(), nextBoolean() to parse specific primitive data types.
String Methods:Use next() for a single word or nextLine() to capture an entire sentence with spaces.
java
import java.util.Scanner; // 1. Import the Scanner utility

public class InputMethodsDemo {
    public static void main(String[] args) {
        // 2. Instantiate Scanner object bound to system keyboard stream
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter your age: ");
        int age = sc.nextInt(); // Reads an integer primitive

        System.out.print("Enter your GPA: ");
        double gpa = sc.nextDouble(); // Reads a double primitive

        sc.nextLine(); // Consume trailing newline character left behind by nextDouble()

        System.out.print("Enter your full name: ");
        String fullName = sc.nextLine(); // Reads complete line of text

        System.out.println("
--- Captured Profile ---");
        System.out.println("Name: " + fullName + " | Age: " + age + " | GPA: " + gpa);

        sc.close(); // Close stream to release system resources
    }
}

Interactive Application Example

Combining Local Variables & Scanner I/O:Capturing user input directly into variables for dynamic logic execution.
java
import java.util.Scanner;

public class InteractiveUserSystem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("==================================");
        System.out.println("   STUDENT DATA CAPTURE SYSTEM    ");
        System.out.println("==================================");

        System.out.print("Enter Student ID Number: ");
        int studentId = scanner.nextInt();
        scanner.nextLine(); // Consume newline

        System.out.print("Enter Student Full Name: ");
        String studentName = scanner.nextLine();

        System.out.print("Enter Tuition Fee Balance: ");
        double feeBalance = scanner.nextDouble();

        System.out.print("Is Enrolled Status (true/false): ");
        boolean isEnrolled = scanner.nextBoolean();

        // Displaying captured input back to console
        System.out.println("
--- RECORD SUMMARY GENERATED ---");
        System.out.println("ID: #" + studentId);
        System.out.println("Name: " + studentName);
        System.out.println("Balance: $" + feeBalance);
        System.out.println("Active Enrolment: " + isEnrolled);

        scanner.close();
    }
}
Classroom Discussion Starter
Why does invoking sc.nextLine() immediately after sc.nextInt() or sc.nextDouble() sometimes seem to 'skip' user input?
Takeaway Goal: Methods like nextInt() only read numeric tokens and leave the newline character (\n) produced by pressing Enter in the input stream. Calling nextLine() immediately consumes that leftover newline, returning an empty String unless cleared first.