What's will be printed when this program is executed?
public class Person {
{
personCount = 10;
}
static {
personCount = 20;
}
private static int personCount = 1000;
{
personCount = 30;
}
static {
personCount = 40;
}
public static void main(String[] args) {
System.out.println(Person.personCount);
Person p = new Person();
System.out.println(Person.personCount);
Person.personCount = 100;
p = new Person();
System.out.println(Person.personCount);
}
}
Tore Garberg
Level 0
Can anyone tell me why the program are 40,30,30
Under discussion
Comments (1)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
12 November 2019, 16:30
Its the order of how the code is run. Static runs before any objects are created, and the last static block in the person call is
So this is the value of personCount before any objects are created. After an object is created the non static blocks are run, in which case the last one is:
So when a new object is created the personCount will equal 30.
In the main method, taking into account above information, the first println is before any objects have been created while the next 2 println's are directly after new objects have been created. 0