Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it worth keeping constants for primitives in Java?

Tags:

java

primitive

My question is related to Is making an empty string constant worth it?.

I know constants should have meaningful names, but is there any benefit in extracting primitive values like ints in Java in a Constants file like:

public final static int ZERO = 0;

to use as general-purpose constants and keep reusing it like Constants.ZERO in your code-base or better use the literal value of 0?

What about general-purpose booleans? i.e.

public static final boolean TRUE = true;
public static final boolean FALSE = false;
like image 653
arun Avatar asked Dec 16 '22 04:12

arun


2 Answers

For the constants you are defining, there's no reason for them because there is no extra meaning. The literals 0, true, and false already have their meaning.

Constants would be worth creating if there is some extra meaning to attach to those values, such as:

public static final int SUCCESS = 0;
public static final boolean DEBUG = true;

There is meaning behind these values, and it's possible that they may change:

public static final int SUCCESS = 1;
public static final boolean DEBUG = false;

which would make it easier to change the values than changing lots of literals in the program.

If the values have meaning beyond their literal values, and if they could change, then creating constants is worth the effort.

like image 190
rgettman Avatar answered Dec 31 '22 23:12

rgettman


If it makes your program easier to understand or maintain, yes. Otherwise, no.

The HotSpot VM probably complies your code to the same machine code either way.

And by the way, Boolean.TRUE and Boolean.FALSE already exist.

like image 39
pscuderi Avatar answered Dec 31 '22 23:12

pscuderi