• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

final variables

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic