I make regular use of this idiom in C++:
/*return type*/ foo(/*parameters*/){
static const char* bar = "Bar";
/*some code here*/
}
Internally this gets added to a table of string literals. Does this Java code do a similar thing:
/*return type*/ foo(/*parameters*/){
final String bar = "Bar";
/*some code here*/
}
or am I unwittingly introducing inefficiencies here?
Constants are basically variables whose value can't change. In C/C++, the keyword const is used to declare these constant variables. In Java, you use the keyword final .
const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.
Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value. Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants.
const char* is a pointer to a constant char, meaning the char in question can't be modified. char* const is a constant pointer to a char, meaning the char can be modified, but the pointer can not (e.g. you can't make it point somewhere else).
Strings are immutable in Java. This means you don't have to give hints to have the JVM know it won't change and optimize it.
String literals are interned to avoid redundancies, which means they already are "added to a table of string literals". Using final
here isn't necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With