Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is String.length() invoked for a final String?

Tags:

java

string

final

A quickie just to get peace of mind:
Considering the following

final String str = "This is the end";

Is str.length() evaluated at runtime or is it hardcoded as 15 in the bytecode?

like image 939
MonoThreaded Avatar asked Aug 13 '12 08:08

MonoThreaded


3 Answers

str.length() is calculated in String constructor and saved in private final int count;, str.length() just returns the count variable. I just checked the Source here http://www.docjar.com/html/api/java/lang/String.java.html

like image 113
Nandkumar Tekale Avatar answered Nov 10 '22 09:11

Nandkumar Tekale


str.length() is evaluated at runtime. final means that value of the reference cannot be changed. It has nothing to do with the string itself.

However, if you look into the source code of String you will see that length() returns the value of a field, so no computation takes place, the value os simply read...

like image 27
Mathias Schwarz Avatar answered Nov 10 '22 07:11

Mathias Schwarz


In the bytecode the method will be evaluated.

However, the method call will likely be inlined during jit compilation

The code for the String.length() method is as follows:

public int length() {
    return count;
}

I don't think the fact that the reference to the string is declared final has any bearing on the inlining in this case.

like image 26
munyengm Avatar answered Nov 10 '22 08:11

munyengm