File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes final variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "final variables" Watch "final variables" New topic
Author

final variables

Yat Cheung
Greenhorn

Joined: Jul 18, 2001
Posts: 15
Hello,
Is there any point in declaring variables like this ...
private static final int BLAH_1 = 0;
private static final int BLAH_2 = 0;


or since I've made it private I may as well declare it ...
private final int blah1 = 0;

I often declare variables with different names but with same values to make my code more readable so I can say stuff like if (field == BLAH_1)

Or should I declare these as
public static final int BLAH_1 = 0
though I am unlikely to use them outside the class they are declared.

Just some thoughts I had which I'd like to clarify to myself really so any comments appreciated
Thanks
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

I generally will go the approach of making them private static final variables if they are to be constants which are the same for all instances of the class. I also will use different variable with the same value sometimes when they would have different meaning in different situations. so I guess I usually work more like your first example:
private static final int BLAH_1 = 0;
private static final int BLAH_2 = 0;

(nowadays I do try to avoid these things altogether when I can replace them with enums though)

-edit-Sorry, had the vars as public, but should have been private


Steve
Siva Masilamani
Ranch Hand

Joined: Sep 19, 2008
Posts: 385
Hi

Since you are declaring the variable as constant anyway you cannot change that value.But if you just want to use that variable you need to create an object for each and every time.If instead the variable is declared as static final then there is no need to create objects which may save some memory.


SCJP 6,SCWCD 5,SCBCD 5

Failure is not an option.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: final variables