After running the code below, I get this output: Eva 1200
Can someone explain to me why the value of a variable of type Person changes, but the value of a variable of type Integer does not? I already read this:
but I don’t understand why it works differently with Person and Integer types.
public class Test { public static void main(String[] args) { Object person = new Person("Adam"); Object integer = new Integer("1200"); changePerson(person); changeInteger(integer); System.out.println(person); System.out.println(integer); } private static void changeInteger(Object integer) { integer = 1000; } private static void changePerson(Object person) { ((Person)person).name="Eve"; } }
In Java, primitive types (such as integer) are always processed exclusively by value, and objects (for example, your Person) and arrays are always processed exclusively by reference .
, , , , , .
/ googlin ', .
Integer ( ). Person . .
Integer
Person
changeInteger(), integer = 1000, .
changeInteger()
person = new Person(); person.name="Eve";
in changePerson()
changePerson()
, .
PS: , .
, ( , ). OP . , , . , . , (.. , ) , . Java, , . , . , , , , . , integer = 1000, Integer - .
, Integer (, .setValue()), , Integer.
? .
private static void changeInteger(Object integer) { integer = 1000; }
integer , object, . Person.
integer
object
:
. Java . get . name Person. Person Person, name . , .
name
changeInteger() (1000) integer. integer main() (1200). , print() main() (1200)
main()
changePerson() person . , .
person
Aslo, , Integer ( ) . , ref var, JDK .
, !
In changePerson (), you yourself modify this object using its public name property. In changeInteger () you change the local Integer object,
Place the file System.out.println (integer); inside the function changeInteger (), and you will see that Integer is changing, but only in the function area.
private static void changeInteger(Object integer) { integer = 1000; System.out.println(integer); }
Source: https://habr.com/ru/post/1730622/More articles:https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1730617/what-happens-to-a-native-dll-when-placed-in-the-bin-folder-of-an-aspnet-application&usg=ALkJrhgTm7wr6CiBpepJwWBMgg-D8TCZEwHelp using Linq to query XML - c #Настройка Mongo DB и хостинг - mongodbSearch tool for composing binary images - embeddedCore Data and Runtime Key Value Coding - objective-cКак спроектировать координаты Lat/Lon на панорамном изображении? - latitude-longitudejava version on Linux - javahttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1730625/is-it-possible-to-use-powershell-to-make-changes-to-application-request-routing-arr-in-iis7&usg=ALkJrhhe1WKksaaruXKiGhPEZjJ8WR0lqwPerforming multiple database operations in a single REST call - restHow to include all formatting header files? - javaAll Articles