Start Coding Now

Data Types in Java - Primitive & Reference Types Explained

Complete guide to Java data types. Learn about primitive types (int, double, boolean, char) and reference types with examples.

Introduction

Data types in Java define what kind of values a variable can hold. Understanding data types is crucial for writing correct and efficient Java programs.

Primitive Data Types

Java has 8 primitive data types divided into 4 categories:

Integer Types

TypeSizeRangeDefault
byte1 byte-128 to 1270
short2 bytes-32,768 to 32,7670
int4 bytes-2^31 to 2^31-10
long8 bytes-2^63 to 2^63-10L
public class IntegerTypes {
    public static void main(String[] args) {
        byte b = 100;
        short s = 10000;
        int i = 100000;
        long l = 10000000000L; // Note the L suffix
        
        System.out.println("byte: " + b);
        System.out.println("short: " + s);
        System.out.println("int: " + i);
        System.out.println("long: " + l);
    }
}

Floating-Point Types

TypeSizePrecisionDefault
float4 bytes6-7 decimal digits0.0f
double8 bytes15-16 decimal digits0.0d
public class FloatingTypes {
    public static void main(String[] args) {
        float price = 99.99f; // Note the f suffix
        double pi = 3.14159265358979;
        
        System.out.println("Price: " + price);
        System.out.println("PI: " + pi);
    }
}

Character Type

public class CharType {
    public static void main(String[] args) {
        char letter = 'A';
        char unicode = '\u0041'; // Also 'A'
        char number = 65; // Also 'A' (ASCII value)
        
        System.out.println(letter);
        System.out.println(unicode);
        System.out.println(number);
    }
}

Boolean Type

public class BooleanType {
    public static void main(String[] args) {
        boolean isJavaFun = true;
        boolean isFishTasty = false;
        
        System.out.println("Is Java fun? " + isJavaFun);
        System.out.println("Is fish tasty? " + isFishTasty);
    }
}

Reference Types

Reference types hold references to objects rather than the actual values.

String

String name = "JavaCompiler.in";
String greeting = new String("Hello");

Arrays

int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[3];

Objects

Student student = new Student();

Summary

  • Java has 8 primitive types for basic values
  • Reference types hold object references
  • Choose the right type for your data needs
  • Use int for most integer operations, double for decimals

Frequently Asked Questions

What are primitive data types in Java?

Java has 8 primitive data types: byte, short, int, long (integers), float, double (decimals), char (characters), and boolean (true/false).

What is the difference between int and Integer?

int is a primitive type that stores the actual value, while Integer is a wrapper class (reference type) that wraps the int value in an object. Integer can be null, int cannot.