length vs length() a Java

array.length: la longitud és una variable final aplicable matrius . Amb l'ajuda de la variable de longitud, podem obtenir la mida de la matriu.

string.length(): El mètode length() és un mètode final que és aplicable per a objectes de cadena. El mètode length() retorna el nombre de caràcters presents a la cadena.

longitud vs longitud ()

1. La variable de longitud s'aplica a una matriu, però no a objectes de cadena, mentre que el mètode length() és aplicable a objectes de cadena però no a les matrius.

2. Exemples:

// 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. Per accedir directament a un membre de camp d'una matriu que podem utilitzar .llargada; mentre que .llargada() invoca un mètode per accedir a un membre del camp.

Exemple:

JAVA




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

Sortida

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

Preguntes pràctiques basades en el concepte de longitud vs longitud()

Fem una ullada a la sortida dels programes següents:

  • Quina serà la sortida del següent programa?

JAVA




Sortida

3 

Explicació: Aquí, str és una matriu de tipus string i per això s'utilitza str.length per trobar la seva longitud.

  • Quina serà la sortida del següent programa?

JAVA




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

Sortida:

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

Explicació: Aquí, str és una matriu de tipus string i per això NO es pot utilitzar str.length() per trobar la seva longitud.

  • Quina serà la sortida del següent programa?

JAVA




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

Sortida

5 

Explicació: Aquí str[0] apunta a String, és a dir, GEEKS i, per tant, es pot accedir mitjançant .length()