+ 5
Why x value 1 is used even though we have static x value as 2 in this code?
Java variables usage https://code.sololearn.com/cE0c5dhfBSPD/?ref=app
4 Respostas
+ 7
static members are bound to the class, not to the instance. So to refer the static <x> we need to specify the class e.g.
System.out.print( Program.x + y );
Here we use 'Program' because <x> is defined as class Program's member.
+ 5
Always first compiler search variables existence in stack memory of local variables.. If it not found then it search in global area.
There x in main method shadowing the global static variable x.
Static variables are stored in class area in java. Where as local variables sre stored in stack memory.
So remove x in main, then you get 4 as output. If you want to use global static variable x in main, even if you have local variable x exist, then use Program.x as @ipang suggested..
Hope it helps...
+ 3
Jayakrishna🇮🇳 thank you
+ 2
Ipang thank you