Value Types
Value types are data types that store the actual data. Examples of value types include int
, float
, boolean
, double
, and char
. Below, you will find examples of some of these types.
public class Main {
public static void main(String[] args) {
int numericalValue = 5;
String textualValue = "Hello World";
boolean controlValue = true; // or false
char singleCharValue = 'A';
}
}
Now, let's consider the following code:
int value1 = 10;
int value2 = 20;
value1 = value2;
value2 = 30;
System.out.println(value1);
If your assumption is that the output of this code will be 30, that would be incorrect. The output will be 20. Let's see why.
When we examine the lines one by one, in the 3rd line, the value of value1 is assigned the value of value2, making the new value of value1 equal to 20. Then, value2 is assigned the value 30, but this does not affect value1. As a result, when we print value1, we get the output 20.
Reference Types
Reference types, unlike value types, store the address of the data rather than the data itself. Reference types include interface, class, string, array, and enum. Reference types are stored in the heap memory.
int[] numbers1 = new int[] {1, 2, 3};
int[] numbers2 = new int[] {10, 20, 30};
numbers1 = numbers2;
numbers2[0] = 100;
System.out.println(numbers1[0]);
In this case, the output will be 100. Let's understand why.
Here, the reference of numbers1 is stored as 101, and the reference of numbers2 is stored as 102. When we come to the 3rd line and set the reference of numbers1 equal to the reference of numbers2, we get a situation similar to the one above. Then, when we set the 0th element of numbers2 to 100, since the reference of numbers2 is 101, the 0th element of the values at reference 101 changes to 100. When we print numbers1[0], we get the value 100.
In this article, I explained value and reference types in the Java language. I hope this has been a helpful read for you. Have a great day!