There are different aspects that come into play.
Default values
Variables in Java have default values, even if you don't specify them. For int this is 0, so the initial values of your App class are:
int ns = 0;
static int s = 0;
So actually ns is not "set to 0 for ref3", but instead just keeps its initial value, whereas ref1 and ref2 explicitly alter the value.
Variable scopes
Let's look at the constructor of App:
App (int ns) {
if (s < ns) {
s = ns;
this.ns = ns;
}
}
There are two different variables with the name ns:
this.ns, which references the field on instance level (which at this point still has its initial value 0)
ns (without this), which is only visible inside the constructor and has the value provided via the constructor argument (50, 125 or 100).
Static variables
s is a static variable and associated with the App class itself, not with a specific instance. So whenever one instance changes its value (e.g. because 50 < 125 in the constructor), all other instances (in fact: the entire program) will see the updated value.
The logic inside the constructor basically sets s to the maximum of all provided ns values so far, which is in this case 125. Try to move your doPrint() methods a few lines above and see how those values change.
Appendix: "Debugging"
For a complete overview of how the values evolve you can also add some "debug" statements:
System.out.println("App.s=" + App.s);
App ref1 = new App(50);
System.out.println("ref1.ns=" + ref1.ns + ", ref1.s=" + ref1.s + ", App.s=" + App.s);
App ref2 = new App(125);
System.out.println("ref2.ns=" + ref2.ns + ", ref2.s=" + ref2.s + ", App.s=" + App.s);
App ref3 = new App(100);
System.out.println("ref3.ns=" + ref3.ns + ", ref3.s=" + ref3.s + ", App.s=" + App.s);
This will output:
App.s=0
ref1.ns=50, ref1.s=50, App.s=50
ref2.ns=125, ref2.s=125, App.s=125
ref3.ns=0, ref3.s=125, App.s=125
You can see that ref.s is always equals App.s and App.s exists even before you create your first instance.
ifis false and the assignments are not executed (andnsstays at the initial default).