Selgitage välja viite-tüüpide kontseptsiooni Java keeles ja kuidas need erinevad primitiivsetest tüüpidest.
sobes.tech AI
Vastus AI-lt
In Java, there are two main data types: primitive and reference types.
Primitive types (e.g., int, boolean, double) directly store values. They occupy a fixed amount of memory and are passed by value. For example, when assigning one variable to another, the value itself is copied.
Reference types are objects and arrays. A variable of a reference type stores not the object’s value itself, but a reference (address) to the memory area where the object is located. When one reference type variable is assigned to another, the reference is copied, not the object. This means both variables point to the same object.
Example:
int a = 5;
int b = a; // copies the value 5
b = 10; // a remains 5
String s1 = new String("hello");
String s2 = s1; // copies the reference to the object
s2 = "world"; // s1 remains "hello", because String is immutable
Thus, the main difference lies in how data is stored and transferred: primitives store values directly, while reference types store references to objects in memory.