Loading

Programming data types define the kind of data a variable can hold. They determine the operations that can be performed on the data and how it is stored in memory.


In Java, data types are divided into two main categories:

  1. Primitive Data Types
  2. Reference Data Types 

Primitive Data Types

Primitive data types are predefined by the language and named by a keyword. They are the most basic data types available within the Java language. 

There are eight primitive data types in Java:

Data TypeSizeDefault ValueRange / Values
boolean~1 bytefalsetrue or false
byte1 byte0-128 to 127
short2 bytes0-32,768 to 32767
int4 bytes0
-2^31 to 2^31-1
long8 bytes0L
-2^63 to 2^63-1
float4 bytes0.0fUp to 7 decimal places
double8 bytes0.0dUp to 15 decimal places
char2 bytes'\u0000'unicode characters (0 to 65,535)



Reference Data Types

Reference types in Java are any objects created from classes. 

   They are used to access objects and include:

  1. Class Objects: Instances of classes, e.g., String, Scanner.
  2. Array: Objects that store multiple items of the same type.
  3. Interface: Defines a contract that classes can implement.
  4. Enumeration: A special Java type used to define collections of constants.

Key Differences Between Primitive and Reference Data Types:

  • Memory: Primitive data types are stored directly in the memory locations allocated for variables, while reference types store references (or addresses) to the objects in memory.
  • Default Values: Primitive data types have default values (e.g., 0 for integers, false for boolean). Reference types have a default value of null.
  • Methods: Primitive data types do not have methods associated with them, whereas objects of reference types do.

Examples:

Here's a basic example to illustrate the use of primitive and reference data types:

public class DataTypesExample {
    public static void main(String[] args) {
        // Primitive data types
        int age = 25;
        char grade = 'A';
        boolean isJavaFun = true;
        double price = 19.99;

        // Reference data types
        String name = "John";
        int[] scores = {90, 85, 88};

        // Output
        System.out.println("Age: " + age);
        System.out.println("Grade: " + grade);
        System.out.println("Is Java Fun: " + isJavaFun);
        System.out.println("Price: " + price);
        System.out.println("Name: " + name);
        System.out.print("Scores: ");
        for (int score : scores) {
            System.out.print(score + " ");
        }
    }
}

In this example:

  • int, char, boolean, and double are primitive data types.
  • String and int[] (array of integers) are reference data types.