logo

longueur vs longueur() en Java

tableau.longueur : la longueur est une variable finale applicable pour tableaux . A l'aide de la variable length, nous pouvons obtenir la taille du tableau.

Longueur de chaine() : La méthode length() est une méthode finale applicable aux objets chaîne. La méthode length() renvoie le nombre de caractères présents dans la chaîne.



longueur vs longueur()

strint à int

1. La variable length est applicable à un tableau mais pas aux objets chaîne alors que la méthode length() est applicable aux objets chaîne mais pas aux tableaux.

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. Pour accéder directement à un champ membre d'un tableau, nous pouvons utiliser .longueur; alors que .longueur() appelle une méthode pour accéder à un membre de champ.

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

>

>

Sortir

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

Questions pratiques basées sur le concept de longueur par rapport à la longueur()

Jetons un coup d'œil au résultat des programmes suivants :

Java contre C++
  • Quel sera le résultat du programme suivant ?

JAVA




>

attraper et essayer Java
>

Sortir

3>

Explication: Ici, str est un tableau de type string et c'est pourquoi str.length est utilisé pour trouver sa longueur.

  • Quel sera le résultat du programme suivant ?

JAVA




pas égal à mysql

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

>

>

Sortir:

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

Explication: Ici, str est un tableau de type chaîne et c'est pourquoi str.length() NE PEUT PAS être utilisé pour trouver sa longueur.

  • Quel sera le résultat du programme suivant ?

JAVA




alphabet numéroté

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

>

>

Sortir

5>

Explication: Ici str[0] pointant vers String, c'est-à-dire GEEKS et est donc accessible en utilisant .length()