Back to posts

Types of Variables in Java

Erik Nguyen / September 2, 2024

Types of Variables in Java

1. Primitive Data Types

These are the basic types of data built into the language:

  • int: Integer (e.g., int age = 30;)
  • double: Double-precision floating-point (e.g., double price = 19.99;)
  • float: Single-precision floating-point (e.g., float temperature = 36.6f;)
  • char: Character (e.g., char grade = 'A';)
  • boolean: True or false (e.g., boolean isActive = true;)
  • byte: 8-bit integer (e.g., byte b = 100;)
  • short: 16-bit integer (e.g., short s = 1000;)
  • long: 64-bit integer (e.g., long l = 100000L;)

2. Reference Data Types

These refer to objects and can be any instance of a class:

  • String: Represents a sequence of characters (e.g., String name = "John";)
  • Arrays: A collection of similar types (e.g., int[] numbers = {1, 2, 3};)
  • Classes: Custom data types defined by the user (e.g., MyClass obj = new MyClass();)
  • Interfaces: A reference type in Java that can contain only constants, method signatures, default methods, static methods, and nested types.

3. Variable Scope Types

Variables can also be categorized based on their scope:

  • Local Variables: Declared within a method or block and can only be accessed within that method/block.
  • Instance Variables: Declared inside a class but outside any method and are tied to an instance of the class.
  • Static Variables: Declared with the static keyword and belong to the class rather than any instance.

Summary

Java variables can be classified into primitive and reference types, with further categorization based on their scope. Understanding these types is essential for effective programming in Java.