简体   繁体   中英

String.length() function

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.

The second one is synonymous to:

String str2 = "String length for the second case is:";
System.out.println(str2.length());

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() );

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.

System.out.println("String length for second case is :".length());

打印字符串"String length for second case is :" 34。

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() );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM