Java for Beginners, Lesson 8: Primitive Data Types in Java

Java for Beginners · Module 2: Building Blocks


🎯 Why Do Types Exist?

Think of containers: a tiny spice jar, a water bottle and a big drum. You choose the container to match what you store. A variable is the same. The data type decides how much memory the variable gets and what kind of value it can hold. A type that is too small loses data. A type that is too big wastes memory.

📌 Java has 8 primitive data types: byte, short, int, long, float, double, char and boolean. They are built into the language and store plain values, not objects.

1️⃣ The Eight Primitive Types

GroupTypesStores
Whole numbersbyte, short, int, longintegers, no decimal part
Decimal numbersfloat, doublenumbers with a decimal point
Single charactercharone letter, digit or symbol
True / falsebooleanonly true or false
8 primitive types in all. Everything else (like String) is a non-primitive type.

Figure 1: Java has 8 primitive data types in 4 groups.

TypeSizeRangeDefault (field)Example
byte1 byte-128 to 1270byte age = 19;
short2 bytes-32,768 to 32,7670short year = 2026;
int4 bytesabout ±2.1 billion0int roll = 21045;
long8 bytesabout ±9.2 × 10¹⁸0Llong pop = 8_100_000_000L;
float4 bytesabout ±3.4 × 10³⁸ (7 digits)0.0ffloat cgpa = 8.75f;
double8 bytesabout ±1.8 × 10³⁰⁸ (15 digits)0.0double bal = 125000.5;
char2 bytes0 to 65,535 (Unicode)code 0char sec = 'B';
booleanJVM decidestrue or falsefalseboolean ok = true;

Figure 2: The 8 primitive types with size, range and an example.

byte
1 byte
short
2 bytes
int
4 bytes
long
8 bytes
float
4 bytes
double
8 bytes
char
2 bytes

Figure 3: Relative sizes of the types (wider box = more memory, bigger range).

Program 1: Ask Java for the limits

public class TypeRanges {
    public static void main(String[] args) {
        System.out.println("byte  : " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE + "  (" + Byte.BYTES + " byte)");
        System.out.println("short : " + Short.MIN_VALUE + " to " + Short.MAX_VALUE + "  (" + Short.BYTES + " bytes)");
        System.out.println("int   : " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE + "  (" + Integer.BYTES + " bytes)");
        System.out.println("long  : " + Long.MIN_VALUE + " to " + Long.MAX_VALUE + "  (" + Long.BYTES + " bytes)");
        System.out.println("float : up to " + Float.MAX_VALUE + "  (" + Float.BYTES + " bytes)");
        System.out.println("double: up to " + Double.MAX_VALUE + "  (" + Double.BYTES + " bytes)");
        System.out.println("char  : " + (int) Character.MIN_VALUE + " to " + (int) Character.MAX_VALUE + "  (" + Character.BYTES + " bytes)");
    }
}
🖥️ Output:
byte : -128 to 127 (1 byte)
short : -32768 to 32767 (2 bytes)
int : -2147483648 to 2147483647 (4 bytes)
long : -9223372036854775808 to 9223372036854775807 (8 bytes)
float : up to 3.4028235E38 (4 bytes)
double: up to 1.7976931348623157E308 (8 bytes)
char : 0 to 65535 (2 bytes)
  • Each wrapper class (Byte, Integer and so on) knows the limits of its type. You never have to memorise them.
  • E38 means × 10³⁸, a very large number. (int) in front of Character.MIN_VALUE shows the character’s numeric code instead of the symbol.
  • The size in bytes explains the range: a byte has 8 bits, so it holds 2⁸ = 256 values, from -128 to 127.

2️⃣ Integers and Overflow

Whole-number types have a fixed range. Going past the largest value does not cause an error in Java. The number silently wraps around to the smallest value. This is called overflow.

127 in a byte
+1 ➜
-128
wraps around, no error!
Like a car odometer rolling over, a number that goes past the maximum wraps to the minimum.

Figure 4: Overflow: going past the largest value wraps to the smallest.

public class OverflowDemo {
    public static void main(String[] args) {
        int big = Integer.MAX_VALUE;
        System.out.println("MAX int      : " + big);
        System.out.println("MAX int + 1  : " + (big + 1));

        byte b = 127;
        b++;
        System.out.println("byte 127 + 1 : " + b);

        long safe = (long) big + 1;
        System.out.println("Using long   : " + safe);
    }
}
🖥️ Output:
MAX int : 2147483647
MAX int + 1 : -2147483648
byte 127 + 1 : -128
Using long : 2147483648
  • Integer.MAX_VALUE + 1 gives -2147483648, which is wrong for real life but is how int arithmetic works.
  • b++ adds 1 to a byte holding 127, so it wraps to -128.
  • (long) big + 1 first converts big to a long, so the addition has room. This is called casting, covered in Lesson 9.
  • When numbers may be large (money, populations, factorials), use long.

3️⃣ Decimals: float and double

Decimal types store approximate values. double is the default for decimal literals and has about 15 digits of precision. float has about 7 digits.

public class PrecisionDemo {
    public static void main(String[] args) {
        System.out.println("0.1 + 0.2 = " + (0.1 + 0.2));
        System.out.println("float  1/3 = " + (1.0f / 3));
        System.out.println("double 1/3 = " + (1.0 / 3));
        System.out.println("0.5 + 0.25 = " + (0.5 + 0.25));
        System.out.printf("Rounded    : %.2f%n", 0.1 + 0.2);
    }
}
🖥️ Output:
0.1 + 0.2 = 0.30000000000000004
float 1/3 = 0.33333334
double 1/3 = 0.3333333333333333
0.5 + 0.25 = 0.75
Rounded : 0.30
  • 0.1 + 0.2 is not exactly 0.3. Computers store decimals in binary, and 0.1 cannot be written exactly in binary, just as 1/3 cannot be written exactly in decimal.
  • double keeps more digits than float, as the two 1/3 lines show.
  • 0.5 and 0.25 are sums of powers of two, so they are stored exactly and give a clean 0.75.
  • Use printf("%.2f") to show a sensible number of decimals. For exact money calculations, professionals use a class called BigDecimal instead.

4️⃣ char: One Character, Also a Number

A char holds one character in single quotes. Behind the scenes it is a 16-bit number (a Unicode code), so you can do arithmetic on it.

public class CharDemo {
    public static void main(String[] args) {
        char c = 'A';
        System.out.println("c               : " + c);
        System.out.println("c + 1 (a number): " + (c + 1));
        System.out.println("(char)(c + 1)   : " + (char) (c + 1));
        char fromUnicode = '\u0042';
        System.out.println("'\\u0042'        : " + fromUnicode);
        System.out.println("Is '7' a digit? : " + Character.isDigit('7'));
        System.out.println("Is 'x' a letter?: " + Character.isLetter('x'));
        System.out.println("'a' in upper    : " + Character.toUpperCase('a'));
    }
}
🖥️ Output:
c : A
c + 1 (a number): 66
(char)(c + 1) : B
‘\u0042’ : B
Is ‘7’ a digit? : true
Is ‘x’ a letter?: true
‘a’ in upper : A
  • ‘A’ has the code 65, so c + 1 is the number 66.
  • (char)(c + 1) converts 66 back to a character, ‘B’.
  • '\u0042' writes a character by its Unicode code in hexadecimal; 0042 is ‘B’.
  • Character.isDigit, isLetter and toUpperCase are ready-made helpers.

5️⃣ boolean

A boolean holds only true or false. It is used for conditions in if statements and loops. Unlike C, Java does not accept 1 or 0 as a boolean.

6️⃣ Choosing the Right Type

QuestionChoose
Whole number, normal size (marks, count, age)int
Very large whole number (population, file size, money in paise)long
Decimal number (price, height, average)double
Single character (grade, section)char
Yes / no flagboolean
Saving memory in huge arrays onlybyte, short, float

Figure 5: Which type should I pick? When unsure: int for whole numbers, double for decimals.

public class ChoosingTypes {
    public static void main(String[] args) {
        byte ageOfStudent = 19;
        short year = 2026;
        int rollNumber = 21045;
        long worldPopulation = 8_100_000_000L;
        float cgpa = 8.75f;
        double accountBalance = 125000.50;
        char section = 'B';
        boolean hostelResident = true;

        System.out.println("Age        : " + ageOfStudent);
        System.out.println("Year       : " + year);
        System.out.println("Roll no    : " + rollNumber);
        System.out.println("Population : " + worldPopulation);
        System.out.println("CGPA       : " + cgpa);
        System.out.println("Balance    : " + accountBalance);
        System.out.println("Section    : " + section);
        System.out.println("Hostel     : " + hostelResident);
    }
}
🖥️ Output:
Age : 19
Year : 2026
Roll no : 21045
Population : 8100000000
CGPA : 8.75
Balance : 125000.5
Section : B
Hostel : true
  • This program uses all eight types, each matched to its data.
  • In everyday code most programmers use int, long, double, char and boolean. byte, short and float are used only when memory really matters.

7️⃣ Errors Beginners Meet

A number too large for int

public class TooBig {
    public static void main(String[] args) {
        int population = 3000000000;
        System.out.println(population);
    }
}
🖥️ Compiler message:
TooBig.java:3: error: integer number too large
int population = 3000000000;
^
1 error
  • 3,000,000,000 is more than the int maximum of 2,147,483,647. Use long and add L.

Losing data when storing into a smaller type

public class Lossy {
    public static void main(String[] args) {
        byte b = 200;
        System.out.println(b);
    }
}
🖥️ Compiler message:
Lossy.java:3: error: incompatible types: possible lossy conversion from int to byte
byte b = 200;
^
1 error
  • 200 does not fit in a byte (-128 to 127), so Java refuses. Use short or int.

Using a number as a boolean

public class NotBool {
    public static void main(String[] args) {
        boolean ready = 1;
        System.out.println(ready);
    }
}
🖥️ Compiler message:
NotBool.java:3: error: incompatible types: int cannot be converted to boolean
boolean ready = 1;
^
1 error
  • Java does not treat 1 as true. Write true.

⚠️ Common Mistakes

MistakeProblemFix
Expecting an error on overflowJava wraps around silentlyChoose a bigger type like long
Comparing doubles with ==0.1 + 0.2 is not exactly 0.3Compare with a small tolerance
float f = 3.14;3.14 is a doubleWrite 3.14f
char c = "A";Double quotes make a StringUse single quotes
Using boolean b = 1;Not allowed in JavaUse true or false
Using int for large money totals in paiseMay overflowUse long

❓ Frequently Asked Questions

Q1. Is String a primitive type?
No. String is a class (a non-primitive type). Lesson 23 covers it.

Q2. Why does int have 4 bytes in Java on every computer?
Java fixes the size of each type, so programs behave the same everywhere. In C the size of int can vary.

Q3. Which is better, float or double?
For most programs, double. It is more accurate and the default for decimals.

Q4. How many bytes does boolean use?
The language only says true or false. The JVM decides the internal size.

✅ Key Takeaways

  • 8 primitive types: byte, short, int, long (whole), float, double (decimal), char, boolean.
  • Sizes are fixed: 1, 2, 4, 8 bytes for the whole-number types.
  • Overflow wraps silently, so choose a type big enough for the data.
  • Decimals are approximate. Use double, and printf to format.
  • char is a 16-bit Unicode number written in single quotes.
  • Default choices: int for whole numbers, double for decimals.
🎓 Practice questions: (1) Which type would you use for the number of students in a class, the price of a pen, a student’s grade letter and “is the library open”? (2) What is the range of a byte, and why? (3) What does Integer.MAX_VALUE + 1 print, and why is it surprising? (4) Why is 0.1 + 0.2 not exactly 0.3? (5) Write a program that prints the next 5 letters after ‘M’ using char arithmetic.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision