Equivalence of static const char * in java function

I regularly use this idiom in C ++:

/*return type*/ foo(/*parameters*/){ static const char* bar = "Bar"; /*some code here*/ } 

Inside, this is added to the string literal table. Is this Java code similar:

 /*return type*/ foo(/*parameters*/){ final String bar = "Bar"; /*some code here*/ } 

or do I involuntarily imagine inefficiency here?

+7
java c ++
source share
4 answers

Strings are immutable in Java. This means you donโ€™t have to give hints to let the JVM know that it will not change or optimize it.

String literals are interned to avoid redundancy, which means that they are already โ€œadded to the string literal tableโ€. Using final is not required here.

+5
source share

I think your solution is correct and they are as close to the equivalent as Java can express.

As mentioned in other answers, strings are immutable, and final does not add performance gains, however I find that final is semantically useful here. Very similar to "const" in C ++; "final" ensures that the value cannot be changed, and trying to do this will result in a compiler error - it seems to me that this is the desired behavior in your case.

Also (as in the case of C ++ const) this can lead to some possible optimization, which otherwise would not have been considered.

+1
source share

You can specify the string to be added to the literal pool (called interning in Java) by calling String.intern() as follows:

 final String bar = myString.intern(); 

This is basically the same concept as a literal pool, using the same object for a given string. Note that string literals are interned automatically. It also allows you to compare interned strings by reference, so it can be more efficient. However, you should always compare strings returned with intern() . Thus,

 a.equals(b); 

can be replaced by

 a.intern() == b.intern(); 

Note that you really do not want this to be exactly as shown. Ideally, you can keep interned strings around and reuse them. However, there are some pitfalls for interned strings. They are not going to garbage, and the method itself is a little expensive.

0
source share

The final keyword in the Java method does not do what you think.

In this particular case, final makes the variable non-modulated. It. The content itself is added to the global String constant table, but a pointer to it (pardon of terminology) is technically set every time.

The final keyword is mostly useful from within the method to make this variable available to any anonymous classes that you create after it. This is a clear stingy semi-professional support for what they like to consider "closure." And this is also the only way to access an external variable inside an internal anonymous class.

 final String bar = "Bar"; final Set<String> allTheBars = new HashSet<>() {{ add(bar); }}; 
0
source share

All Articles