Skip to content
Concept ยท Software Development

Java data types explained: primitives, wrappers and casting

Younus FardeenBy Younus FardeenUpdated 1 Dec 20268 min read
Short answer

Java has two kinds of data types: eight primitive types (byte, short, int, long, float, double, char, boolean) that hold plain values, and reference types (classes, arrays, interfaces) that hold addresses of objects. Wrapper classes such as Integer turn primitives into objects. Casting converts between types, and narrowing casts can lose data.

On this pageThe eight primitive types in JavaReference types: String, arrays, classesWrapper classes, autoboxing and the Integer cache trapType casting: widening, narrowing and overflowvar, and the errors you will actually seeFrequently asked questions

This page is for students learning Java who need the type system straight before interviews and labs. Ranges and rules were checked on 1 December 2026 against the Java Language Specification (Java SE 25) and Oracle's primitive data types tutorial.

The Java snippets were proofread but not run, because no Java runtime was installed on the machine used. One Python block models the casting and overflow results using plain arithmetic and was run on Python 3.9.6. Basics of syntax live in Java syntax basics; this page is only about types.

The eight primitive types in Java

A primitive holds a value directly and is never null. Java fixes the size of each numeric type on every machine, which is why int is always 32 bits.

TypeSizeRange or valuesDefault (fields)Typical use
byte8-bit-128 to 1270Raw data, large arrays where memory matters
short16-bit-32768 to 327670Rarely used
int32-bit-2147483648 to 21474836470Default whole number
long64-bit-9223372036854775808 to 92233720368547758070LLarge counts, timestamps
float32-bit IEEE 754Largest finite value (2 - 2^-23) x 2^127, about 3.4 x 10^380.0fMemory-tight decimals
double64-bit IEEE 754Largest finite value (2 - 2^-52) x 2^1023, about 1.8 x 10^3080.0dDefault decimal number
char16-bit unsigned0 to 65535 ('\u0000' to '\uffff')'\u0000'A single UTF-16 code unit
booleanNot precisely definedtrue or falsefalseFlags and conditions

Two details the Oracle tutorial states and interviewers like: float and double should never hold money (use java.math.BigDecimal), and the size of boolean is not precisely defined even though it carries one bit of information. Local variables have no default value: the compiler refuses to let you read one before assigning it.

Reference types: String, arrays, classes

A reference variable holds the address of an object on the heap, or null. Classes, interfaces, arrays and enums are reference types. String is the one you meet first. It is a class, not a primitive, and a String object cannot be changed after creation.

QuestionPrimitiveReference
What does the variable hold?The value itselfAn address of an object, or null
Can it be null?NoYes
Compared with ==Compares valuesCompares whether both point to the same object
Compared with .equals()Not availableCompares contents when the class overrides it (String and Integer do)
Works as a generic type argument?No: List<int> is an errorYes: List<Integer>

That last row is the reason wrapper classes exist. For how this shows up in interviews, see Java interview questions.

Wrapper classes, autoboxing and the Integer cache trap

Each primitive has a wrapper: byte to Byte, short to Short, int to Integer, long to Long, float to Float, double to Double, char to Character and boolean to Boolean. Autoboxing is the compiler converting a primitive to its wrapper (Integer x = 5;), and unboxing is the reverse.

Trap 1: == on wrappers

The Language Specification (section 5.1.7) guarantees only that boxing a value from -128 to 127 (and true, false, and chars up to '\u007f') always gives the same object. Outside that range, whether two boxes are the same object is not promised. On a default HotSpot JVM, 128 boxes to two different objects.

public class CacheDemo {
    public static void main(String[] args) {
        Integer a = 127, b = 127;
        Integer c = 128, d = 128;
        System.out.println(a == b);        // true
        System.out.println(c == d);        // false on a default HotSpot JVM
        System.out.println(c.equals(d));   // true
        System.out.println(c.intValue() == d.intValue());   // true
    }
}

Expected output, proofread and not run: true, false, true, true. The rule: compare wrappers with .equals(), never ==.

Trap 2: unboxing null

import java.util.HashMap;
import java.util.Map;

public class UnboxDemo {
    public static void main(String[] args) {
        Map<String, Integer> marks = new HashMap<>();
        marks.put("Asha", 81);
        int ok = marks.get("Asha");        // fine: unboxes 81
        int bad = marks.get("Ravi");       // NullPointerException: get returns null, unboxing fails
    }
}

Map.get returns null for a missing key, and assigning null to an int forces an unbox that throws NullPointerException. Use getOrDefault or check for null.

Trap 3: boxing inside a hot loop

Declaring Long sum = 0L; and adding in a loop creates a new object on many iterations. Use the primitive long for accumulators and keep wrappers for collections and nullable values.

Type casting: widening, narrowing and overflow

Widening goes from a smaller to a larger type and happens automatically: byte to short to int to long to float to double, and char to int. Narrowing goes the other way, needs an explicit cast, and can lose data. The block below uses Python arithmetic to reproduce what Java's rules give. It is a model of the rules, not Java.

# Python modelling Java's rules. This is arithmetic, not Java.
def int32(x):
    return (x + 2**31) % 2**32 - 2**31      # wrap into the 32-bit signed range

def to_byte(x):
    return (x + 128) % 256 - 128            # wrap into the 8-bit signed range

print(int32(2147483647 + 1))                # int overflow: Integer.MAX_VALUE + 1
print(to_byte(200))                         # (byte) 200
print(int(3.99), int(-3.99))                # (int) 3.99 and (int) -3.99 truncate toward zero
print(ord("A"), chr(ord("a") + 1))          # (int) 'A' and (char) ('a' + 1)
print(10 // 4, 10 / 4)                      # 10 / 4 on ints, then 10 / 4.0
print(0.1 + 0.2)                            # same IEEE 754 double result Java prints
print(int32(1_000_000 * 1_000_000))         # int * int overflows before any widening
Java expressionResultWhat happened
(int) 3.993Fraction truncated toward zero
(int) -3.99-3Truncated toward zero, not rounded down
(byte) 200-56Low 8 bits kept, read as signed
Integer.MAX_VALUE + 1-2147483648int overflow wraps silently
1000000 * 1000000-727379968Multiplied as int, overflowed, then widened
long big = 1000000 * 1000000;-727379968Widening happens after the overflow; write 1000000L * 1000000
10 / 4 and 10 / 4.02 and 2.5Integer division drops the fraction
(int) 'A' and (char) ('a' + 1)65 and bchar is a number underneath
0.1 + 0.20.30000000000000004Binary floating point; use BigDecimal for money

References cast too, but between a class and its parents or children. A wrong downcast throws ClassCastException at run time; test with instanceof first.

var, and the errors you will actually see

var (Java 10 onward) lets the compiler infer a local variable's type from its initialiser. It is not dynamic typing: the type is fixed at compile time. It works only for local variables, not fields, parameters or return types.

import java.util.ArrayList;

public class VarDemo {
    public static void main(String[] args) {
        var count = 10;                          // int
        var price = 99.5;                        // double
        var names = new ArrayList<String>();     // ArrayList<String>
        names.add("Asha");
        // var x;            error: cannot infer type for local variable x
        // var y = null;     error: cannot infer type for local variable y
    }
}
Compiler or runtime messageCauseFix
incompatible types: possible lossy conversion from double to intint x = 3.5;Cast (int) 3.5 if you mean to truncate, or use double
incompatible types: possible lossy conversion from double to floatfloat f = 3.14; (3.14 is a double)Write 3.14f
integer number too largelong n = 3000000000;Write 3000000000L
variable might not have been initializedReading a local before assigning itAssign a value first
NullPointerExceptionUnboxing null or calling a method on nullCheck for null; prefer getOrDefault
ClassCastExceptionDowncasting to the wrong classCheck with instanceof

If you can explain each row without looking, you are ready for most data-type questions. Practise them on small programs from the software development projects list, and compare Java's strictness with Python in Python vs Java.

Frequently asked questions

How many data types are there in Java?

Two categories: eight primitive types (byte, short, int, long, float, double, char, boolean) and reference types, which include classes, interfaces, arrays and enums. String is a class, so it is a reference type, even though the language gives it special syntax such as string literals.

What is the range of int in Java?

An int is a 32-bit signed two's complement integer: from -2147483648 to 2147483647. Adding 1 to the maximum does not raise an error; it wraps to -2147483648. Use long, or Math.addExact, when values might exceed the range.

Why does Integer 127 == 127 give true but 128 == 128 give false?

The language guarantees that boxing integers from -128 to 127 returns the same cached object, so == is true. Above that, each boxing may create a new object, so == compares different references. On a default JVM, 128 gives false. Always compare wrappers with equals().

What is the difference between primitive and wrapper types?

A primitive such as int holds a raw value, cannot be null and works only in arithmetic. A wrapper such as Integer is an object: it can be null, can be used in collections and generics, and has methods like parseInt and compareTo. Autoboxing converts between them automatically.

What is type casting in Java?

Type casting converts a value from one type to another. Widening (int to long) is automatic and safe. Narrowing (double to int) needs an explicit cast such as (int) 3.99 and can lose data or overflow. Reference casts between classes are checked at run time.

Is String a primitive data type in Java?

No. String is a class in java.lang, so it is a reference type. It is immutable: methods like toUpperCase return a new String instead of changing the original. Java gives it literal syntax and the + operator, which is why it feels primitive.

Does var make Java dynamically typed?

No. var only asks the compiler to infer the type of a local variable from its initial value, and that type is fixed at compile time. var x = 10; makes x an int for good. It cannot be used without an initialiser or with null.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Interview prep

Java interview questions

40 model answers from basics to virtual threads, with the Java version noted

11 min read
Explainer

Java syntax basics

Program structure, types, loops, methods and common errors.

3 min read
Concept

Python vs Java

Same three programs in both languages, plus a decision table by goal.

6 min read