• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

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

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for clearing this up. Very enlightening.
 
reply
    Bookmark Topic Watch Topic
  • New Topic