- 2

What is the meaning of the output of the following code...

public class MyClass { public static void main(String[ ] args) { Person j; j = new Person("John"); j.setAge(20); celebrateBirthday(j); System.out.println(j); } 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; } }

22nd Aug 2018, 9:00 AM
mn121
mn121 - avatar
10 Antworten
+ 3
thanks
22nd Aug 2018, 9:37 AM
mn121
mn121 - avatar
+ 2
In the line System.out.println(j); You are printing the actual person object rather than one of it's attributes, ie name or age.
22nd Aug 2018, 9:22 AM
Duncan
Duncan - avatar
+ 2
I want to know what is the meaning of the program output which is coming : Person@2a139a55
22nd Aug 2018, 9:25 AM
mn121
mn121 - avatar
+ 2
Patrick Maok thanks
22nd Aug 2018, 9:34 AM
mn121
mn121 - avatar
+ 1
Person j; -- Declaring a new person object under the variable 'j' j = new Person("John"); -- Calls the Person constructor with a string input 'Person (String n)' and sets the person object's class variable 'name' as "John" (the input) j.setAge(20); -- Calling the void (no values return) procedure 'setAge (int a)' which takes an integer value and sets the object's class variable 'age' as 20 (the input) celebrateBirthday(j); -- Calls a void procedure 'celebrateBirthday(Person p)' which takes a person object and calls the class' void procedure 'setAge' to increment the object's current age 'p.getAge()' by 1 '+ 1'. Essentially John will celebrate his birthday and as a result, his age 20 will go up by 1 to become 21. System.out.println(j) -- This will output the Person object as a unique identifier, so Person@2a139a55 is the unique identifier in memory which is the internal representation of the object.
22nd Aug 2018, 9:32 AM
Patrick Maok
Patrick Maok - avatar
+ 1
Basically if you print out the object, it will always be: ClassName@HashCode mn121 No problem!
22nd Aug 2018, 9:36 AM
Patrick Maok
Patrick Maok - avatar
0
mn121 I know what you meant as I ran your program. My answer wasn't as detailed but it gave the same reason.
22nd Aug 2018, 11:53 AM
Duncan
Duncan - avatar
0
struct human { int age; char name[40]; }; human h1 = {19, "John"}; h1 age += 2; Please tell the answer
3rd Oct 2022, 3:23 PM
MUGILA R
MUGILA R - avatar
0
Fill in the blanks to increase the age of the h1 variable by 2. struct human { int age; char name[40]; }; struct human h1 = {19, "John"}; h1 age += 2; Answer plz
8th Oct 2022, 5:21 PM
KIKKARA SONIYA
- 3
10
9th Jan 2019, 5:33 AM
K. Asma nikhath
K. Asma nikhath - avatar