String length() method in java

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

String length() method in java

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

Also read – learn strings in java

String length() method is specified by CharSequence interface.

Syntax

public int length()

Returns

returns length of characters.

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

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("string length java = " + a);
      sc.close();
   }
}



Output:

Please enter a string to find length: virat
string length java = 5

array length java

To find array length java, array 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