β˜• Java

Java Data Types β€” Primitive & Non-Primitive

A complete beginner's guide to all Java data types β€” 8 primitive types, non-primitive reference types, sizes, ranges, default values, literals, wrapper classes, autoboxing, and type casting with working code examples.

πŸ“…

Last Updated

March 2026

⏱️

Read Time

18 min

🎯

Level

Beginner

Java Data Types β€” Overview

In the previous chapter, we learned about Java Blocks β€” code blocks, static blocks, instance blocks, and scope rules. Now we cover one of the most foundational topics in Java: Data Types.

Every variable in Java has a data type β€” it tells the compiler two things: what kind of value the variable can hold, and how much memory to allocate. Java is a statically typed language, which means you must declare the data type of every variable at compile time. This is what makes Java programs reliable, predictable, and fast.

  • β–Ά

    What you will learn: Both categories of Java data types, all 8 primitive types in depth, non-primitive reference types, Java literals, wrapper classes, autoboxing/unboxing, type casting, and how to choose the right type for your use case.

Two Categories of Java Data Types

Java data types fall into exactly two categories. Understanding the fundamental difference between them is the first step to mastering Java memory management and object-oriented programming.

FeaturePrimitive TypesNon-Primitive (Reference) Types
CountExactly 8Unlimited β€” all classes, interfaces, arrays, enums
Examplesbyte, short, int, long, float, double, char, booleanString, int[], Scanner, ArrayList, your own classes
StoresThe actual value directlyA memory address (reference) pointing to the object
Memory locationStackReference on stack; object data on heap
Can be null?No β€” always has a valueYes β€” reference can be null
Default value0, 0.0, false, '\u0000'null
Has methods?NoYes β€” all objects have methods
SizeFixed β€” defined by Java specNot fixed β€” depends on object structure
Extends Object?NoYes β€” all reference types extend java.lang.Object
PerformanceFaster β€” direct value accessSlightly slower β€” requires dereferencing
β˜• JavaPrimitive vs Reference β€” Memory Concept
// PRIMITIVE β€” value stored directly in the variable
int age = 21;          // 'age' holds the value 21 directly

// NON-PRIMITIVE β€” variable holds a reference (memory address)
String name = "Rahul"; // 'name' holds the address of the String object
                        // the actual characters 'R','a','h','u','l' are on the heap

// null means the reference variable points to nothing
String city = null;    // city holds no address β€” not pointing to any object

Primitive Data Types β€” All 8 Types

Java has exactly 8 primitive data types. Their sizes are fixed by the Java specification β€” unlike C/C++ where sizes can vary by platform. This platform independence is a key part of Java's Write Once, Run Anywhere guarantee.

TypeCategorySizeDefaultMin ValueMax ValueExample Literal
byteInteger1 byte (8 bits)0-128127byte b = 100;
shortInteger2 bytes (16 bits)0-32,76832,767short s = 5000;
intInteger4 bytes (32 bits)0-2,147,483,6482,147,483,647int i = 2026;
longInteger8 bytes (64 bits)0L-9,223,372,036,854,775,8089,223,372,036,854,775,807long l = 8000000000L;
floatFloating-Point4 bytes (32 bits)0.0f~1.4 Γ— 10⁻⁴⁡~3.4 Γ— 10³⁸float f = 3.14f;
doubleFloating-Point8 bytes (64 bits)0.0d~4.9 Γ— 10⁻³²⁴~1.8 Γ— 10³⁰⁸double d = 3.14159265;
charCharacter2 bytes (16 bits)'\u0000'0 (\u0000)65,535 (\uFFFF)char c = 'A';
booleanLogicalJVM-dependent (~1 bit)falsefalsetrueboolean flag = true;
πŸ”’
4 Integer Types

byte, short, int, long β€” for whole numbers. int is the default choice. Use long for very large numbers. Use byte/short only when memory is critically limited.

πŸ“
2 Floating-Point Types

float, double β€” for decimal numbers. double is the default choice (and the default for decimal literals). Use float only when memory is tightly constrained.

πŸ”€
1 Character Type

char β€” stores a single Unicode character using 16-bit UTF-16 encoding. Can also store any integer from 0 to 65,535 representing a Unicode code point.

βœ…
1 Boolean Type

boolean β€” stores only true or false. Used for conditions, flags, and logical decisions. Cannot be cast to/from numeric types (unlike C/C++).

Integer Types β€” byte, short, int, long

Java has four integer types for storing whole numbers (no decimal part). They differ only in size and therefore the range of values they can hold. int is the most commonly used integer type.

byte β€” 1 Byte

byte is the smallest integer type β€” 1 byte (8 bits). Range: -128 to 127. Used when memory saving is critical β€” in large arrays, file/network I/O streams, or image pixel data.

β˜• Javabyte Examples
byte minByte = -128;       // minimum value
byte maxByte =  127;       // maximum value
byte pixelValue = 64;      // grayscale pixel β€” 0 to 127 range
byte fileFlag  = 0x0A;     // hexadecimal literal β€” value is 10

// Overflow β€” byte wraps around
byte overflow = (byte) 128;  // 128 overflows β†’ becomes -128
System.out.println(overflow); // -128

short β€” 2 Bytes

short is 2 bytes (16 bits). Range: -32,768 to 32,767. Rarely used in modern Java β€” int is preferred unless you are working with binary protocols, audio samples, or legacy systems.

β˜• Javashort Examples
short minShort = -32768;    // minimum value
short maxShort =  32767;    // maximum value
short year     =  2026;     // fits comfortably in a short
short audioSample = 15000;  // raw PCM audio sample

int β€” 4 Bytes (Default Integer Type)

int is 4 bytes (32 bits). Range: -2,147,483,648 to 2,147,483,647 (about Β±2.1 billion). This is the default integer type in Java β€” integer literals like 42 are int by default. Use int for counting, indexing, loop variables, and general arithmetic.

β˜• Javaint Examples
int age        = 21;
int year       = 2026;
int population = 1400000000;   // India population β€” fits in int
int maxInt     = Integer.MAX_VALUE;  // 2147483647
int minInt     = Integer.MIN_VALUE;  // -2147483648

// Numeric literals with underscore (Java 7+) β€” for readability
int oneMillion  = 1_000_000;     // same as 1000000
int cardNumber  = 1234_5678_9012_3456;  // not valid β€” too large for int

// Integer arithmetic
int a = 10, b = 3;
System.out.println(a / b);   // 3  β€” integer division, truncates
System.out.println(a % b);   // 1  β€” remainder (modulo)

long β€” 8 Bytes

long is 8 bytes (64 bits). Range: -9.2 Γ— 10¹⁸ to 9.2 Γ— 10¹⁸. Use long when your value exceeds the int range β€” world population, millisecond timestamps, file sizes in bytes, database IDs. Must add L or l suffix to long literals (uppercase L preferred β€” lowercase l looks like 1).

β˜• Javalong Examples
long worldPopulation  = 8_100_000_000L;    // 8.1 billion β€” exceeds int
long fileSize         = 10_737_418_240L;   // 10 GB in bytes
long epochMs          = 1_700_000_000_000L; // Unix timestamp in ms
long maxLong          = Long.MAX_VALUE;     // 9223372036854775807

// Missing L suffix β€” compile error if value > Integer.MAX_VALUE
// long big = 8100000000;   ← ERROR: integer number too large
long big = 8_100_000_000L;  // βœ… correct with L suffix

System.out.println("World population: " + worldPopulation);

Output

World population: 8100000000

Floating-Point Types β€” float, double

Java has two floating-point types for storing decimal numbers. Both follow the IEEE 754 standard. The key difference is precision and memory size.

float β€” 4 Bytes, Single Precision

float is 4 bytes (32 bits) β€” single-precision IEEE 754. Accurate to approximately 7 significant decimal digits. Must add f or F suffix to float literals β€” otherwise the compiler treats them as double.

β˜• Javafloat Examples
float pi      = 3.14f;         // 'f' suffix required
float price   = 99.99f;
float tempC   = 36.6f;         // body temperature
float maxFloat = Float.MAX_VALUE;  // ~3.4 Γ— 10^38

// Without 'f' suffix β€” compile error
// float x = 3.14;   ← ERROR: possible lossy conversion from double to float

// Precision limitation of float
float f1 = 1.0f / 3.0f;
System.out.println(f1);   // 0.33333334  β€” only ~7 digits accurate

double β€” 8 Bytes, Double Precision (Default)

double is 8 bytes (64 bits) β€” double-precision IEEE 754. Accurate to approximately 15–16 significant decimal digits. Decimal literals like 3.14 are double by default. Prefer double for all general decimal calculations.

β˜• Javadouble Examples
double pi       = 3.141592653589793;  // no suffix needed
double salary   = 75000.50;
double distance = 384400.0;            // moon distance in km
double maxDouble = Double.MAX_VALUE;   // ~1.8 Γ— 10^308

// Better precision than float
double d1 = 1.0 / 3.0;
System.out.println(d1);  // 0.3333333333333333  β€” ~15 digits accurate

// Scientific notation literal
double avogadro = 6.022e23;   // 6.022 Γ— 10^23
double electron = 1.6e-19;    // 1.6 Γ— 10^-19 coulombs
System.out.println(avogadro); // 6.022E23

Output

0.3333333333333333 6.022E23
  • β–Ά

    ⚠️ Floating-point precision warning: Neither float nor double can represent all decimal values exactly β€” this is a property of IEEE 754 binary representation. Example: 0.1 + 0.2 does not equal exactly 0.3 in Java (or any language using IEEE 754). For exact decimal arithmetic (money, banking), use java.math.BigDecimal.

Featurefloatdouble
Size4 bytes (32 bits)8 bytes (64 bits)
Precision~7 significant digits~15–16 significant digits
Suffix required?Yes β€” f or FNo β€” optional d or D
Default for literals?NoYes β€” 3.14 is double
Memory usageLessMore
When to useMemory-critical; graphics; ML weightsGeneral decimal math β€” always prefer this
Special valuesFloat.NaN, Float.POSITIVE_INFINITYDouble.NaN, Double.POSITIVE_INFINITY

Character Type β€” char

char is a 2-byte (16-bit) unsigned integer that stores a single character using UTF-16 Unicode encoding. Range: 0 to 65,535 (Unicode code points \u0000 to \uFFFF). Unlike C/C++ where char is 1 byte (ASCII only), Java's char supports the full Unicode character set.

β˜• Javachar Examples
// Character literals β€” enclosed in SINGLE quotes
char letter  = 'A';
char digit   = '7';
char space   = ' ';
char newline = '\n';   // escape sequence
char tab     = '\t';   // escape sequence

// Unicode escape sequence
char rupee   = '\u20B9';  // β‚Ή Indian Rupee symbol
char heart   = '\u2665';  // β™₯ Heart symbol
char omega   = '\u03A9';  // Ξ© Omega symbol

// char can be treated as an unsigned integer
char ch = 'A';
System.out.println(ch);          // A
System.out.println((int) ch);    // 65 β€” ASCII/Unicode value of 'A'
System.out.println(ch + 1);      // 66 β€” arithmetic on char returns int
System.out.println((char)(ch + 1)); // B β€” cast back to char

// char arithmetic β€” classic use
for (char c = 'A'; c <= 'E'; c++) {
    System.out.print(c + " ");  // A B C D E
}

Output

A 65 66 B A B C D E

Common Escape Sequences for char

Escape SequenceNameUnicodeUse Case
\nNewline\u000AMove to next line in output
\tTab\u0009Horizontal indentation
\rCarriage Return\u000DMove cursor to line start (Windows line endings)
\'Single Quote\u0027Literal single quote inside char literal: '\''
\"Double Quote\u0022Literal double quote inside String literal
\\Backslash\u005CLiteral backslash character: '\\'
\0Null Character\u0000Default value of char; string terminator in C β€” not Java
\uXXXXUnicode EscapeAnyAny Unicode character: '\u20B9' = β‚Ή

Boolean Type β€” boolean

boolean stores only two values: true or false. It is used for conditions, flags, control-flow decisions, and any binary state. The actual memory size is JVM-dependent (often treated as a 32-bit int internally for alignment, though it represents only 1 bit of information).

β˜• Javaboolean Examples
boolean isLoggedIn  = true;
boolean isExpired   = false;
boolean hasPassed   = true;

// Boolean from comparison expressions
int score = 85;
boolean distinction = score >= 90;   // false β€” 85 is not >= 90
boolean firstClass  = score >= 60;   // true

// Boolean in control flow
if (isLoggedIn) {
    System.out.println("Welcome back!");
}

// Boolean from method return
String name = "Java";
boolean startsWithJ = name.startsWith("J");  // true
boolean isEmpty     = name.isEmpty();           // false

System.out.println("Distinction : " + distinction);
System.out.println("First Class : " + firstClass);
System.out.println("Starts with J: " + startsWithJ);

Output

Welcome back! Distinction : false First Class : true Starts with J: true
  • β–Ά

    ⚠️ Java vs C/C++: In Java, boolean is not interchangeable with integers. You cannot write if (1) or cast a boolean to int. true and false are the only valid values β€” period.

  • β–Ά

    πŸ’‘ Naming convention: Boolean variables and methods are typically named with the is, has, can, or should prefix β€” isActive, hasPermission, canEdit β€” making the intent immediately clear.

Java Literals β€” Writing Values in Code

A literal is a fixed value written directly in the source code β€” the actual data itself, not a variable or expression. Java supports several forms of literals for different data types.

Integer Literals

β˜• JavaInteger Literal Forms
// Decimal (base 10) β€” default, no prefix
int decimal = 255;

// Binary (base 2) β€” prefix 0b or 0B  (Java 7+)
int binary  = 0b11111111;     // same as 255

// Octal (base 8) β€” prefix 0 (zero)
int octal   = 0377;           // same as 255

// Hexadecimal (base 16) β€” prefix 0x or 0X
int hex     = 0xFF;           // same as 255

// Underscore separator (Java 7+) β€” improves readability
int million    = 1_000_000;
long creditCard = 1234_5678_9012_3456L;
int rgb        = 0xFF_A5_00;  // orange color in hex

System.out.println(decimal + " " + binary + " " + octal + " " + hex);

Output

255 255 255 255

Floating-Point Literals

β˜• JavaFloating-Point Literal Forms
double d1 = 3.14;         // standard decimal β€” double by default
double d2 = 3.14d;        // explicit double suffix (optional)
float  f1 = 3.14f;        // float β€” 'f' suffix REQUIRED

// Scientific (exponential) notation
double avogadro = 6.022e23;    // 6.022 Γ— 10^23
double planck   = 6.626e-34;   // 6.626 Γ— 10^-34

// Special values
double posInf = Double.POSITIVE_INFINITY;  // 1.0 / 0.0
double negInf = Double.NEGATIVE_INFINITY;  // -1.0 / 0.0
double nan    = Double.NaN;                // 0.0 / 0.0 β€” Not a Number

System.out.println(1.0 / 0.0);   // Infinity
System.out.println(-1.0 / 0.0);  // -Infinity
System.out.println(0.0 / 0.0);   // NaN

Output

Infinity -Infinity NaN

char, boolean, and String Literals

β˜• JavaOther Literal Types
// char literal β€” SINGLE quotes, exactly ONE character
char grade   = 'A';
char unicode = '\u20B9';  // β‚Ή

// boolean literals β€” only two values
boolean t = true;
boolean f = false;

// String literal β€” DOUBLE quotes (non-primitive, but very common)
String name = "Tech Sustainify";

// Text Block (Java 15+) β€” multi-line String literal
String json = """
        {
            "name": "Java",
            "version": 21
        }
        """;

// null literal β€” for any reference type
String city = null;
Literal TypeSyntaxExample
Integer decimaldigitsint n = 42;
Integer binary0b + digitsint n = 0b101010;
Integer octal0 + digitsint n = 052;
Integer hex0x + digitsint n = 0x2A;
Longdigits + Llong n = 42L;
Floatdigits + ffloat f = 3.14f;
Doubledigits (no suffix)double d = 3.14;
Scientific notationdigits + e + expdouble d = 6.022e23;
charsingle quoteschar c = 'A';
booleantrue or falseboolean b = true;
Stringdouble quotesString s = "Hello";
nullnullString s = null;

Non-Primitive (Reference) Data Types

Non-primitive types are also called reference types because a variable of this type stores a reference (memory address) to where the object data lives on the heap β€” not the data itself. All non-primitive types ultimately extend java.lang.Object.

TypeDescriptionCreated withExample
StringImmutable sequence of characters. Most used type in Java.String literal or new String()String name = "Java";
ArrayFixed-size, ordered collection of same-type elements.new type[size] or { } literalint[] marks = {90, 85, 92};
ClassBlueprint for objects β€” groups state (fields) and behaviour (methods).new ClassName()Student s = new Student();
InterfaceContract β€” defines methods a class must implement.Implemented by a classRunnable r = () -> {};
EnumFixed set of named constants.Enum declarationDay d = Day.MONDAY;
RecordImmutable data carrier class (Java 16+).record declarationrecord Point(int x, int y) {}
β˜• JavaNon-Primitive Types Demo
import java.util.ArrayList;

public class NonPrimitiveDemo {
    public static void main(String[] args) {

        // String
        String language = "Java";
        System.out.println(language.length());       // 4
        System.out.println(language.toUpperCase());  // JAVA

        // Array
        int[] scores = {95, 82, 78, 91};
        System.out.println(scores[0]);               // 95
        System.out.println(scores.length);           // 4

        // null reference
        String city = null;
        System.out.println(city);                    // null
        // city.length();  ← NullPointerException at runtime!

        // ArrayList (class from java.util)
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Mango");
        fruits.add("Apple");
        System.out.println(fruits);   // [Mango, Apple]
    }
}

Output

4 JAVA 95 4 null [Mango, Apple]

String β€” Most Used Non-Primitive Type

String is by far the most commonly used non-primitive type in Java. It represents an immutable sequence of Unicode characters. Once created, a String's value cannot be changed β€” any modification creates a new String object.

β˜• JavaString Essentials
// Two ways to create a String
String s1 = "Hello";                // String literal β€” stored in String Pool
String s2 = new String("Hello");    // new object on heap β€” NOT recommended

// String is immutable
String name = "Java";
name.toUpperCase();          // does NOT change 'name'
System.out.println(name);    // Java β€” unchanged
name = name.toUpperCase();   // reassign the reference to a new String
System.out.println(name);    // JAVA

// String concatenation
String firstName = "Rahul";
String lastName  = "Sharma";
String fullName  = firstName + " " + lastName;  // "Rahul Sharma"

// Useful String methods
System.out.println(fullName.length());          // 12
System.out.println(fullName.charAt(0));         // R
System.out.println(fullName.contains("Rahul")); // true
System.out.println(fullName.replace("Rahul", "Priya")); // Priya Sharma
System.out.println(fullName.substring(6));      // Sharma
System.out.println(fullName.toLowerCase());     // rahul sharma
System.out.println("  Java  ".trim());          // Java

// == vs .equals() for Strings
String a = "Java";
String b = "Java";
String c = new String("Java");
System.out.println(a == b);         // true  β€” same pool object
System.out.println(a == c);         // false β€” different heap objects
System.out.println(a.equals(c));    // true  β€” same content
  • β–Ά

    ⚠️ Always use .equals() to compare String content β€” not ==. The == operator compares references (memory addresses), not the actual characters. This is one of the most common beginner bugs in Java.

  • β–Ά

    πŸ’‘ String Pool: When you write String s = "Java", Java checks if "Java" already exists in the String Pool (a special area of the heap). If yes, the same object is reused β€” no new allocation. This is why String a = "Java"; String b = "Java"; gives a == b β†’ true.

Wrapper Classes & Autoboxing / Unboxing

Wrapper classes are object representations of Java's 8 primitive types. They exist because many parts of Java (like collections, generics, reflection) require objects, not primitives. Every primitive type has exactly one corresponding wrapper class.

PrimitiveWrapper ClassPackageKey Utility Methods
byteBytejava.langByte.parseByte(str), Byte.MAX_VALUE, Byte.MIN_VALUE
shortShortjava.langShort.parseShort(str), Short.MAX_VALUE
intIntegerjava.langInteger.parseInt(str), Integer.MAX_VALUE, Integer.toBinaryString(n)
longLongjava.langLong.parseLong(str), Long.MAX_VALUE, Long.toBinaryString(n)
floatFloatjava.langFloat.parseFloat(str), Float.MAX_VALUE, Float.isNaN(f)
doubleDoublejava.langDouble.parseDouble(str), Double.MAX_VALUE, Double.isInfinite(d)
charCharacterjava.langCharacter.isLetter(c), Character.isDigit(c), Character.toUpperCase(c)
booleanBooleanjava.langBoolean.parseBoolean(str), Boolean.TRUE, Boolean.FALSE

Autoboxing and Unboxing (Java 5+)

Autoboxing is the automatic conversion of a primitive to its wrapper class. Unboxing is the reverse β€” automatic conversion of a wrapper to its primitive. Java does this conversion automatically wherever needed.

β˜• JavaWrapper Classes & Autoboxing Demo
import java.util.ArrayList;

public class WrapperDemo {
    public static void main(String[] args) {

        // --- Autoboxing: primitive β†’ Wrapper ---
        int primitiveInt  = 42;
        Integer wrappedInt = primitiveInt;   // autoboxed automatically
        System.out.println(wrappedInt);      // 42

        // --- Unboxing: Wrapper β†’ primitive ---
        Integer wrapperVal = 100;
        int primitiveVal   = wrapperVal;     // unboxed automatically
        System.out.println(primitiveVal);    // 100

        // --- ArrayList requires objects, not primitives ---
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);   // autoboxed: int 10 β†’ Integer(10)
        numbers.add(20);
        numbers.add(30);
        int sum = 0;
        for (int n : numbers) {   // each Integer is unboxed to int
            sum += n;
        }
        System.out.println("Sum: " + sum);  // 60

        // --- Wrapper utility methods ---
        String numStr  = "2026";
        int    parsed  = Integer.parseInt(numStr);   // String β†’ int
        String binary  = Integer.toBinaryString(255); // "11111111"
        String hex     = Integer.toHexString(255);    // "ff"
        System.out.println(parsed);   // 2026
        System.out.println(binary);   // 11111111
        System.out.println(hex);      // ff

        // --- Character utility ---
        char ch = 'a';
        System.out.println(Character.isLetter(ch));    // true
        System.out.println(Character.toUpperCase(ch)); // A
        System.out.println(Character.isDigit('5'));     // true
    }
}

Output

42 100 Sum: 60 2026 11111111 ff true A true
  • β–Ά

    ⚠️ Autoboxing performance: Autoboxing creates new objects on the heap. In performance-critical loops, avoid autoboxing millions of times β€” it adds GC pressure. Use primitive arrays instead of ArrayList<Integer> when performance matters.

  • β–Ά

    ⚠️ NullPointerException trap: If a wrapper variable is null and you try to unbox it, Java throws a NullPointerException. Example: Integer x = null; int y = x; β†’ NullPointerException at runtime.

Type Casting β€” Widening & Narrowing

Type casting is the process of converting a value from one data type to another. Java supports two kinds of casting for primitive types β€” and they behave very differently.

1. Widening Casting (Implicit / Automatic)

Converting a smaller type to a larger type. Java does this automatically β€” no code needed, no data loss. The hierarchy: byte β†’ short β†’ int β†’ long β†’ float β†’ double

β˜• JavaWidening Casting
byte   b = 42;
short  s = b;       // byte  β†’ short  (auto)
int    i = s;       // short β†’ int    (auto)
long   l = i;       // int   β†’ long   (auto)
float  f = l;       // long  β†’ float  (auto)
double d = f;       // float β†’ double (auto)

System.out.println("byte   : " + b);  // 42
System.out.println("short  : " + s);  // 42
System.out.println("int    : " + i);  // 42
System.out.println("long   : " + l);  // 42
System.out.println("float  : " + f);  // 42.0
System.out.println("double : " + d);  // 42.0

// char to int β€” char's Unicode value is used
char  ch  = 'A';
int   val = ch;    // char β†’ int (auto)
System.out.println(val);  // 65

Output

byte : 42 short : 42 int : 42 long : 42 float : 42.0 double : 42.0 65

2. Narrowing Casting (Explicit / Manual)

Converting a larger type to a smaller type. Must be done manually by writing the target type in parentheses. Data loss may occur β€” the extra bits are simply discarded.

β˜• JavaNarrowing Casting
double d = 9.99;
int    i = (int) d;       // double β†’ int: decimal truncated (not rounded)
System.out.println(d);    // 9.99
System.out.println(i);    // 9  ← 0.99 is lost

// int to byte β€” overflow may occur
int  bigInt = 130;
byte b      = (byte) bigInt;  // 130 is outside byte range (-128 to 127)
System.out.println(b);         // -126  ← data corruption due to overflow

// Narrowing the full chain
double source = 1234.56;
long   toLong = (long) source;   // 1234
int    toInt  = (int)  toLong;   // 1234
short  toShort= (short)toInt;    // 1234  (fits)
byte   toByte = (byte) toShort;  // 1234 % 256 = 210 β†’ wraps to -46

System.out.println("double β†’ long  : " + toLong);
System.out.println("long   β†’ int   : " + toInt);
System.out.println("int    β†’ short : " + toShort);
System.out.println("short  β†’ byte  : " + toByte);

Output

9.99 9 -126 double β†’ long : 1234 long β†’ int : 1234 int β†’ short : 1234 short β†’ byte : -46
FeatureWidening (Implicit)Narrowing (Explicit)
DirectionSmall type β†’ Large typeLarge type β†’ Small type
SyntaxAutomatic β€” no extra codeManual β€” (targetType) value
Data loss?NoYes β€” truncation or overflow possible
Exampleint i = 42; double d = i;double d = 9.9; int i = (int) d;
Compile error?NoYes if you forget the cast operator
Runtime error?NoNo β€” but result may be unexpected

How to Choose the Right Data Type

Choosing the right data type makes your code correct, efficient, and readable. Here is a practical decision guide for real-world Java development:

πŸ”’
Whole Numbers β†’ int by default

Use int for counters, ages, IDs, indices, loop variables. Switch to long only when values might exceed 2.1 billion β€” timestamps, file sizes, world-scale counts.

πŸ“
Decimal Numbers β†’ double by default

Use double for prices, measurements, scientific values, percentages. Only use float if memory is critically constrained (GPU buffers, ML model weights).

πŸ’°
Money / Exact Decimals β†’ BigDecimal

Never use float or double for money β€” they cannot represent 0.1 exactly. Use java.math.BigDecimal for financial calculations requiring exact precision.

πŸ”€
Single Character β†’ char

Use char for individual characters, grade letters, menu options. For sequences of characters always use String.

βœ…
True/False States β†’ boolean

Use boolean for flags, conditions, enable/disable switches. Name it with is/has/can prefix: isActive, hasRole, canEdit.

🏷️
Small Memory-Critical β†’ byte/short

Use byte for raw binary data, file I/O buffers, image pixels, network packets. Use short only in legacy protocols or large arrays where each byte matters.

ScenarioRecommended TypeReason
Age of a personintMax ~150, always whole number β€” int is the default
World populationlong8.1 billion exceeds int's max of 2.1 billion
Product price (β‚Ή99.99)doubleDecimal needed; double is default for decimal math
Bank account balanceBigDecimalExact decimal required β€” float/double have rounding errors
Student pass/failbooleanOnly two states β€” true or false
Grade letter (A, B, C)charSingle character
Student nameStringSequence of characters
Pixel color value (0–255)byte or intbyte saves memory; int is simpler for arithmetic
Unix timestamp (milliseconds)longMilliseconds since 1970 exceeds int range
Loop counterintStandard β€” int is default for indices
Scientific measurementdoubleHigh precision needed; double provides ~15 digits
Raw network packet databyte[]Network protocols work in bytes

Complete Java Program β€” Putting It All Together

Let us write one complete program that uses all 8 primitive types, String, arrays, wrapper class utility, and type casting β€” all in a single realistic student information system.

β˜• JavaStudentProfile.java
import java.util.Scanner;

/**
 * StudentProfile.java
 * Demonstrates all 8 primitive types, String, array, wrapper classes,
 * literals, and type casting in one realistic program.
 */
public class StudentProfile {

    // Class constants using appropriate types
    static final int    MAX_MARKS    = 100;
    static final double PASS_PERCENT = 40.0;
    static final char   HIGHEST_GRADE = 'O';

    public static void main(String[] args) {

        // ---- 8 PRIMITIVE TYPES ----
        byte  rollNumber = 42;              // byte: small whole number
        short batchYear  = 2026;            // short: year fits in short
        int   studentId  = 1_00_001;        // int: large ID with underscore
        long  aadhaarNum = 1234_5678_9012L; // long: 12-digit Aadhaar
        float attendance = 87.5f;           // float: percentage
        double gpa       = 8.75;            // double: GPA precision
        char  section    = 'A';             // char: section label
        boolean isActive = true;            // boolean: enrollment status

        // ---- STRING ----
        String name    = "Rahul Sharma";
        String course  = "B.Tech CSE";
        String college = "Tech Sustainify University";

        // ---- ARRAY ----
        int[] subjectMarks = {88, 92, 79, 95, 85};

        // ---- CALCULATIONS using appropriate types ----
        int totalMarks = 0;
        for (int mark : subjectMarks) {
            totalMarks += mark;
        }
        double percentage = (totalMarks / (double)(subjectMarks.length * MAX_MARKS)) * 100;

        // ---- TYPE CASTING ----
        int roundedGpa  = (int) gpa;           // narrowing: 8.75 β†’ 8
        double longToDouble = (double) studentId; // widening: int β†’ double

        // ---- WRAPPER CLASS UTILITY ----
        String gpaStr   = Double.toString(gpa);      // double β†’ String
        String idBinary = Integer.toBinaryString(studentId % 256); // binary
        char   sectionUpper = Character.toUpperCase(section); // already upper

        // ---- GRADE using char ----
        char grade;
        if      (percentage >= 90) grade = 'O';   // Outstanding
        else if (percentage >= 75) grade = 'A';
        else if (percentage >= 60) grade = 'B';
        else if (percentage >= PASS_PERCENT) grade = 'C';
        else                       grade = 'F';

        boolean hasPassed = percentage >= PASS_PERCENT;

        // ---- DISPLAY ----
        System.out.println("╔══════════════════════════════════════╗");
        System.out.println("β•‘          STUDENT PROFILE             β•‘");
        System.out.println("╠══════════════════════════════════════╣");
        System.out.printf ("β•‘ Name      : %-24sβ•‘%n", name);
        System.out.printf ("β•‘ Course    : %-24sβ•‘%n", course);
        System.out.printf ("β•‘ College   : %-24sβ•‘%n", college);
        System.out.printf ("β•‘ Roll No   : %-24dβ•‘%n", (int) rollNumber);
        System.out.printf ("β•‘ Section   : %-24cβ•‘%n", sectionUpper);
        System.out.printf ("β•‘ Batch     : %-24dβ•‘%n", (int) batchYear);
        System.out.printf ("β•‘ GPA       : %-24sβ•‘%n", gpaStr);
        System.out.printf ("β•‘ GPA (int) : %-24dβ•‘%n", roundedGpa);
        System.out.printf ("β•‘ Attendance: %-23.1f%%β•‘%n", attendance);
        System.out.printf ("β•‘ Total     : %-24dβ•‘%n", totalMarks);
        System.out.printf ("β•‘ Percentage: %-23.2f%%β•‘%n", percentage);
        System.out.printf ("β•‘ Grade     : %-24cβ•‘%n", grade);
        System.out.printf ("β•‘ Status    : %-24sβ•‘%n", hasPassed ? "PASS" : "FAIL");
        System.out.printf ("β•‘ Active    : %-24bβ•‘%n", isActive);
        System.out.println("β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•");

Output

╔══════════════════════════════════════╗ β•‘ STUDENT PROFILE β•‘ ╠══════════════════════════════════════╣ β•‘ Name : Rahul Sharma β•‘ β•‘ Course : B.Tech CSE β•‘ β•‘ College : Tech Sustainify Universityβ•‘ β•‘ Roll No : 42 β•‘ β•‘ Section : A β•‘ β•‘ Batch : 2026 β•‘ β•‘ GPA : 8.75 β•‘ β•‘ GPA (int) : 8 β•‘ β•‘ Attendance: 87.5% β•‘ β•‘ Total : 439 β•‘ β•‘ Percentage: 87.80% β•‘ β•‘ Grade : A β•‘ β•‘ Status : PASS β•‘ β•‘ Active : true β•‘ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

Practice This Code β€” Live Editor

Java Data Types β€” Interview Questions

These are the most frequently asked Java interview questions on data types β€” from beginner to intermediate level.

Practice Questions β€” Test Your Knowledge

Test your understanding of Java Data Types. Try to answer each question before revealing the answer.

1. What is the output? int a = 5; int b = 2; System.out.println(a / b); System.out.println(a % b);

Easy

2. Will this compile? long l = 3000000000; Explain.

Medium

3. What is the output? char c = 'A'; System.out.println(c + 1); System.out.println((char)(c + 1));

Medium

4. What data type would you use to store a 12-digit Aadhaar number? Why?

Easy

5. What is the output and why? double d = 0.1 + 0.2; System.out.println(d); System.out.println(d == 0.3);

Medium

6. What is the difference between String s1 = 'Java' and String s2 = new String('Java')? Which is better?

Medium

7. What is the result of (byte)(200)? Explain the calculation.

Hard

8. Can you store the value 65535 in a char? Can you store -1 in a char?

Hard

Summary β€” What You Learned in Java Data Types

You have now mastered the complete Java type system β€” from the 8 primitive types to non-primitive reference types, wrapper classes, literals, and casting. Here is a quick recap:

TopicKey Takeaway
Two categoriesPrimitive (8 types, store value) vs Non-Primitive (store reference)
byte1 byte, -128 to 127 β€” raw data, I/O buffers, pixel values
short2 bytes, -32768 to 32767 β€” rarely used; legacy protocols
int4 bytes, Β±2.1 billion β€” default integer type for most use cases
long8 bytes, Β±9.2 Γ— 10¹⁸ β€” timestamps, IDs, large counts; needs L suffix
float4 bytes, ~7 digits β€” memory-constrained decimals; needs f suffix
double8 bytes, ~15 digits β€” default decimal type; no suffix needed
char2 bytes, 0–65535 β€” single Unicode character; single quotes only
booleantrue or false only β€” not interchangeable with int unlike C/C++
StringImmutable; use .equals() for comparison, never ==
Wrapper ClassesByte, Short, Integer, Long, Float, Double, Character, Boolean β€” for collections, parsing, utility
Autoboxing/UnboxingAutomatic primitive ↔ wrapper conversion; beware null unboxing NPE
Literals0b prefix=binary, 0x=hex, 0=octal, _ separator for readability
Widening CastingAutomatic, no data loss: byte→short→int→long→float→double
Narrowing CastingManual (targetType)value β€” may lose data; truncates decimals
Money/Exact decimalsNever use float/double β€” use BigDecimal for financial calculations

The next step is understanding Java Variables in depth β€” declaration, initialization, scope, naming rules, the var keyword, and the difference between local, instance, and static variables. Continue to the next chapter: Java Variables β†’

Frequently Asked Questions (FAQ) β€” Java Data Types