• Post Reply Bookmark Topic Watch Topic
  • New Topic

wat's the diff between final and static variables  RSS feed

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys,
tell me wat's the diff between static and final variables;
regds
chaitu
 
Ranch Hand
Posts: 1054
2
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
final means that the value assigned to the variable will not change.

So the value for TUESDAY will always be 5. If you try and change it you will get a compiler error.
static means that you only get one copy of a variable (or class). static variables are also called class variables.

I couldn't come up with a good example of this one, as you can tell. The class B would "share" the variable Monday, but have it's own copy of Tuesday.
 
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically, if you have multiple objects of a class, and the class has a static variable (or class variable, as Christopher pointed out), each object does not get its own copy of the variable, they all use the same one. Here's a simple example:

The output here is:
1
2
Why not two 1's?? Because variable is static, there is only one instance of it, so all objects of MyClass access the same variable.
If we had not declared variable as static, then object a would have its own copy of variable, and object b would have its own copy.
Clear as mud?
Jason
[This message has been edited by jason adam (edited August 20, 2001).]
 
Paper jam tastes about as you would expect. Try some on this tiny ad:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!