2014-03-18 27 views
0

有人可以請我解釋一下java的這種行爲。String.length()函數

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

    } 
} 

的代碼的輸出是:

字符串長度:15

首先println語句提供輸出作爲15.沒關係,但對於第二個??第二個是甚至在語法上是否正確,因爲Java的連接運算符是「+」而不是「。」。任何人都可以請解釋我這個輸出。

+0

什麼是'.'呢? –

+0

什麼是'length()'? –

+2

這就是你應該問自己的問題。 –

回答

3

您正在呼籲串"String length for second case is :"length()方法在該字符串中的字符加起來34

這將是相同的話說

String s =「第二種情況下的字符串長度爲:」;

System.out.println(s.length());

3

第二個是同義:

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

當運行該代碼,我得到

String length is :15 
34 

當然,的"Hi! This is me."長度是15.但是"String length for second case is :"String的文本,這可以被視爲一個String對象和方法可以是也呼籲它。沒有連接;只是一個字符串文字的方法調用。它的長度爲34。

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

打印字符串"String length for second case is :"其是34.

2

第二個調用字符串文字的方法的長度「爲第二殼體字符串長度是:」。

它等同於:

String str2 = "String length for second case is :"; 
System.out.println(str2.length()); 
相關問題