Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalence of static const char* in a java function

Tags:

java

c++

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?

like image 842
Bathsheba Avatar asked Oct 23 '13 15:10

Bathsheba


People also ask

What is the equivalent of const in Java?

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 .

Can const char * Be Changed?

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.

What is static constant in Java?

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.

What is static const char?

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).


1 Answers

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.

like image 90
Denys Séguret Avatar answered Sep 29 '22 07:09

Denys Séguret