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.
1️⃣ The Eight Primitive Types
| Group | Types | Stores |
| Whole numbers | byte, short, int, long | integers, no decimal part |
| Decimal numbers | float, double | numbers with a decimal point |
| Single character | char | one letter, digit or symbol |
| True / false | boolean | only true or false |
Figure 1: Java has 8 primitive data types in 4 groups.
| Type | Size | Range | Default (field) | Example |
| byte | 1 byte | -128 to 127 | 0 | byte age = 19; |
| short | 2 bytes | -32,768 to 32,767 | 0 | short year = 2026; |
| int | 4 bytes | about ±2.1 billion | 0 | int roll = 21045; |
| long | 8 bytes | about ±9.2 × 10¹⁸ | 0L | long pop = 8_100_000_000L; |
| float | 4 bytes | about ±3.4 × 10³⁸ (7 digits) | 0.0f | float cgpa = 8.75f; |
| double | 8 bytes | about ±1.8 × 10³⁰⁸ (15 digits) | 0.0 | double bal = 125000.5; |
| char | 2 bytes | 0 to 65,535 (Unicode) | code 0 | char sec = 'B'; |
| boolean | JVM decides | true or false | false | boolean ok = true; |
Figure 2: The 8 primitive types with size, range and an example.
1 byte
2 bytes
4 bytes
8 bytes
4 bytes
8 bytes
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)");
}
}
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,Integerand so on) knows the limits of its type. You never have to memorise them. E38means × 10³⁸, a very large number.(int)in front ofCharacter.MIN_VALUEshows 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-128wraps around, no error!
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);
}
}
MAX int : 2147483647
MAX int + 1 : -2147483648
byte 127 + 1 : -128
Using long : 2147483648
Integer.MAX_VALUE + 1gives -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 + 1first convertsbigto along, 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);
}
}
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.2is 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.doublekeeps more digits thanfloat, 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 calledBigDecimalinstead.
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'));
}
}
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 + 1is 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,isLetterandtoUpperCaseare 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
| Question | Choose |
| 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 flag | boolean |
| Saving memory in huge arrays only | byte, 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);
}
}
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,charandboolean.byte,shortandfloatare 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);
}
}
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
longand addL.
Losing data when storing into a smaller type
public class Lossy {
public static void main(String[] args) {
byte b = 200;
System.out.println(b);
}
}
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
shortorint.
Using a number as a boolean
public class NotBool {
public static void main(String[] args) {
boolean ready = 1;
System.out.println(ready);
}
}
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
| Mistake | Problem | Fix |
|---|---|---|
| Expecting an error on overflow | Java wraps around silently | Choose a bigger type like long |
Comparing doubles with == | 0.1 + 0.2 is not exactly 0.3 | Compare with a small tolerance |
float f = 3.14; | 3.14 is a double | Write 3.14f |
char c = "A"; | Double quotes make a String | Use single quotes |
Using boolean b = 1; | Not allowed in Java | Use true or false |
Using int for large money totals in paise | May overflow | Use 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, andprintfto format. charis a 16-bit Unicode number written in single quotes.- Default choices:
intfor whole numbers,doublefor 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 doesInteger.MAX_VALUE + 1print, and why is it surprising? (4) Why is0.1 + 0.2not exactly 0.3? (5) Write a program that prints the next 5 letters after ‘M’ usingchararithmetic.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java