This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 3013
    
  35

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


Founder of ExamLab and Systemup
See how I can help you to become an awesome programmer
Greg Brannon
Bartender

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


Learning Java using Eclipse on OpenSUSE 11.2
Linux user#: 501795
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: declaring constant variable in java
 
Similar Threads
final keyword in method
doubt in final variable
Switch- Case doubt in case expressions.
Class Loading
final static int i =0 Whizlabs says i is variable and i feel it is a constant