- 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; } }
10 Antworten
+ 3
thanks
+ 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.
+ 2
I want to know what is the meaning of the program output which is coming :
Person@2a139a55
+ 2
Patrick Maok thanks
+ 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.
+ 1
Basically if you print out the object, it will always be:
ClassName@HashCode
mn121 No problem!
0
mn121 I know what you meant as I ran your program. My answer wasn't as detailed but it gave the same reason.
0
struct human {
int age;
char name[40];
};
human h1 = {19, "John"};
h1
age += 2;
Please tell the answer
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
- 3
10