Data Types
Primitive and reference types in Java
Understanding Data Types
Data types specify the type of data a variable can hold. Java is a strongly typed language, meaning every variable must be declared with a type before use.
Primitive Data Types
Primitive types are the basic building blocks. They are not objects and store single values in memory.
| Type | Size | Range | Example |
|---|---|---|---|
| byte | 1 byte | -128 to 127 | byte age = 25; |
| short | 2 bytes | -32,768 to 32,767 | short year = 2025; |
| int | 4 bytes | -2³¹ to 2³¹-1 | int count = 1000; |
| long | 8 bytes | -2⁶³ to 2⁶³-1 | long id = 123456789L; |
| float | 4 bytes | ±3.4×10³⁸ | float price = 19.99f; |
| double | 8 bytes | ±1.7×10³⁰⁸ | double pi = 3.14159; |
| char | 2 bytes | 0 to 65,535 (Unicode) | char initial = 'J'; |
| boolean | 1 bit | true or false | boolean isActive = true; |
Reference Data Types
Reference types don't store the actual data but store a reference (address) to the data in memory. They include classes, interfaces, arrays, and strings.
🔑 Key Difference: Primitive types are passed by value, while reference types are passed by reference.
Code Examples
Declaration and initialization of all primitive data types
1// Primitive data types
2byte age = 25;
3short temperature = -10;
4int population = 7800000000;
5long distance = 384400000L;
6float price = 29.99f;
7double pi = 3.14159265;
8char grade = 'A';
9boolean isJavaFun = true;Examples of reference data types - strings, arrays, collections, and objects
1// Reference data types
2String name = "John Doe"; // String object
3int[] scores = {95, 87, 92}; // Array of integers
4ArrayList<String> cities = new ArrayList<>(); // Collection
5Student student = new Student(); // Custom class objectUnderstanding the difference between primitive and reference type assignments
1// Demonstrating primitive vs reference
2public class DataTypeDemo {
3 public static void main(String[] args) {
4 // Primitive - copy by value
5 int a = 10;
6 int b = a; // b gets the value 10
7 b = 20; // changing b doesn't affect a
8 System.out.println(a); // Output: 10
9
10 // Reference - copy by reference
11 int[] arr1 = {1, 2, 3};
12 int[] arr2 = arr1; // arr2 points to same array
13 arr2[0] = 99; // changing arr2 affects arr1
14 System.out.println(arr1[0]); // Output: 99
15 }
16}Use Cases
- Choosing appropriate data types for variables to save memory
- Avoiding integer overflow by using long instead of int
- Working with floating-point calculations (double for precision)
- Processing character data and Unicode
- Creating boolean conditions for control flow
Common Mistakes to Avoid
- Using int for very large numbers instead of long
- Assuming float has same precision as double
- Forgetting the L suffix for long literals
- Forgetting the f suffix for float literals
- Confusing == operator with .equals() method for reference types
- Not understanding that variables store values, not the objects themselves for primitives