Reference Types & Strings
Reference types, String, Arrays, Stack vs Heap, pass-by-value
- Differentiate primitive types from reference types
- Understand how references work in memory
- Master String handling and immutability
- Understand pass-by-value semantics in Java
Series:
Java Core Concepts | Chapter: Variables — Part 2 Audience: Beginner to Intermediate Java Developers Coverage: Reference Data Types, String Constant Pool, Wrapper Classes, Autoboxing/Unboxing, Constant Variables
Table of Contents
- What are Reference Data Types?
- Reference Type 1 — Class
- Reference Type 2 — String
- Reference Type 3 — Interface
- Reference Type 4 — Array
- Wrapper Classes
- Autoboxing and Unboxing
- Constant Variables
- Interview Question Bank
- Master Summary
Data Type Taxonomy Quick Recap
1. What are Reference Data Types?
Overview
A reference data type is any type whose variable does not store the actual value directly. Instead, the variable stores a reference (memory address) pointing to the location in heap memory where the actual data lives.
This is the fundamental distinction from primitive types, which store values directly.
Why the Name "Reference"?
When you create an object using the new keyword, Java:
- Allocates a block of memory in the heap
- Stores the object's data there
- Gives the variable a reference (pointer-like address) to that memory location
The variable itself doesn't hold the object — it points to where the object lives.
Heap Memory What it is
Java's memory is divided into regions. The two most important for now:
| Memory Region | What lives here |
|---|---|
| Stack | Primitive variables, method call frames, local variable references |
| Heap | All objects created with new, String literals (in String Constant Pool) |
Diagram Reference vs Value
The primitive int a holds the value 10 directly. The reference variable empObj holds only an address — the actual Employee object data is in the heap.
Pass By Value in Java The Critical Concept
This is a statement that surprises many developers — especially those from a C++ background. Here's what it actually means:
- When you pass a primitive to a method → a copy of the value is passed. Changes inside the method do not affect the original.
- When you pass an object to a method → a copy of the reference (address) is passed. Both the original and the method's copy point to the same heap object. So changes to the object's fields are reflected in the caller.
This is why reference types give you similar power to C++ pointers — without Java ever literally using pointer syntax.
2. Reference Type 1 Class
Overview
A class is the most fundamental reference data type in Java. When you instantiate a class using new, an object is created in heap memory, and the variable holds a reference to it.
Code Example Class Reference and Shared Memory
1class Employee {2 int employeeId;3
4 int getEmployeeId() {5 return employeeId;6 }7
8 void setEmployeeId(int id) {9 this.employeeId = id;10 }11}12
13public class Main {14 static void modify(Employee emp) {15 emp.employeeId = 20; // modifies the object in heap16 }17
18 public static void main(String[] args) {19 Employee empObj = new Employee();20 empObj.employeeId = 10;21
22 System.out.println("Before: " + empObj.employeeId); // 1023
24 modify(empObj); // passing the reference by value25
26 System.out.println("After: " + empObj.employeeId); // 2027 }28}Before: 10 After: 20
Step-by-Step Execution
| Step | What Happens |
|---|---|
Employee empObj = new Employee() | JVM allocates heap memory for an Employee object. empObj stores the address (e.g., AIJ1246987) |
empObj.employeeId = 10 | Via the reference, employeeId at that heap address is set to 10 |
modify(empObj) is called | A copy of the reference (AIJ1246987) is passed into emp parameter |
emp.employeeId = 20 | emp points to the SAME heap object → sets employeeId to 20 |
Back in main, print empObj.employeeId | empObj still points to same heap address → sees 20 |
Multiple References to the Same Object
1Employee empObj = new Employee();2empObj.employeeId = 10;3
4Employee obj2 = empObj; // obj2 now points to the SAME heap object5
6obj2.employeeId = 30;7
8System.out.println(empObj.employeeId); // 30 — same object!Both empObj and obj2 are different variables holding the same reference. Changing the object via either variable affects both.
Primitive Pass-by-Value Contrast
1static void modifyPrimitive(int x) {2 x = 20; // only changes local copy3}4
5public static void main(String[] args) {6 int a = 10;7 modifyPrimitive(a);8 System.out.println(a); // 10 — unchanged9}With primitives, a lives on the stack. A copy of 10 is sent to modifyPrimitive. Changing x inside the method has zero effect on a.
Primitive vs Reference Key Difference Table
| Aspect | Primitive | Reference (Object) |
|---|---|---|
| Stored in | Stack | Heap (reference on Stack) |
| Variable holds | Actual value | Memory address |
| Pass to method | Copy of value | Copy of reference |
| Method changes reflected? | ❌ No | ✅ Yes (if mutating fields) |
| Default value | 0, false, '\0' | null |
3. Reference Type 2 String
Overview
String in Java is special. It is predefined by Java (like int or boolean), yet it is treated as a reference data type, not a primitive. Understanding why requires understanding the String Constant Pool and immutability.
The String Constant Pool
Inside the heap, Java maintains a special region called the String Constant Pool (also called the String Pool or String Intern Pool).
When you create a string using a string literal (text in double quotes), Java:
- Checks whether that exact string already exists in the pool
- If it does → reuses it (both variables point to the same pool entry)
- If it doesn't → creates a new entry in the pool
String Literals vs `new String()`
There are two ways to create a String in Java, with very different behavior:
1String s1 = "hello"; // String literal → goes to String Constant Pool2String s2 = "hello"; // Same literal → points to SAME pool entry as s13String s3 = new String("hello"); // new keyword → creates a NEW object in heap (outside pool)`==` vs `.equals()` for Strings Critical Concept
| Operator / Method | What it checks |
|---|---|
== | Are both references pointing to the exact same memory location? |
.equals() | Do both strings contain the same characters (same value)? |
1String s1 = "hello";2String s2 = "hello";3String s3 = new String("hello");4
5System.out.println(s1 == s2); // true — both point to same pool entry6System.out.println(s1 == s3); // false — s3 is a separate heap object7System.out.println(s1.equals(s2)); // true — same content8System.out.println(s1.equals(s3)); // true — same contenttrue false true true
== to compare String values in Java. It compares references (memory addresses), not content. Always use .equals() for value comparison.String Immutability
Strings are immutable in Java — once a String object is created, its value cannot be changed.
What appears to be "changing" a String actually creates a new String object and updates the reference:
1String s1 = "hello"; // pool: ["hello"], s1 → "hello"2s1 = "hello world"; // pool: ["hello", "hello world"], s1 → "hello world"3 // "hello" is still in the pool — it was NOT modifieds1 could mutate "hello" to "world", then s2 (which also points to "hello") would unexpectedly see "world". Immutability prevents this and also makes strings safe to use as HashMap keys, in multi-threaded programs, etc.Why is String a Reference Type?
Even though Java defines String for you (unlike Employee which you write yourself), it is still a reference type because:
- A
Stringvariable holds a reference to a string object (either in the pool or on the heap) - It is not stored directly on the stack like a primitive
- It can be
null(a primitive cannot be null) - It behaves like an object: has methods like
.length(),.equals(),.substring(), etc.
4. Reference Type 3 Interface
Overview
An interface is also a reference data type in Java. It works very similarly to a class from a reference perspective — variables of an interface type hold references to objects of classes that implement that interface.
Code Example
1interface Person {2 String profession();3}4
5class Teacher implements Person {6 @Override7 public String profession() {8 return "Teaching";9 }10}11
12class Engineer implements Person {13 @Override14 public String profession() {15 return "Software Engineer";16 }17}18
19public class Main {20 public static void main(String[] args) {21 // Valid: interface reference holds child object22 Person p1 = new Engineer(); // ✅23 Person p2 = new Teacher(); // ✅24
25 // Also valid: concrete type reference26 Engineer e = new Engineer(); // ✅27 Teacher t = new Teacher(); // ✅28
29 // INVALID: cannot instantiate an interface directly30 // Person p3 = new Person(); // ❌ Compile error31
32 System.out.println(p1.profession()); // Software Engineer33 System.out.println(p2.profession()); // Teaching34 }35}Software Engineer Teaching
Key Rules for Interface References
| Rule | Valid? | Reason |
|---|---|---|
Person p = new Engineer() | ✅ | Parent interface ref can hold child object |
Person p = new Teacher() | ✅ | Same as above |
Engineer e = new Engineer() | ✅ | Concrete type ref holding its own object |
Person p = new Person() | ❌ | Cannot instantiate an interface — no implementation exists |
Memory Diagram Interface Reference
p1 is declared as type Person, but it actually points to an Engineer object in the heap. This is polymorphism at work — the same interface reference can point to different implementing classes.
5. Reference Type 4 Array
Overview
An array in Java is a reference data type that stores a fixed-size, ordered sequence of elements of the same data type in contiguous memory locations in the heap.
Creating a 1D Array
There are two main ways to create a 1D array:
Method 1 Declare Size, Then Assign Values
1int[] arr = new int[5]; // allocate 5 integer slots in heap2
3arr[0] = 10;4arr[3] = 40;5// Default value for int is 0, so unset indices are 06// Result: [10, 0, 0, 40, 0]Method 2 Declare and Initialize in One Line
1int[] arr = {30, 20, 10, 40, 50};2// Java automatically sets size to 5 and fills values3// Result: [30, 20, 10, 40, 50]Both syntaxes for declaring the array variable are valid:
1int[] arr = new int[5]; // bracket after type — preferred2int arr[] = new int[5]; // bracket after name — also valid (C-style)Memory Representation 1D Array
Array elements are stored in contiguous memory. arr is a reference variable on the stack pointing to the first element in the heap.
Creating a 2D Array
A 2D array is essentially an array of arrays. Think of it as a table with rows and columns.
Method 1 Declare Size, Then Assign
1int[][] arr = new int[5][4]; // 5 rows, 4 columns2// Default values: all zeros3
4arr[2][2] = 20; // row 2, column 2 → set to 205arr[1][3] = 30; // row 1, column 3 → set to 30Method 2 Declare and Initialize
1int[][] arr = {2 {1, 5, 7},3 {4, 2, 3}4};5// 2 rows, 3 columns6// arr[1][2] → row 1, col 2 → value = 32D Array Visual Representation
For new int[5][4] (5 rows, 4 columns), default state:
1 Col 0 Col 1 Col 2 Col 32Row 0 [ 0 0 0 0 ]3Row 1 [ 0 0 0 30 ] ← arr[1][3] = 304Row 2 [ 0 0 20 0 ] ← arr[2][2] = 205Row 3 [ 0 0 0 0 ]6Row 4 [ 0 0 0 0 ]Why is Array a Reference Type?
- Created with
new→ lives in heap memory - The variable holds a reference to the heap memory block
- Passing an array to a method passes the reference → modifications inside the method affect the original array
1static void modify(int[] a) {2 a[0] = 999; // modifies heap memory3}4
5public static void main(String[] args) {6 int[] nums = {1, 2, 3};7 modify(nums);8 System.out.println(nums[0]); // 999 — changed!9}6. Wrapper Classes
Overview
Java provides a wrapper class for each of the 8 primitive types. A wrapper class is a class that "wraps" a primitive value inside an object, giving it reference-type capabilities.
Primitive to Wrapper Mapping
| Primitive | Wrapper Class |
|---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
int → Integer and char → Character.Why Do Wrapper Classes Exist?
Reason 1 Reference Capability (Modification Reflection)
When you pass a primitive to a method and modify it there, the original is unchanged. This is because primitives are stored on the stack and passed by value (a copy).
1// With primitive — change NOT reflected2static void modify(int x) {3 x = 20;4}5
6public static void main(String[] args) {7 int a = 10;8 modify(a);9 System.out.println(a); // 10 — unchanged10}With a wrapper class (which is an object), you get reference behaviour:
1// With wrapper — object in heap, reference passed2static void modify(int[] holder) {3 holder[0] = 20; // modifying heap object4}5
6public static void main(String[] args) {7 int[] a = {10};8 modify(a);9 System.out.println(a[0]); // 20 — changed10}Integer itself is immutable in Java (similar to String), so typically you use mutable containers or AtomicInteger for this use case. But conceptually, wrapper classes give you the object/reference nature you need.Reason 2 Java Collections Only Work With Objects
Java's Collections Framework (ArrayList, HashMap, HashSet, etc.) can only store objects — not primitives.
1// ❌ NOT VALID — ArrayList cannot hold primitives2// ArrayList<int> list = new ArrayList<int>();3
4// ✅ VALID — ArrayList can hold wrapper objects5ArrayList<Integer> list = new ArrayList<Integer>();6list.add(10); // 10 is auto-converted to Integer (autoboxing)7list.add(20);Without wrapper classes, you could not use Java's powerful collections with numeric or boolean data.
Wrapper Class Diagram
Wrapper classes also provide utility methods that primitives don't have — like Integer.parseInt(), Integer.MAX_VALUE, Integer.toBinaryString(), etc.
7. Autoboxing and Unboxing
Overview
Java performs automatic conversions between primitives and their wrapper types. These conversions are so common that Java handles them automatically (since Java 5).
Definitions
| Term | Direction | What happens |
|---|---|---|
| Autoboxing | Primitive → Wrapper | Java automatically wraps a primitive into its wrapper object |
| Unboxing | Wrapper → Primitive | Java automatically extracts the primitive value from a wrapper object |
Code Examples
1// AUTOBOXING — primitive int to Integer object2int a = 10;3Integer a1 = a; // autoboxing: int → Integer4// equivalent to: Integer a1 = Integer.valueOf(a);5
6// UNBOXING — Integer object to primitive int7Integer x = 20;8int x1 = x; // unboxing: Integer → int9// equivalent to: int x1 = x.intValue();Autoboxing in Collections
The most common place you'll see autoboxing in practice:
1ArrayList<Integer> list = new ArrayList<>();2
3list.add(5); // autoboxing: int 5 → Integer.valueOf(5)4list.add(10); // autoboxing: int 10 → Integer.valueOf(10)5
6int first = list.get(0); // unboxing: Integer → int7System.out.println(first); // 5Flowchart Autoboxing and Unboxing
Common Autoboxing Pitfall `==` with Integer Cache
Integer objects for values between -128 and 127. This means == may return true for small values but false for large ones — a subtle trap.1Integer a = 100;2Integer b = 100;3System.out.println(a == b); // true — both from cache, same object4
5Integer c = 200;6Integer d = 200;7System.out.println(c == d); // false — outside cache range, different objects8
9System.out.println(c.equals(d)); // true — always use .equals() for value comparison.equals() to compare wrapper objects by value, just like with Strings.8. Constant Variables
Overview
A constant variable is a variable whose value is set once and can never be changed. In Java, constants are created using a combination of static and final keywords.
Recap `static` Variables
A static variable belongs to the class, not to any individual object. All objects share a single copy.
1class Employee {2 static int employeeId = 10;3}4
5Employee obj1 = new Employee();6Employee obj2 = new Employee();7
8obj1.employeeId = 20; // changes shared value to 209System.out.println(obj2.employeeId); // 20 — same variable!But static alone doesn't prevent modification — both obj1 and obj2 can change it.
Making it a Constant `static final`
Adding final means the value is assigned once and locked. Any attempt to reassign it causes a compile error.
1class Employee {2 public static final int EMPLOYEE_ID = 10;3}4
5// Anywhere in code:6// Employee.EMPLOYEE_ID = 20; // ❌ Compile error: cannot assign to final variable7System.out.println(Employee.EMPLOYEE_ID); // ✅ Reading is fineNaming Convention for Constants
By Java convention, constant variable names are written in ALL_CAPS_WITH_UNDERSCORES (SCREAMING_SNAKE_CASE):
1public static final int MAX_RETRY_COUNT = 3;2public static final double PI = 3.14159265;3public static final String APP_NAME = "MyApp";`static` vs `final` vs `static final`
| Modifier | One copy shared? | Can be changed? | Constant? |
|---|---|---|---|
static | ✅ Yes | ✅ Yes | ❌ No |
final | ❌ No (per object) | ❌ No | Per-object constant |
static final | ✅ Yes | ❌ No | ✅ True constant |
Code Example Full Constant Demo
1class AppConfig {2 public static final int MAX_CONNECTIONS = 100;3 public static final String DB_NAME = "production_db";4}5
6public class Main {7 public static void main(String[] args) {8 System.out.println(AppConfig.MAX_CONNECTIONS); // 1009 System.out.println(AppConfig.DB_NAME); // production_db10
11 // AppConfig.MAX_CONNECTIONS = 200; // ❌ Compile error12 }13}100 production_db
Constant Variables Summary
9. Interview Question Bank
Reference Data Types
| Question | Key Answer |
|---|---|
| What is a reference data type? | Variable holds a memory address (reference) pointing to heap, not the value itself |
| What are the four main reference data types in Java? | Class, String, Interface, Array |
| Is Java pass-by-value or pass-by-reference? | Always pass-by-value — but for objects, the value being passed is the reference |
| How do reference types give us pointer-like behavior? | Multiple variables can reference the same heap object; mutations are shared |
| What is the default value of a reference type? | null |
String Specific
| Question | Key Answer |
|---|---|
| What is the String Constant Pool? | A special area in heap where string literals are stored and reused |
| Why are Strings immutable in Java? | To safely allow pool reuse — if literals could change, shared references would be corrupted |
What is the difference between == and .equals() for Strings? | == checks same memory reference; .equals() checks same content |
What happens when you use new String("hello")? | Creates a new heap object outside the pool — even if the pool has "hello" |
| Why is String a reference type even though Java defines it? | It holds a reference to heap memory (pool or regular heap); it has methods; it can be null |
Wrapper Classes
| Question | Key Answer |
|---|---|
| What is a wrapper class? | A class that wraps a primitive to give it object/reference capabilities |
| Name all 8 primitive-wrapper pairs | int/Integer, double/Double, char/Character, boolean/Boolean, byte/Byte, short/Short, long/Long, float/Float |
| Why do we need wrapper classes? | (1) Reference/mutation capability; (2) Java Collections only accept objects |
| What is autoboxing? | Automatic conversion from primitive to wrapper (e.g., int → Integer) |
| What is unboxing? | Automatic conversion from wrapper to primitive (e.g., Integer → int) |
| Integer cache trap | Integer caches -128 to 127; == may give unexpected results outside that range |
Constant Variables
| Question | Key Answer |
|---|---|
| How do you declare a constant in Java? | public static final TYPE NAME = value; |
What does static do? | One shared copy across all instances |
What does final do? | Prevents reassignment after initial value is set |
| What is the naming convention for constants? | ALL_CAPS_WITH_UNDERSCORES |
10. Master Summary
Complete Mind Map
Quick Revision Bullets
- ✅ Reference data type = variable holds a memory address, not the actual value
- ✅ Object lives in heap; reference lives on stack
- ✅ Java is always pass-by-value — for objects, the value passed is the reference
- ✅ Multiple variables can reference the same heap object — mutations are shared
- ✅ String Constant Pool — string literals are stored and reused in a pool inside heap
- ✅
String s = "hello"→ pool entry;String s = new String("hello")→ separate heap object - ✅
==for Strings = same memory location;.equals()for Strings = same content - ✅ Strings are immutable — "changing" a string creates a new object; old one stays in pool
- ✅ Interface reference can hold any object of a class that implements it; cannot use
new Interface() - ✅ Array = fixed-size, same-type, contiguous heap memory; variable is a reference to it
- ✅ Wrapper classes — one per primitive;
int→Integer,char→Character, etc. - ✅ Two reasons for wrapper classes: (1) reference/mutation capability, (2) Collections need objects
- ✅ Autoboxing = primitive → wrapper (automatic); Unboxing = wrapper → primitive (automatic)
- ✅ Integer cache (-128 to 127):
==may returntruefor cached values; always use.equals() - ✅ Constant variable =
public static final TYPE NAME = value;in ALL_CAPS - ✅
staticalone = shared, changeable.static final= shared, immutable = true constant
End of Chapter — Java Variables Part 2: Reference Data Types, Wrapper Classes & Constants
Mastery check
How well can you recall this?
Finished this lesson?