Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming

Java Data Types

Java data types are the foundation of data manipulation in Java programming. They define the size and type of values that can be stored in a variable. Java is a statically typed language, meaning every variable must be declared with a data type before use. Java data types are categorized into two main groups: primitive data types and reference data types.

Primitive Data Types

Primitive data types are the most basic data types available in Java. There are eight primitive data types, each serving a specific purpose:

  1. byte:
    • Size: 8-bit
    • Range: -128 to 127
    • Usage: Memory-efficient storage in large arrays.
    • byte b = 100;
  2. short:
    • Size: 16-bit
    • Range: -32,768 to 32,767
    • Usage: Suitable for saving memory in large arrays.
    • short s = 10000;
  3. int:
    • Size: 32-bit
    • Range: -231 to 231-1
    • Usage: Default choice for integer values.
    • int i = 100000;
  4. long:
    • Size: 64-bit
    • Range: -263 to 263-1
    • Usage: For large integer values.
    • long l = 100000L;
  5. float:
    • Size: 32-bit
    • Usage: For fractional numbers, with single precision.
    • float f = 234.5f;
  6. double:
    • Size: 64-bit
    • Usage: For fractional numbers, with double precision.
    • double d = 123.4;
  7. boolean:
    • Values: true or false
    • Usage: For simple flags and conditions.
    • boolean flag = true;
  8. char:
    • Size: 16-bit
    • Range: 0 to 65,535 (Unicode characters)
    • Usage: For storing characters.
    • char c = 'A';

Reference Data Types

Reference data types are objects that store references to the actual data. They include classes, interfaces, and arrays. Unlike primitive data types, reference data types do not store the value directly.

Example: Class and Array

public class ReferenceExample {
    public static void main(String[] args) {
        String str = "Hello, World!"; // Class type
        int[] numbers = {1, 2, 3, 4, 5}; // Array type

        System.out.println(str);
        for (int num : numbers) {
            System.out.println(num);
        }
    }
}

In this example, str is a reference variable of type String, and numbers is an array of integers.

Tips and Best Practices

  • Choose Appropriate Types: Use the most appropriate data type for your needs to optimize performance and memory usage.
  • Default to int: Use int for integer calculations unless there is a specific need for other integer types.
  • Use double for Precision: Prefer double for decimal values unless memory constraints dictate otherwise.
  • Boolean for Conditions: Always use boolean for flags and conditions to improve code readability.
  • Prefer Reference Types for Flexibility: Use reference types when you need the flexibility of methods and properties.