From the Code for String class I can see that length()
returns value.length
(here).
Lets say I want to print the length of a string str
length()
number of times.
Q1) What would be the better way to do it from the following code snippets: (if you have a better method please suggest)
Code 1:
public static void main(String[] args) {
String str="Hello World";
for(int i=0;i<str.length();++i){
System.out.println(str.length());
}
}
Code 2 (I prefer this one cause of the readability it offers about the program...)
public static void main(String[] args) {
String str="Hello World";
final int len=str.length();
for(int i=0;i<len;++i){
System.out.println(len);
}
}
Code 3:
public static void main(String[] args) {
String str="Hello World";
int len=str.length();
for(int i=0;i<len;++i){
System.out.println(len);
}
}
Q2) Which is the most optimized way OR are they the same ?
Q3) Does the compiler inline the length in the bytecode generated for this program ?
Thanks!