Win a copy of Microservices Testing (Live Project) this week in the Spring forum!
  • 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:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

class and instance variables

 
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
my program is given below:

the output is :
value of j is 0
value of cv.s is 0
value of cv.p is null
value of cvs.s is 0
value of cvs.p is null
value of cv.s is 1000
value of cv.p is firststring
i have initialized the values of s and p. i was under the impression that class variables belonged to the class and not to the instance and it did not matter if they were prefixed with the instance name their values would still remain the same. Am i missing something basic here???
[ Jess added UBB [CODE] tags to preserve whitespace. ]
[ October 01, 2002: Message edited by: Jessica Sant ]
 
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think you're getting a bit confused by local variables, static variables and non-static variables.
int j is a local variable -- it belongs only to the method it is defined in.
int s and String p are non-static variables -- it belongs to the instance of a class. You have created two instances: cv and cvs.
you don't have any static variables defined. Try modifying one of the non-static variables to use the 'static' modifier, and see what happens, I think you'll get more the behavior you expected. But realize, its VERY bad practice to access a static variable through an instance.
 
charu latha
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the information. I was under the impression that if i declared a class variable then it automatically became a static variable. I think that is not the case. I did my program again with static prefixed the class variables and it worked as i wanted it to.
 
reply
    Bookmark Topic Watch Topic
  • New Topic