Length of String in Java Examples

Length of String in Java with Examples. In the Java String class, the length() method is given to calculate the length of the string literal. In this post, we will find the length of String in Java by demonstrating many examples.

Method declaration,

public int length()

Return value of length() method,

It returns numbers of characters available in the String. It returns zero if the string has no characters.

Internal implementation of String length() method in Java,

public int length() {
   return value.length >> coder();
}

Java program to find the length of String in Java using length() method of String class

public class Test {
   public static void main(String[] args) {
      String s1 = "Java";
      System.out.println(s1.length());

      String s2 = "Learn Java";
      System.out.println(s2.length());

      String s3 = "Know Program";
      System.out.println(s3.length());

      String s4 = "Learn Java Tutorial - Know Program";
      System.out.println(s4.length());
   }
}

Output:-

4
10
12
34

The string literal “Java” contains 4 characters ‘J’, ‘a’, ‘v’, and ‘a’. Therefore s1.length() returns 4. Similarly, the string literal “Lean Java” contains 10 characters ‘l’, ‘e’, ‘a’, ‘r’, ‘n’, ‘ ‘ (space), ‘J’, ‘a’, ‘v’, and ‘a’. Hence s2.length() method returns 10. Other string literal lengths are calculated in a very similar way.

Now, let us use another Java program to demonstrate the length() method of the String class. Find the output of the below program?

public class Test {
   public static void main(String[] args) {
      String s1 = "";
      System.out.println(s1.length());

      String s2 = " ";
      System.out.println(s2.length());

      String s3 = "Know Program";
      System.out.println(s3.length());

      String s4 = new String();
      System.out.println(s4.length());

      String s5 = new String("");
      System.out.println(s5.length());

      String s6 = new String(" ");
      System.out.println(s6.length());

      String s7 = new String("Know Program");
      System.out.println(s7.length());
   }
}

The output of the above Java program:-

0
1
12
0
0
1
12

The string literal "" is empty containing only null characters ‘\0’, and its length is 0 therefore the s1.length() method returns 0. Every string literal ends with a null character ‘\0’ even if the string is empty and the length() method doesn’t count ‘\0’.

The string literal " " contains one blank space which is a valid character. Therefore s2.length() method returns 1.

We can also find the length of a string in Java without using the length() method. See more:- How to find the length of the string in Java without using the length() method

Based on the above program,

ValueisBlank()
""true
" "true
“Program”false
new String();true
new String("");true
new String(" ");true
new String(“Program”);false

Let us see another program to find length of string in Java by taking String input values from the end-user through Scanner class,

import java.util.Scanner;

public class Test {
   public static void main(String[] args) {
      
      Scanner scan = new Scanner(System.in);
      
      System.out.println("Enter three Strings in three lines,");
      String s1 = scan.nextLine(); // directly press enter key
      String s2 = scan.nextLine(); // enter blank spaces or tabs
      String s3 = scan.nextLine(); // enter normal string
      
      System.out.println(s1.length() + ", s1 = " + s1);
      System.out.println(s2.length() + ", s2 = " + s2);
      System.out.println(s3.length() + ", s3 = " + s3);
   }
}

Output:-

Enter three Strings in three lines,
->(Here directly enter key was pressed)
->(Here one space was entered)
Know Program
0, s1 =
1, s2 =
12, s3 = Know Program

MCQ to Find length of String in Java using length() Method

Based on the above-discussed points let us see some interesting MCQ on the length() method of the String class. Find the answers and for the programs find the correct outputs.

Q1) For a given valid string the return value of length() can’t be?

a) 0
b) 10
c) -10
d) None of these.

[bg_collapse view=”button-blue” color=”#fff” icon=”eye” expand_text=”Show Answer” collapse_text=”Show Less” ]
Answer:- c) -10; The length of a string can’t be negative therefore length() method will not return -10.
[/bg_collapse]


Q2) Find the output of the given program?

package com.kp.test;
public class Test {
   private static String s1;
   public static void main(String[] args) {
      System.out.println(s1.length());
   }
}

a) 0
b) Any value > 0
c) Compile time error
d) NullPointerException

[bg_collapse view=”button-blue” color=”#fff” icon=”eye” expand_text=”Show Answer” collapse_text=”Show Less” ]
Answer:- d) NullPointerException

If the string is not initialized then we can’t perform any operation on it because there is not any String object available here. Due to this reason, we will get an Exception in thread “main” java.lang.NullPointerException: Cannot invoke “String.length()” because “com.kp.test.Test.s1” is null at com.kp.test.Test.main(Test.java:6)
[/bg_collapse]


Q3) Find the output of the given program?

package com.kp.test;
public class Test {
   public static void main(String[] args) {
      String s2;
      System.out.println(s2.length());
   }
}

a) 0
b) Any value > 0
c) Compile time error
d) NullPointerException

[bg_collapse view=”button-blue” color=”#fff” icon=”eye” expand_text=”Show Answer” collapse_text=”Show Less” ]
Answer:- c) Compile time error

In this program, before running compile time itself gets an error because the local variable is not initialized. All the local variables must be initialized before using it. Hence we get a compile-time error: variable s2 might not have been initialized.
[/bg_collapse]


Q4) Find the output of the given program?

package com.kp.test;
public class Test {
   public static void main(String[] args) {
      String s3 = null;
      System.out.println(s3.length());
   }
}

a) 0
b) Any value > 0
c) Compile time error
d) NullPointerException

[bg_collapse view=”button-blue” color=”#fff” icon=”eye” expand_text=”Show Answer” collapse_text=”Show Less” ]
Answer:- d) NullPointerException

The string is not initialized, and we are trying to call the length() method with null reference. Hence we get:- Exception in thread “main” java.lang.NullPointerException: Cannot invoke “String.length()” because “s3” is null at com.kp.test.Test.main(Test.java:5)
[/bg_collapse]


Q5) Find the output of the given program?

package com.kp.test;
public class Test {
   public static void main(String[] args) {
      String s4 = "null";
      System.out.println(s4.length());
   }
}

a) 0
b) 4
c) Compile time error
d) NullPointerException

[bg_collapse view=”button-blue” color=”#fff” icon=”eye” expand_text=”Show Answer” collapse_text=”Show Less” ]
Answer:- b) 4

In this program, “null” is a String literal with characters ‘n’, ‘u’, ‘l’, ‘l’. It is a simple string like “Java”, “program”, and e.t.c.. Hence s4.length() gives result 4.
[/bg_collapse]


The null and “null” are completely different things. The string s3 has null, it is a reference that can be used for initializing any reference variable. The compiler will not give any error if String is not null but JVM will give an exception when we try to excess string data. String reference is null so JVM gives an exception. Hence s2.length() gives NullPointerException in Q3.

But “null” is a String literal with 4 characters ‘n’, ‘u’, ‘l’, ‘l’. It is a simple string literal like “Hi”, “Hello”, “java”, and e.t.c. Hence s4.length() gives the result 4.

Also see:- String isBlank() Java with Examples

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *