String Methods

String Length

🙋 Need help? Ask an expert now!

Let's dive into introducing the methods that exist in the String class. A fundamental method to start off with is one that finds the length of a String, which is also the number of characters, including punctuation and spaces, that make up the string. The syntax for finding the length of a String is stringname.length(). Look below to see an example of its use.

StringLengthExample.java
package exlcode;

public class StringLengthExample {

  public static String exampleVariableOne = "Hello World!";
  public static String exampleVariableTwo = "";
  // returns the length of exampleVariableOne and exampleVariableTwo
  // and assigns it to lengthOne and lengthTwo
  public static int lengthOne = exampleVariableOne.length();
  public static int lengthTwo = exampleVariableTwo.length();

  public static void main(String[] args) {
    System.out.println(lengthOne);
    System.out.println(lengthTwo);
  }
}

Did you run the program? Did you see how an empty String has a length of zero? Take note of the fact that the length method takes no parameters but the parenthesis are part of the necessary syntax to call the method, along with the dot which tells the program that you want to use the length method that exists in the String class.

Please keep in mind for future sections, that the length of the String has nothing to do with the index. You can just count up the number of characters inside the String to determine the accurate length.

Application Question

What is the length of the String "Hello World!"?