• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static variable gets unexpected value in method. Qestion of initialization?  RSS feed

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone please explain what is happening in this piece of code? The first three should print "22" and the last two should print "44" but it doesn't. Is this about initialization? I've added a couple of comments.
Thank you.

 
Greenhorn
Posts: 13
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In line 17 you have used Q.x where Q is class that you have created and x is static variable which can be accessed by using classname.variablename,so it wil print 11 because the value assigned to the instance variable x is 11 in the class Q,and in line 20, it will print 33 because it is called by using the object of the class which you have created because whenever you create a object, memory is allocated for that particular object,so if if you to print 44 instead of 33 you have to change the value of the instance variable y in that object,and then you can use q.y to print 44.
 
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I ran theprogram and got whatI expected....

Output: 11
Output: 22
Output: 11
Output: 33
Output: 44

You are confusing x variable input to call() with class variable x.
Comment the line....x = 22;
...and run it, you would get the idea.

Manish
 
Sven Sylta
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for clearing this up. Very enlightening.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!