Java Tutorial
🔍

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).

Java
1int age = 25; 2int score = -100; 3int population = 1400000000; 4int 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.

Java
1// Common uses of int: 2int studentCount = 60; 3int year = 2025; 4int temperature = -5; 5for (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.

Java
1double price = 99.99; 2double pi = 3.14159265; 3double salary = 75000.50; 4double 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.

Java
1// Common uses of double: 2double accountBalance = 10250.75; 3double gpa = 8.6; 4double discountRate = 0.15; 5double 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.

Java
1System.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.

Java
1boolean isLoggedIn = true; 2boolean hasDiscount = false; 3boolean isAdult = age >= 18; // result of a comparison 4boolean 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.

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

⚠️ 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).

Java
1char grade = 'A'; 2char initial = 'J'; 3char symbol = '@'; 4char digit = '5'; // the character '5', not the number 5 5char newline = '\n'; // escape character — moves to next line
  • Size: 2 bytes
  • Range: 0 to 65,535 (stores Unicode characters)
  • Default value: '\u0000' (null character)
Java
1// Single quotes for char: 2char letter = 'A'; // ✅ correct 3char letter = "A"; // ❌ error — double quotes = String 4 5// Common escape characters: 6char tab = '\t'; // horizontal tab 7char newline = '\n'; // new line 8char quote = '\''; // single quote character 9char 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.

Java
1long worldPopulation = 8000000000L; // ← note the L suffix 2long distanceToMoon = 384400000L; 3long 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).

Java
1long big = 8000000000; // ❌ error — Java treats this as int literal, overflows 2long 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.

Java
1float temperature = 36.6f; // ← note the f suffix 2float 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.

Java
1float temp = 36.6; // ❌ error — 36.6 is a double literal 2float 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.

Java
1byte smallNumber = 100; 2byte age = 25; 3byte[] 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.

Java
1short year = 2025; 2short 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.

Java
1String name = "Arjun"; 2String greeting = "Hello, World!"; 3String empty = ""; 4String 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.

Java
1char letter = 'A'; // one character, single quotes 2String word = "Apple"; // multiple characters, double quotes 3String 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:

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

String Concatenation

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

Java
1String firstName = "Arjun"; 2String lastName = "Kumar"; 3String fullName = firstName + " " + lastName; 4System.out.println(fullName); // Arjun Kumar 5 6int age = 25; 7System.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.

Java
1System.out.println(10 + 20); // 30 (addition) 2System.out.println("Result: " + 10 + 20); // Result: 1020 (concatenation!) 3System.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.

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

⚠️ 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:

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

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 numberint (or long if very large)
  • Decimal numberdouble
  • True or falseboolean
  • One characterchar
  • Text / wordsString

Common Beginner Mistakes

1. Using int for decimal values

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

2. Using double quotes for char

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

3. Forgetting the L suffix for large long values

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

4. Forgetting the f suffix for float

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

5. Using uninitialized local variables

Java
1int count; 2System.out.println(count); // ❌ error — not initialized 3 4int count = 0; 5System.out.println(count); // ✅ works

6. Confusing + addition with + concatenation

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

Putting It All Together

Java
1public class DataTypesDemo { 2 public static void main(String[] args) { 3 4 // Whole number 5 int age = 22; 6 7 // Decimal number 8 double gpa = 8.75; 9 10 // True or false 11 boolean isEnrolled = true; 12 13 // Single character 14 char grade = 'A'; 15 16 // Text 17 String name = "Priya"; 18 19 // Large whole number 20 long universityId = 202400123456L; 21 22 // Print all values 23 System.out.println("Name: " + name); 24 System.out.println("Age: " + age); 25 System.out.println("GPA: " + gpa); 26 System.out.println("Grade: " + grade); 27 System.out.println("Enrolled: " + isEnrolled); 28 System.out.println("ID: " + universityId); 29 } 30}

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 mostint for whole numbers, double for decimals, boolean for true/false, String for text. Master these four first.
  2. Primitives store values; reference types store addressesint age = 25 stores 25 directly. String name = "Arjun" stores a reference to the String object in memory.
  3. Suffixes matter for literalslong 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
  • booleantrue 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

TopicLink
Declaring and using variablesVariables →
Converting between data typesType Casting →
Arithmetic and comparison operatorsOperators →
Getting user input as different typesUser Input (Scanner) →
Strings in depth — methods and operationsString Basics →
Data Types | DevStackFlow