How are Java objects assigned values and referenced?
In Java, object assignment and references can be achieved in several ways.
- Assigning directly: You can assign one object directly to another object, so that both objects will reference the same memory address, pointing to the same object.
Object obj1 = new Object();
Object obj2 = obj1; // 将obj1对象赋值给obj2对象,obj1和obj2引用同一个对象
- By assigning values through constructors: one can create a new object by calling an object’s constructor and passing parameters, and then assign it to another object.
Object obj1 = new Object();
Object obj2 = new Object(obj1); // 通过构造函数将obj1对象的值赋给obj2对象
- Assigning a returned value through a method: by calling a method and assigning its returned value to another object, both objects will reference the same returned value object.
Object getObject() {
return new Object();
}
Object obj1 = getObject();
Object obj2 = obj1; // 将getObject方法返回的对象赋值给obj2对象,obj1和obj2引用同一个对象
- By assigning an array: You can create an array object and assign it to another array object, so that both array objects will reference the same array.
int[] arr1 = {1, 2, 3};
int[] arr2 = arr1; // 将arr1数组赋值给arr2数组,arr1和arr2引用同一个数组
It is important to note that in Java, primitive data types (such as int, double, etc.) are passed by value, not by reference, so when assigning them, the value is directly copied to another variable. Only object types are passed by reference.