0

Can someone explain how this code works?

public class MyClass { public static void main(String[ ] args) { Person j; j = new Person("John"); j.setAge(20); celebrateBirthday(j); System.out.println(j.getAge()); } static void celebrateBirthday(Person p) { p.setAge(p.getAge() + 1); } } //Outputs "21"

7th Sep 2017, 1:02 PM
neil dcruze
neil dcruze - avatar
3 Respuestas
+ 2
@ Carl You could just assume the class exists. 😛 @Main question Objects are basically (Okay, yes @ran technically it's just the value of the reference 😛) passed by reference. Person is an Object. So, celibrateBirthDay(j); Is passing the Object j as arguments. static void celibrateBirthDay(Person p){} This means that p will NOT be a new Person. It will be the same Object as the one you passed through as arguments. Example with arrays/ int[] myArray = {1,2,3} doStuff(myArray); System.out.println(myArray[0]); static void doStuff(int[] a){ a[0] = 7; } Output: 7 This only works differently for primitive data-types, which are passed by value.
7th Sep 2017, 3:45 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
It's a big no no.Java is passed by value!never pass by reference.The object is copy by reference,not pass by reference! Remember this!
7th Sep 2017, 4:18 PM
Ran
Ran - avatar
0
Code won't work since there is no class called Person. Therefore you can't create an instance of Person.
7th Sep 2017, 1:06 PM
Carl Fies
Carl Fies - avatar