String length() method in java

Let’s learn string length() method in java.

String length() method in java

String length() method returns length of this string. The length of the sequence of characters represented by this object.

Also read – java string methods

String length() method is specified by CharSequence interface. The length is equal to the number of Unicode code units in the string.

Syntax

public int length()

Here’s String length() method example,

public class StringLengthJava
{
   public static void main(String[] args)
   {
      String str1 = "flowerbrackets";
      String str2 = "helloworld";
      System.out.println("string length : " + str1.length());
      System.out.println("string length : " + str2.length());
   }
}


Output:

string length() method in java

length without using length() method

Here’s the java program.

// how to find length of string in java without using length() method
import java.util.Scanner;
public class StringLengthDemo 
{
   public static void main(String[] args) 
   {
      int a = 0;
      String strGiven;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a string to find length: ");
      strGiven = sc.nextLine();
      char[] chArray = strGiven.toCharArray();
      for(char ch : chArray)
      {
         a++; 
      }
      System.out.println("length without using length() method = " + a);
      sc.close();
   }
}


Output:

Please enter a string to find length: virat
length without using length() method = 5


array length java

To find array length, length attribute is used. Here’s an example.

public class ArrayLengthDemo 
{
   public static void main(String[] args) 
   {
      String[] strArray = { "Hello", "World", "Java" };
      int arr = strArray.length;
      System.out.println("Array length java: " + arr);
   }
}


Output:

Array length java: 3