Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final variables

 
Yat Cheung
Greenhorn
Posts: 15
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 4181
21
IntelliJ IDE Java Python
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Siva Masilamani
Ranch Hand
Posts: 385
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic