1

This one is a bit of conceptual question. I know strings are constant; their values cannot be changed after they are created. Consider this declaration -

private final static String ABC = "abc"; 

vs

private final String ABC = "abc"; 

Why is the first one better in terms of performance?

Is there any reason why the second one would be needed if the value of ABC not being updated in the class anywhere as such directly?

Thanks in advance.

Tiny
  • 27,221
  • 105
  • 339
  • 599
ND27
  • 447
  • 1
  • 5
  • 16
  • 6
    Do you understand the difference between `static` and non-`static`? – Oliver Charlesworth Sep 26 '14 at 21:13
  • Strings are _immutable_, but not necessarily _constant_. – Reinstate Monica -- notmaynard Sep 26 '14 at 21:15
  • @oliver Charlesworth - yes, I understand the difference between static and non-static. The question was specific to STRINGS. Thanks to all who marked the question as duplicate BUT the link provided as a duplicate doesn't answer my question. – ND27 Sep 26 '14 at 21:48
  • @iamnotmaynard - Please refer to this link - "Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:" http://docs.oracle.com/javase/7/docs/api/java/lang/String.html It is important not to treat String in java like any other data type. That is something most developers dont pay heed to. I was trying to get my basics correct with the question. – ND27 Sep 26 '14 at 21:48

2 Answers2

2

The first one creates only one copy for all the instances of your class.But the second one creates ABC for each instances.

The first one can be called without the object itself.

Venkatesh
  • 1,537
  • 15
  • 28
1

The first one is ~better~ because you won't have an extra String reference in all your instances. Because they are both constant expressions, you'll get the same behavior in the class byte code (where their value is used).

There are also a few differences to consider if you use reflection anywhere.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724