Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

declaring constant variable in java  RSS feed

 
goel Ashish
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why we always use static final variable in java as constant variable? When only declaring the variable as final can do the job.
 
Devaka Cooray
Marshal
Posts: 5511
687
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What did you mean by "constant variable"?
You can declare a 'variable' with final keyword if you find it's appropriate for your design. The thing is you will have to instantiate the class before you can access a non-static variable.

Here you can access 'X' as in SomeClass.X
But if you have omitted the use of 'static', X will be bounded to the objects created of SomeClass, and thus you will need to have an object of SomeClass before accessing X
 
Greg Brannon
Bartender
Posts: 563
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may find the discussion on this page helpful.

There is a reason for each of the key words or modifiers that you may not realize in the relatively simple, single class?, programs you've written so far, but it's important to understand their purpose and proper application in more complex code.
 
Rob Spoor
Sheriff
Posts: 21044
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Devaka Cooray wrote:But if you have omitted the use of 'static', X will be bounded to the objects created of SomeClass, and thus you will need to have an object of SomeClass before accessing X

Not only that, but each instance will have its own, equal copy of the variable. If you have 10 instances, you have 10 ints in memory, all with the same constant value.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!