Java における length と length() の比較

配列の長さ: length は、次の条件に適用される最終変数です。 配列 。 length 変数を使用すると、配列のサイズを取得できます。

string.length() : length() メソッドは、文字列オブジェクトに適用できる最後のメソッドです。 length() メソッドは、文字列内に存在する文字数を返します。

長さと長さ()

1. length 変数は配列には適用できますが、文字列オブジェクトには適用できません。一方、 length() メソッドは文字列オブジェクトには適用できますが、配列には適用できません。

2. 例:

// length can be used for int[], double[], String[] // to know the length of the arrays. // length() can be used for String, StringBuilder, etc // String class  related Objects to know the length of the String 

3. 配列のフィールド メンバーに直接アクセスするには、次を使用します。 。長さ; 一方 。長さ() フィールドメンバーにアクセスするメソッドを呼び出します。

例:

ジャワ




public> class> Test {> > public> static> void> main(String[] args)> > {> > // Here str[0] pointing to String i.e. GEEKS> > String[] str = {> 'GEEKS'> ,> 'FOR'> ,> 'GEEKS'> };> > System.out.println(str[> 0> ].length());> > }> }>

出力

The size of the array is 4 The size of the String is 13 

長さと length() の概念に基づいた練習問題

次のプログラムの出力を見てみましょう。

  • 次のプログラムの出力はどうなるでしょうか?

ジャワ




出力

3 

説明: ここで、str は文字列型の配列であるため、その長さを見つけるために str.length が使用されます。

  • 次のプログラムの出力はどうなるでしょうか?

ジャワ




public> class> Test {> > public> static> void> main(String[] args)> > {> > // Here str[0] pointing to a string i.e. GEEKS> > String[] str = {> 'GEEKS'> ,> 'FOR'> ,> 'GEEKS'> };> > System.out.println(str.length());> > }> }>

出力:

error: cannot find symbol symbol: method length() location: variable str of type String[] 

説明: ここで、str は string 型の配列であるため、その長さを見つけるために str.length() を使用することはできません。

  • 次のプログラムの出力はどうなるでしょうか?

ジャワ




public> class> Test {> > public> static> void> main(String[] args)> > {> > // Here str[0] pointing to String i.e. GEEKS> > String[] str = {> 'GEEKS'> ,> 'FOR'> ,> 'GEEKS'> };> > System.out.println(str[> 0> ].length());> > }> }>

出力

5 

説明: ここで str[0] は String、つまり GEEKS を指しているため、.length() を使用してアクセスできます。