Java Tutorial
🔍

Java Data Types

Every value in a Java program has a type.

The type tells Java two things: what kind of data is stored, and how much memory to reserve for it. Declare a variable without a type and Java refuses to compile. Use the wrong type and your program produces incorrect results or crashes.

Understanding data types is foundational — every concept that follows in Java (variables, operators, methods, collections) depends on types working correctly.

👉 What you'll learn here:

  • ›The 8 primitive data types and when to use each
  • ›The difference between primitive types and reference types
  • ›Value ranges and what happens when you exceed them
  • ›Type defaults and why they matter
  • ›How to choose the right type for your situation

🧘 You don't need to memorize every range on this page.

Focus on understanding int, double, boolean, and char — those four cover 90% of what you'll write as a beginner. The others exist for specific situations and you'll reach for them naturally when needed.

Two Categories of Data Types

Java has two categories of data types:

JAVA DATA TYPE CATEGORIES Primitive Types 8 built-in types Store the value directly in memory int · double · boolean · char long · float · byte · short int age = 25; Reference Types Classes, Arrays, Interfaces Store a reference (address) to the data String · int[] · ArrayList Scanner · any class you create String name = "Arjun";
  • ›Primitive types — store the actual value directly. There are exactly 8, built into Java itself.
  • ›Reference types — store the memory address of an object, not the object itself. Includes String, arrays, and any class.

💡 Quick way to tell them apart: Primitive type names are all lowercase (int, double, boolean). Reference type names start with uppercase (String, Scanner, ArrayList). There is one exception — String is a reference type but is so commonly used it feels like a primitive.

The 8 Primitive Data Types

1. int — Whole Numbers

The most commonly used numeric type. Stores whole numbers (no decimal point).

int age = 25; int score = -100; int population = 1400000000; int zero = 0;
  • ›Size: 4 bytes
  • ›Range: −2,147,483,648 to 2,147,483,647 (roughly ±2.1 billion)
  • ›Default value: 0

💡 Use int for: counting, ages, scores, quantities, loop counters — any whole number that fits within ±2 billion.

// Common uses of int: int studentCount = 60; int year = 2025; int temperature = -5; for (int i = 0; i < 10; i++) { ... } // loop counter

2. double — Decimal Numbers

The standard type for numbers with decimal points. "Double" refers to double-precision floating point.

double price = 99.99; double pi = 3.14159265; double salary = 75000.50; double temperature = -12.5;
  • ›Size: 8 bytes
  • ›Range: approximately ±1.8 × 10³⁰⁸ (enormous)
  • ›Precision: ~15 significant decimal digits
  • ›Default value: 0.0

💡 Use double for: prices, measurements, scientific values, percentages — any number that needs a decimal point.

// Common uses of double: double accountBalance = 10250.75; double gpa = 8.6; double discountRate = 0.15; double circleArea = Math.PI * radius * radius;

⚠️ Floating point precision: double is approximate, not exact. Never use double for precise financial calculations where exact decimal arithmetic is required — use BigDecimal instead.

System.out.println(0.1 + 0.2); // prints: 0.30000000000000004

3. boolean — True or False

Stores exactly one of two values: true or false. Named after mathematician George Boole.

boolean isLoggedIn = true; boolean hasDiscount = false; boolean isAdult = age >= 18; // result of a comparison boolean isPassed = score >= 35;
  • ›Size: 1 bit (stored as 1 byte in practice)
  • ›Values: true or false — nothing else
  • ›Default value: false

💡 Use boolean for: flags, conditions, on/off states, results of comparisons.

// Common uses of boolean: boolean isEmailValid = email.contains("@"); boolean isWeekend = (day == 6 || day == 7); boolean accountActive = true; if (isLoggedIn) { System.out.println("Welcome back!"); }

⚠️ Java vs other languages: In Java, boolean only accepts true or false — not 1, 0, "yes", or any other value. if (1) is a compile error in Java.

4. char — Single Characters

Stores exactly one character. The value must be wrapped in single quotes (not double quotes).

char grade = 'A'; char initial = 'J'; char symbol = '@'; char digit = '5'; // the character '5', not the number 5 char newline = '\n'; // escape character — moves to next line
  • ›Size: 2 bytes
  • ›Range: 0 to 65,535 (stores Unicode characters)
  • ›Default value: '\u0000' (null character)
// Single quotes for char: char letter = 'A'; // ✅ correct char letter = "A"; // ❌ error — double quotes = String // Common escape characters: char tab = '\t'; // horizontal tab char newline = '\n'; // new line char quote = '\''; // single quote character char slash = '\\'; // backslash character

💡 Use char for: representing individual characters — grades, initials, symbols. For text with more than one character, use String instead.

5. long — Large Whole Numbers

Use long when int is not big enough. Holds much larger whole numbers.

long worldPopulation = 8000000000L; // ← note the L suffix long distanceToMoon = 384400000L; long fileSize = 9876543210L;
  • ›Size: 8 bytes
  • ›Range: −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (roughly ±9.2 quintillion)
  • ›Default value: 0L

⚠️ The L suffix is required: When you write a number larger than int's range, Java needs to know it's a long literal. Append L (uppercase is preferred over l to avoid confusion with the digit 1).

long big = 8000000000; // ❌ error — Java treats this as int literal, overflows long big = 8000000000L; // ✅ correct

💡 Use long for: timestamps, file sizes, population counts, any whole number that might exceed ±2.1 billion.

6. float — Single-Precision Decimal

Less precise than double. Rarely needed in modern Java.

float temperature = 36.6f; // ← note the f suffix float discount = 0.15f;
  • ›Size: 4 bytes
  • ›Precision: ~7 significant decimal digits (half the precision of double)
  • ›Default value: 0.0f

⚠️ The f suffix is required: Without it, Java treats the literal as a double, causing a compile error.

float temp = 36.6; // ❌ error — 36.6 is a double literal float temp = 36.6f; // ✅ correct

💡 Use double instead of float in almost every situation. float is used in specific contexts where memory is extremely tight (graphics programming, large float arrays) — not in general-purpose code.

7. byte — Small Integers

The smallest integer type. Used when memory efficiency is critical.

byte smallNumber = 100; byte age = 25; byte[] imageData = new byte[1024]; // common use — raw data buffers
  • ›Size: 1 byte
  • ›Range: −128 to 127
  • ›Default value: 0

💡 Use byte for: raw binary data, file streams, network communication, large arrays where memory matters. Don't use it just to save memory on a single variable — the difference is negligible.

8. short — Medium-Small Integers

Between byte and int. Rarely used in modern Java.

short year = 2025; short port = 8080;
  • ›Size: 2 bytes
  • ›Range: −32,768 to 32,767
  • ›Default value: 0

💡 Use int instead in almost every situation. short exists mainly for compatibility with legacy systems and protocols that use 16-bit integers.

All 8 Primitive Types — Quick Reference

TypeSizeRange / ValuesDefaultUse For
int4 bytes±2.1 billion0Whole numbers (most common)
double8 bytes±1.8 × 10³⁰⁸0.0Decimal numbers
boolean1 bittrue / falsefalseConditions and flags
char2 bytes0 – 65,535'\u0000'Single characters
long8 bytes±9.2 quintillion0LVery large whole numbers
float4 bytes±3.4 × 10³⁸0.0fDecimal (prefer double)
byte1 byte−128 to 1270Raw binary data
short2 bytes−32,768 to 32,7670Rarely used

Reference Types — String and Beyond

Reference types are everything that isn't a primitive — classes, arrays, interfaces, and enums. The most important reference type for beginners is String.

String — Text

String stores a sequence of characters — words, sentences, names, any text.

String name = "Arjun"; String greeting = "Hello, World!"; String empty = ""; String sentence = "Java is fun to learn.";

Key difference from char: char stores one character with single quotes. String stores any amount of text with double quotes.

char letter = 'A'; // one character, single quotes String word = "Apple"; // multiple characters, double quotes String oneChar = "A"; // also valid — String with one character

String is technically a class (reference type), not a primitive — but it's used so frequently that Java gives it special treatment, including the ability to create one without new:

String name = "Arjun"; // shorthand — Java creates the String object String name = new String("Arjun"); // explicit — same result, rarely used

String Concatenation

Join two Strings (or a String and a number) with +:

String firstName = "Arjun"; String lastName = "Kumar"; String fullName = firstName + " " + lastName; System.out.println(fullName); // Arjun Kumar int age = 25; System.out.println("Age: " + age); // Age: 25

⚠️ Addition vs concatenation: When + is used with two numbers, it adds. When at least one operand is a String, it concatenates.

System.out.println(10 + 20); // 30 (addition) System.out.println("Result: " + 10 + 20); // Result: 1020 (concatenation!) System.out.println("Result: " + (10 + 20)); // Result: 30 (addition first)

Type Defaults — What Happens Without Initialization

Every data type has a default value — the value Java assigns automatically if you declare a variable but don't initialize it.

// Class-level (instance/static) variables get defaults: public class Defaults { int number; // defaults to 0 double price; // defaults to 0.0 boolean active; // defaults to false char letter; // defaults to '\u0000' String name; // defaults to null }

⚠️ Local variables do NOT get defaults. Variables declared inside a method must be explicitly initialized before use. Using an uninitialized local variable is a compile error:

public static void main(String[] args) { int count; System.out.println(count); // ❌ error: variable count might not have been initialized int score = 0; // ✅ initialized System.out.println(score); // works fine }

Choosing the Right Type

Most situations follow a simple decision tree:

CHOOSING THE RIGHT DATA TYPE What kind of value? True/False Number Text True/False Has decimal? → double Whole number? → int (or long) 1 character → char Multiple chars → String → boolean For very large whole numbers: use long instead of int For precise financial calculations: use BigDecimal instead of double

In plain English:

  • ›Whole number → int (or long if very large)
  • ›Decimal number → double
  • ›True or false → boolean
  • ›One character → char
  • ›Text / words → String

Common Beginner Mistakes

1. Using int for decimal values

int price = 9.99; // ❌ error — 9.99 is not a whole number double price = 9.99; // ✅ correct

2. Using double quotes for char

char grade = "A"; // ❌ error — double quotes = String char grade = 'A'; // ✅ correct — single quotes for char

3. Forgetting the L suffix for large long values

long population = 8000000000; // ❌ error — too large for int literal long population = 8000000000L; // ✅ correct

4. Forgetting the f suffix for float

float rate = 0.05; // ❌ error — 0.05 is a double literal float rate = 0.05f; // ✅ correct

5. Using uninitialized local variables

int count; System.out.println(count); // ❌ error — not initialized int count = 0; System.out.println(count); // ✅ works

6. Confusing + addition with + concatenation

System.out.println("Sum: " + 5 + 3); // Sum: 53 (not 8!) System.out.println("Sum: " + (5 + 3)); // Sum: 8 (correct)

Putting It All Together

public class DataTypesDemo { public static void main(String[] args) { // Whole number int age = 22; // Decimal number double gpa = 8.75; // True or false boolean isEnrolled = true; // Single character char grade = 'A'; // Text String name = "Priya"; // Large whole number long universityId = 202400123456L; // Print all values System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("GPA: " + gpa); System.out.println("Grade: " + grade); System.out.println("Enrolled: " + isEnrolled); System.out.println("ID: " + universityId); } }

Output:

Name: Priya Age: 22 GPA: 8.75 Grade: A Enrolled: true ID: 202400123456

The 3 Things to Remember From This Page

  1. ›The 4 you'll use most — int for whole numbers, double for decimals, boolean for true/false, String for text. Master these four first.
  2. ›Primitives store values; reference types store addresses — int age = 25 stores 25 directly. String name = "Arjun" stores a reference to the String object in memory.
  3. ›Suffixes matter for literals — long values need L (8000000000L), float values need f (3.14f). Without them, the compiler misidentifies the type and throws an error.

Summary

  • ›Java has two categories of data types: 8 primitive types and reference types
  • ›8 primitive types: int, double, boolean, char, long, float, byte, short
  • ›int — whole numbers up to ±2.1 billion. Most commonly used numeric type
  • ›double — decimal numbers with ~15 digits of precision. Default for decimals
  • ›boolean — true or false only. Used for conditions and flags
  • ›char — single character in single quotes. Stores Unicode values
  • ›long — whole numbers up to ±9.2 quintillion. Needs L suffix on literals
  • ›float — less precise decimal. Needs f suffix. Prefer double in most cases
  • ›String — reference type for text. Not a primitive, but treated specially by Java
  • ›Local variables have no default — they must be initialized before use

What to Read Next

Practice Programs

Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.

Show all 13 practice programs ↓
Browse all Java programs →