• Post Reply Bookmark Topic Watch Topic
  • New Topic

static variables  RSS feed

 
Ranch Hand
Posts: 99
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
does static variable follows the pass by value? I'm confused, since they are one per class their value can change if one object changes it.
 
Marshal
Posts: 56608
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Everything is pass‑by‑value in Java®.
As you say, a change from one object is seen by all instances, but that may simply represent a reassignment.
 
Ranch Hand
Posts: 136
1
Netscape Opera Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aki Mohan wrote:does static variable follows the pass by value? I'm confused, since they are one per class their value can change if one object changes it.



Yep, any object can change a static variable and that change will be seen by all other classes in the program. It is Java's equivalent to global variables in other languages. So they should only be used for data that you want to apply to the entire program. Although Java references will behave like global data as well if the object they refer to is mutable (changeable) and 2 or more classes share that reference value.
 
Campbell Ritchie
Marshal
Posts: 56608
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can persuade the compiler to allow global variables like that, but don't; it is bad design.
 
Red Smith
Ranch Hand
Posts: 136
1
Netscape Opera Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:You can persuade the compiler to allow global variables like that, but don't; it is bad design.


What are you referring to with regard to "persuade the compiler " and "like that" ?
 
Aki Mohan
Ranch Hand
Posts: 99
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys It made things clearer.
 
Campbell Ritchie
Marshal
Posts: 56608
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler will happily accept global variables because they do not violate the rules of the grammar … but they do violate the principals of good programming.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!