lunghezza vs lunghezza() in Java

array.lunghezza: la lunghezza è una variabile finale applicabile per matrici . Con l'aiuto della variabile length possiamo ottenere la dimensione dell'array.

stringa.lunghezza() : Il metodo length() è un metodo finale applicabile agli oggetti stringa. Il metodo length() restituisce il numero di caratteri presenti nella stringa.

lunghezza vs lunghezza()

1. La variabile length è applicabile a un array ma non agli oggetti stringa mentre il metodo length() è applicabile agli oggetti stringa ma non agli array.

2. Esempi:

// 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 accedere direttamente a un campo membro di un array possiamo usare .lunghezza; mentre .lunghezza() richiama un metodo per accedere a un membro del campo.

Esempio:

GIAVA




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

Produzione

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

Domande pratiche basate sul concetto di lunghezza vs lunghezza()

Diamo un'occhiata all'output dei seguenti programmi:

  • Quale sarà l'output del seguente programma?

GIAVA




Produzione

3 

Spiegazione: Qui str è un array di tipo stringa ed è per questo che viene utilizzato str.length per trovarne la lunghezza.

  • Quale sarà l'output del seguente programma?

GIAVA




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

Produzione:

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

Spiegazione: Qui str è un array di tipo stringa ed è per questo che str.length() NON PUÒ essere utilizzato per trovarne la lunghezza.

  • Quale sarà l'output del seguente programma?

GIAVA




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

Produzione

5 

Spiegazione: Qui str[0] punta a String, ad esempio GEEKS e quindi è possibile accedervi utilizzando .length()