This week's book giveaway is in the Beginning Java forum.
We're giving away four copies of Get Programming with Java (MEAP only) and have Peggy Fisher on-line!
See this thread for details.
Win a copy of Get Programming with Java (MEAP only) this week in the Beginning Java 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
Bartenders:
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

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: 1067
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 ()
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).]
 
Hey, check out my mega multi devastator cannon. It's wicked. It makes this tiny ad look weak:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!