Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming practice for defining string constants in Java

My perception for defining string constants in Java is that one should define a string constant, when the same string is used at multiple places. This help in reducing typo errors, reduce the effort for future changes to the string etc.

But how about string that are used at a single place. Should we declare string constant even in that case.

For eg. Logging Some counter (random example).

CounterLogger.addCounter("Method.Requested" , 1)
  • Is there an advantage of declaring constant rather than using raw string?
  • Does the compiler does any optimization?
like image 673
Keen Sage Avatar asked Dec 25 '13 07:12

Keen Sage


1 Answers

Declaring constants can improve your code because they can be more descriptive. In your example

CounterLogger.addCounter("Method.Requested" , 1)

The method parameter "Method.Requested" is quite self describing but the 1 is not making this a constant would make this example more readable.

CounterLogger.addCounter("Method.Requested" , INITIAL_VALUE)
like image 111
Alex Edwards Avatar answered Sep 28 '22 01:09

Alex Edwards