Reputation: 47
Can somebody please explain me this behavior of java.
class StringLength {
public static void main(String args[]) {
String str = "Hi! This is me.";
int length = str.length();
System.out.println("String length is :" + length);
System.out.println("String length for second case is :".length());
}
}
The output of code is :
String length is :15
34
First println
statement gives output as 15. That's ok, but what about second one?? How second one is even syntactically correct, because concatenation operator for java is "+" not ".". can anyone please explain me this output.
Upvotes: 0
Views: 265
Reputation: 471
You are calling the length()
method on the string "String length for second case is :"
The characters in that string add up to 34.
It would be the same as saying
String s = "String length for second case is :";
System.out.println( s.length() );
Upvotes: 3
Reputation: 1128
The second one calls method of the string literal "String length for second case is :".
It's equivalent to:
String str2 = "String length for second case is :";
System.out.println( str2.length() );
Upvotes: 2
Reputation: 53859
System.out.println("String length for second case is :".length());
prints the length of the string "String length for second case is :"
which is 34.
Upvotes: 2
Reputation: 178333
When running this code, I get
String length is :15
34
Sure, the length of "Hi! This is me."
is 15. But "String length for second case is :"
is a String
literal, which can be treated as a String
object, and a method can be called on it too. There is no concatenation; just a method call on a string literal. Its length is 34.
Upvotes: 3
Reputation: 2353
The second one is synonymous to:
String str2 = "String length for the second case is:";
System.out.println(str2.length());
Upvotes: 3