Why x value 1 is used even though we have static x value as 2 in this code? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 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

13th Mar 2022, 7:36 AM
alagammai uma
alagammai uma - avatar
4 ответов
+ 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.
13th Mar 2022, 7:59 AM
Ipang
+ 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...
13th Mar 2022, 9:03 AM
Jayakrishna 🇮🇳
+ 3
13th Mar 2022, 9:07 AM
alagammai uma
alagammai uma - avatar
+ 2
Ipang thank you
13th Mar 2022, 8:50 AM
alagammai uma
alagammai uma - avatar