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:
- ›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 counter2. 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.300000000000000043. 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:
trueorfalse— 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
| Type | Size | Range / Values | Default | Use For |
|---|---|---|---|---|
int | 4 bytes | ±2.1 billion | 0 | Whole numbers (most common) |
double | 8 bytes | ±1.8 × 10³⁰⁸ | 0.0 | Decimal numbers |
boolean | 1 bit | true / false | false | Conditions and flags |
char | 2 bytes | 0 – 65,535 | '\u0000' | Single characters |
long | 8 bytes | ±9.2 quintillion | 0L | Very large whole numbers |
float | 4 bytes | ±3.4 × 10³⁸ | 0.0f | Decimal (prefer double) |
byte | 1 byte | −128 to 127 | 0 | Raw binary data |
short | 2 bytes | −32,768 to 32,767 | 0 | Rarely 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 characterString 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 usedString 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:
In plain English:
- ›Whole number →
int(orlongif 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; // ✅ correct2. Using double quotes for char
char grade = "A"; // ❌ error — double quotes = String
char grade = 'A'; // ✅ correct — single quotes for char3. Forgetting the L suffix for large long values
long population = 8000000000; // ❌ error — too large for int literal
long population = 8000000000L; // ✅ correct4. Forgetting the f suffix for float
float rate = 0.05; // ❌ error — 0.05 is a double literal
float rate = 0.05f; // ✅ correct5. Using uninitialized local variables
int count;
System.out.println(count); // ❌ error — not initialized
int count = 0;
System.out.println(count); // ✅ works6. 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
- ›The 4 you'll use most —
intfor whole numbers,doublefor decimals,booleanfor true/false,Stringfor text. Master these four first. - ›Primitives store values; reference types store addresses —
int age = 25stores25directly.String name = "Arjun"stores a reference to the String object in memory. - ›Suffixes matter for literals —
longvalues needL(8000000000L),floatvalues needf(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—trueorfalseonly. Used for conditions and flags - ›
char— single character in single quotes. Stores Unicode values - ›
long— whole numbers up to ±9.2 quintillion. NeedsLsuffix on literals - ›
float— less precise decimal. Needsfsuffix. Preferdoublein 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
Learn how to store and reuse values in Java.
Practice Programs
Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.
Adds two fixed integers and prints the result.
Divides one fixed integer by another and prints the result.
Computes the area of a circle from its radius using the formula π × r².
Finds the remainder left over when one integer is divided by another.
Shows the two meanings of char-to-int conversion: a character's code versus a digit's numeric value.
Converts a temperature from Fahrenheit to Celsius using the standard formula.
Converts a distance from kilometers to miles using the standard conversion factor.
Converts a distance from miles to kilometers using the standard conversion factor.
Computes pay by multiplying an hourly rate by the number of hours worked.
Computes gross salary by summing basic pay, HRA, DA, and other fixed allowances.
Show all 13 practice programs ↓Show fewer ↑
Computes a discount amount by applying a single flat discount percentage to a price.
Computes an electricity bill by multiplying units consumed by a single flat rate per unit.
Finds a person's age in years from their birth year and the current year.