關於JAVA中對字符串與數組求長度的問題


  我在學習中發現在求數組或者字符串的長度的時候,用到length的時候,有時候是length,有時候是length(),很是奇怪,於是上API查了一下,發現一些小細節。

  首先看看這段代碼

 1 public class TS{
 2     public static String arr[] = {"s","a","s",};
 3     public static String str = "sas";
 4     public static void main(String [] args){
 5         System.out.println(arr.length);
 6         //System.out.println(arr.length());
 7         //System.out.println(str.length);
 8         System.out.println(str.length());
 9     }
10 
11 } 

  這是非注釋的打印是正確的代碼,結果為;

  但當把代碼改為

public class TS{
    public static String arr[] = {"s","a","s",};
    public static String str = "sas";
    public static void main(String [] args){
        //System.out.println(arr.length);
        System.out.println(arr.length());
        System.out.println(str.length);
        //System.out.println(str.length());
    }

} 

  這時候就出了問題,報錯為.

  這就可以發現,數組對應是length,字符串對應是length()。

  那么這到底是怎么回事呢,查詢API可知,即length()是字符串的一個方法,而length則是數組的屬性。

  這個小細節平常需要格外注意,以減少debug的工作量。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM