Data Types in Java with Examples

  • Last updated Apr 25, 2024

In Java, a data type specifies the type of values that a variable can hold. It defines the operations that can be done on those values and how the memory for that value is allocated. Java provides several built-in data types to handle different kinds of values. In Java, data types can be broadly classified into two types:

  1. Primitive Data Types: Primitive types are the most basic data types in Java. They are built-in and provided by Java.
  2. Non-Primitive Data Types (Reference Types): Non-Primitive data types are not built into the language but are created using classes. Non-primitive data types, also known as reference types, can refer to strings, classes, and arrays. Instead of storing values directly, they hold a reference to the value in memory. The default value of a reference variable is null.
Primitive Data Types

Java provides eight primitive data types. The following table shows each primitive data type, along with its storage size and the range of values it can hold:

Data Type Size Range
byte
8 bit
Can store value from -128 to 127
short
16-bit
Can store value from -32,768 to 32,767
int
32-bit
Can store value from -2,147,483,648 to 2,147,483,647
long
64-bit
Can store from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float
32-bit single-precision
Store value from 3.402,823,5 E+38 to 1.4 E-45
double
64-bit double-precision
Can store value from 1.797,693,134,862,315,7 E+308 to 4.9 E-324
boolean
1-bit
Can store true or false
char
16-bit
Can store unicode character value from '\u0000' (or 0) to '\uffff'
Example:
public class StudentPerformance {
    
    public static void main(String[] args) {
        
        // 1. byte: Student's age
        byte age = 26;
        
        // 2. short: Total number of courses taken
        short totalCourses = 5;
        
        // 3. int: Year of admission
        int admissionYear = 2023;
        
        // 4. long: Student ID
        long studentId = 2023001L; // 'L' suffix denotes a long literal
        
        // 5. float: GPA (Grade Point Average)
        float gpa = 3.75f; // 'f' suffix denotes a float literal
        
        // 6. double: Total fees paid by the student
        double totalFeesPaid = 12500.50;
        
        // 7. char: Grade in the latest exam (e.g., 'A', 'B', 'C')
        char latestGrade = 'A';
        
        // 8. boolean: Status of scholarship (true if received, false otherwise)
        boolean hasScholarship = true;
        
        // Displaying student details
        System.out.println("Student Age: " + age + " years");
        System.out.println("Total Courses: " + totalCourses);
        System.out.println("Year of Admission: " + admissionYear);
        System.out.println("Student ID: " + studentId);
        System.out.println("GPA: " + gpa);
        System.out.println("Total Fees Paid: $" + totalFeesPaid);
        System.out.println("Latest Grade: " + latestGrade);
        System.out.println("Scholarship Status: " + (hasScholarship ? "Received" : "Not Received"));
    }
}

In this example, the byte type is used to represent the student's age. The short type indicates the total number of courses taken by the student. The int type is employed for the year of admission. The long type is utilized to store the unique student ID. The float type is chosen to store the student's GPA. The double type keeps track of the total fees paid by the student. The char type stores the grade the student received in the latest exam. The boolean type indicates whether the student has received a scholarship.

Output:
Student Age: 26 years
Total Courses: 5
Year of Admission: 2023
Student ID: 2023001
GPA: 3.75
Total Fees Paid: $12500.5
Latest Grade: A
Scholarship Status: Received
Non-Primitive Data Types (Reference Types)

The following table shows non-primitive data types in Java:

Data Type Description
String It represents a sequence of characters. The size can vary based on the number of characters in the string.
Arrays It represents collections of similar data types.
Classes These are user-defined data types that define objects. The size of a class instance can vary depending on its properties (instance variables).
Example:
public class CarDealership {

    public static void main(String[] args) {
        
        // String: Dealership's name
        String dealershipName = "City Auto Mall";
        
        // Class: Car information
        Car toyotaCamry = new Car("Toyota", "Camry", 2022, "Blue");
        
        // Array: List of cars in the showroom
        Car[] carsInShowroom = {
            new Car("Honda", "Civic", 2023, "Red"),
            new Car("Ford", "Mustang", 2022, "Black")
        };
        
        // Displaying dealership details
        System.out.println("Dealership Name: " + dealershipName);
        System.out.println("Featured Car: " + toyotaCamry.getMake() + " " + toyotaCamry.getModel() + " " + toyotaCamry.getYear() + ", Color: " + toyotaCamry.getColor());
        System.out.println("Cars in Showroom: ");
        for (Car car : carsInShowroom) {
            System.out.println("- " + car.getMake() + " " + car.getModel() + " " + car.getYear() + ", Color: " + car.getColor());
        }
    }
}

class Car {
    private String make;
    private String model;
    private int year;
    private String color;

    public Car(String make, String model, int year, String color) {
        this.make = make;
        this.model = model;
        this.year = year;
        this.color = color;
    }

    public String getMake() {
        return make;
    }

    public String getModel() {
        return model;
    }

    public int getYear() {
        return year;
    }

    public String getColor() {
        return color;
    }
}

In this example, the String type is used to store the name of the car dealership. A custom Car class is defined to represent car details, containing String and int data types. An array (Car[]) is used to store a list of cars available in the showroom.

Output:
Dealership Name: City Auto Mall
Featured Car: Toyota Camry 2022, Color: Blue
Cars in Showroom: 
- Honda Civic 2023, Color: Red
- Ford Mustang 2022, Color: Black
The Importance of Choosing the Right Data Type

Choosing the right data type in Java is important for several reasons:

  • Memory Efficiency: Different data types have different memory requirements. Using a data type that's too large can waste memory, while one that's too small can lead to data loss or unexpected behavior.
  • Performance: Correct data type usage can lead to faster program execution.
  • Data Integrity: Choosing the correct data type ensures that the data is stored and manipulated correctly. For instance, using the int data type for whole numbers ensures that fractional parts aren't mistakenly included.
  • Error Prevention: Using the wrong data type can lead to errors that are difficult to debug. For example, storing a large number in a byte variable can lead to overflow, and operations might not produce the expected results.
  • Interoperability: When working with other systems or libraries, ensuring that you use compatible data types can prevent data conversion issues and make integration smoother.
  • Resource Optimization: In some applications, especially those running on constrained environments (like embedded systems), choosing the right data type can help in optimizing resource usage.
Java is Strongly Typed and Type-safe

Java is strongly typed language which means a variable declared with an integer data type cannot be assigned a floating point number (a number with a decimal point).

Java language is designed to be type-safe which means all the data types declared in the program are checked during compilation so as to ensure that the operations are performed on right kind of data.

In summary, picking the right data type in Java is key to writing efficient, correct, and maintainable code. Using the correct data types ensures that your software behaves as expected.