First, you need to understand what static
keyword does, here's a good question to start with: What does the 'static' keyword do in a class?
Now that you know that static
makes a variable a member of the Class and not of the instance, you will know that if an instance of class modify a static field of that class, another instance will see the modified value, we can go through your questions:
- Why
Test.x
isn't 11
and give output like: 11 22 33 44
Test.x
refers to this variable: static int x = 11;
, which you're modifying its value to 22
here:
this.x = 22;
In this case, you have a local variable, which you're receiving as a parameter int x
. When using this
keyword, you're accessing the instance of this class and as it's a static variable, there's no instance but you access it.
So, when you call this.x = 22
is like saying Test.x = 22
.
- Why
t.y
and y
isn't a 44
and 44
and gives output like: 11 22 44 44
It's due to y
not being static, so it has it's own value. When you call new Test();
, the variable t
creates a new instance having a variable called y
initialized to 33
, because of this:
private int y = 33;
So, when you call t.y
it prints the above result because it's a different instance.
When you print y
, then you're calling the variable y
which is in use in the program right now (and it's a different instance from the one above), and you changed its value to 44
before printing it.
That's why the first this.y
prints 33
and y
prints 44
- Why
t.method(5)
is not executed in this code?
It's indeed being executed, or you wouldn't see any output at all, but you don't get a 5
because you're never using the local variable in the parameters int x
. You could try writing
System.out.println(x);
So you get that value.