+ 1

Output && Explanation

what will be the output of the code segments when you try to compile and execute it? Briefly explain the reason for your answer. public class Test { public static void main(String[] args) { Person p1 = new Person("Sunil"); Person p2 = new Person(); p2.name = "Nimal"; System.out.println("P1 Name: " + p1.name); System.out.println("P2 Name: " + p2.name); } } class Person { static String name; Person(String name) { this.name = name; } Person() { } }

15th Feb 2020, 1:11 PM
Kirushanthi Letchumanan
Kirushanthi Letchumanan - avatar
2 Réponses
+ 1
You should learn about the static keyword first to understand the behavior of the code you shared. Static data members are class members and do not belong to a specific object. Static data members have only a single copy of them so the memory allocation is only once and all the objects of the class share it. In simple words, the static data members will only have the last value assigned to them for all objects. Edit: In your case you have assigned 'Nimal' to the name which is the final assignment, so it will be reflected to the previous object as well. https://code.sololearn.com/c18AJgjgqd8z/?ref=app
15th Feb 2020, 1:31 PM
Avinesh
Avinesh - avatar
+ 1
Avinesh, create objects in reverse order, run it and then delete 'this.' Person p2 = new Person(); p2.name = "Nimal"; Person p1 = new Person("Sunil");
16th Feb 2020, 2:06 AM
zemiak