wood burning stoves*
The moose likes Beginning Java and the fly likes declaring constant variable in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "declaring constant variable in java" Watch "declaring constant variable in java" New topic
Author

declaring constant variable in java

goel Ashish
Greenhorn

Joined: May 14, 2011
Posts: 21
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
ExamLab Creator
Saloon Keeper

Joined: Jul 29, 2008
Posts: 3268
    
  52

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


Author of ExamLab ExamLab - a free SCJP / OCPJP exam simulator
What would SCJP exam questions look like? -- Home -- Twitter -- How to Ask a Question
Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 563
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.


Always learning Java, currently using Eclipse on Fedora.
Linux user#: 501795
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19790
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: declaring constant variable in java