- 1

Explain this program?

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); } } public class Person { private String name; private int age; Person (String n) { this.name = n; } public int getAge() { return age; } public void setAge(int a) { this.age = a; } }

7th Nov 2019, 6:12 AM
Minhaj Haider
Minhaj Haider - avatar
2 Answers
+ 3
It's simple. See the reference variable j is of type person. And j.setAge(20) sets the age 20 for the object j. Now this object j is passed to the celebrateBirthday(). So the age of the person passed is 20 now. Inside that method the value is incremented by 1. So now the age becomes 21. And finally that is printed using j.getAge(). Kindly read about static keyword.
7th Nov 2019, 6:25 AM
Avinesh
Avinesh - avatar
+ 2
It's Java isn't it? Then why have you tagged C#?
7th Nov 2019, 6:17 AM
Avinesh
Avinesh - avatar