Back to Curriculum

Variables and Data Types

📚 Lesson 2 of 16 ⏱️ 30 min

Variables and Data Types

30 min

Java is a statically-typed language, meaning all variables must be declared with their data type before they can be used. This type safety catches errors at compile time rather than runtime, making programs more reliable. The compiler enforces type rules, preventing many common programming errors. Understanding Java's type system is fundamental to writing correct Java code.

Primitive data types include: byte, short, int, long, float, double, boolean, and char. These types store actual values (not references) and have fixed sizes. Integer types (byte, short, int, long) store whole numbers with different ranges. Floating-point types (float, double) store decimal numbers with different precision. boolean stores true/false, and char stores a single Unicode character. Choosing the right type affects memory usage and performance.

Reference types include classes, interfaces, and arrays. String is a special reference type that's commonly used. Reference types store references (addresses) to objects in memory, not the objects themselves. This means multiple variables can reference the same object. Understanding the difference between primitives and references is crucial for avoiding bugs related to object sharing and mutation.

Understanding data type ranges and memory usage is crucial for performance optimization. Using the smallest appropriate type (e.g., byte instead of int) can save memory in large arrays. However, modern JVMs are optimized, so premature optimization is usually unnecessary. More important is choosing types that clearly express intent and prevent errors. Understanding type ranges helps avoid overflow bugs.

Java supports type conversion (casting) between compatible types. Implicit conversions happen automatically for widening conversions (e.g., int to long), while explicit casting is required for narrowing conversions (e.g., long to int). Casting can cause data loss or overflow, so it must be done carefully. Understanding casting rules helps avoid runtime errors and data loss.

Variable scope determines where a variable can be accessed. Local variables exist only within their block (method, loop, etc.). Instance variables belong to object instances. Class (static) variables belong to the class itself. Understanding scope prevents bugs from accessing variables where they don't exist and helps design better APIs. Proper variable naming and scope management are essential for maintainable code.

Key Concepts

  • Java is statically typed—variables must be declared with types.
  • Primitive types store values directly (byte, int, double, boolean, char).
  • Reference types store references to objects (classes, arrays, String).
  • Type conversion (casting) is required for narrowing conversions.
  • Variable scope determines where variables can be accessed.

Learning Objectives

Master

  • Declaring variables with appropriate types
  • Understanding primitive vs reference types
  • Performing type conversions and casting
  • Understanding variable scope and lifetime

Develop

  • Understanding type safety and its benefits
  • Choosing appropriate types for different use cases
  • Designing code with proper variable scope

Tips

  • Use descriptive variable names that indicate purpose and type.
  • Prefer int and double for most numeric operations (simpler, JVM optimized).
  • Use final for constants: final int MAX_SIZE = 100.
  • Initialize variables before use to avoid compilation errors.

Common Pitfalls

  • Using wrong data type, causing overflow or precision loss.
  • Confusing == with .equals() for reference types (especially String).
  • Not understanding that reference types can be null.
  • Using primitive types when wrapper classes are needed (e.g., in collections).

Summary

  • Java is statically typed with primitive and reference types.
  • Primitive types store values, reference types store object references.
  • Type conversion requires explicit casting for narrowing conversions.
  • Understanding types and scope is essential for correct Java code.

Exercise

Declare variables of different types and demonstrate type conversion.

public class Variables {
    public static void main(String[] args) {
        int age = 25;
        double height = 1.75;
        String name = "John";
        boolean isStudent = true;
        
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Height: " + height + "m");
        System.out.println("Is Student: " + isStudent);
    }
}

Code Editor

Output