Chuyển đến nội dung chính

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:
  2. short:
    • Size: 16-bit
    • Range: -32,768 to 32,767
    • Usage: Suitable for saving memory in large arrays.
    • short s = 10000;
  3. int:
  4. long:
  5. float:
  6. double:
  7. boolean:
  8. char:

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.