w3resource

Java: Get the length of a given string


22. String Length

Write a Java program to get the length of a given string.

Visual Presentation:

Java String Exercises: Get the length of a given string


Sample Solution:

Java Code:

// Define a public class named Exercise22.
public class Exercise22 {
    // Define the main method.
    public static void main(String[] args) {
        // Declare and initialize a string variable.
        String str = "example.com";
        
        // Get the length of the string 'str'.
        int len = str.length();
        
        // Display the length of the string.
        System.out.println("The string length of '" + str + "' is: " + len);
    }
}

Sample Output:

The string length of 'example.com' is: 11

Flowchart:

Flowchart: Java String  Exercises - Get the length of a given string


For more Practice: Solve these Related Problems:

  • Write a Java program to calculate the length of a string without using the built-in length() method.
  • Write a Java program to compare the lengths of two strings and display the longer one.
  • Write a Java program to determine the length of a string after removing all spaces.
  • Write a Java program to compute the length of a string and then display it in both numeric and word formats.

Go to:


PREV : Last Index of Character.
NEXT : Region Match Between Strings.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.