Java string length Examples [Multiple Scenarios]

 

Getting Java string length

Sometimes we might want to find the length of String in the Java programming language. For example, to validate the password, the first thing to do is to compare the total length, so in such cases, we need to find the length of an unknown String.

In this tutorial, we will learn how we can find the Java string length using the length method. We will also cover various examples and see how we can calculate the length of a string without counting the whitespaces and who we can calculate the total number of whitespaces in a string.

Advertisement

Moreover, we will also use the length method to find the length of the String typed Java array. All in all, this tutorial will contain all the important scenarios that you need to know to find the java string length for different purposes.

 

Getting Started with java string length

Before going into and finding the size of the java string, let us first recap java strings. So, a Java string is a sequence of characters that exist as an object of the class java. Java strings are created and manipulated through the string class. Once created, a string is immutable its value cannot be changed. You can read more from our article on "java string methods". Let us here see the syntax of strings in java through an example.

 

Syntax and example of a Java String

There are two ways to create String in java. The first method is using java literals. See the simple syntax below:

String name_of_string = "String Expression";

Another way to create a Java string is to create a String object from the Java string class. See the simple syntax below:

String name_of_string = new String("string expression");

Now let us take an example and create strings using both methods. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // Using string literals
        String string1 = "This is string one";
        // using string class
        String string2 = new String("This is string two");

        // printing the strings
        System.out.println(string1);
        System.out.println(string2);
    }
}

Output:

Advertisement
This is string one
This is string two

 

Get length of string in Java

Java Strings are one of the most common and widely used classes in Java programming. The String is an array of characters, and since arrays are immutable in nature, a String is an immutable object, which means they are constant, and we cannot change them after creating the objects. In this section, we will see how we can find the size of a string using the length method and will solve various examples related to finding the length.

 

Syntax and return type of Java length method

The simple syntax to get java string length looks like this;

StringName.length();

The length method returns an integer value which will be the size of the String. This method is not only used to find the length of the String but also can return the size of an array as well.

See the diagram below which shows pictorially the length of a string.

Java string length Examples [Multiple Scenarios]

Now let us take a practical example of the java length method and find out the length of a string. See the example below where we had found the length of a string using this method.

// class
public class Main  { 
    public static void main(String[] args){
        // Java string
        String string1 = "This is string one";
        // Check java string length 
        System.out.println("The length of java string is :" + string1.length());
    }
}

Output:

The length of java of string is :18

Notice that this method also counts the whitespaces as characters because they are considered to be characters in Java.

 

Example-1: Check java string length having only whitespaces

Now let us take an example of a string containing only whitespaces and then let us apply the java length method on it to find its length. See the example below:

Advertisement
// class
public class Main  { 
    public static void main(String[] args){
        // Java string
        String string1 = "           ";
        // java string length 
        System.out.println("The length of java string is :" + string1.length());
    }
}

Output:

The length of java of string is :11

Notice that the strings only contain whitespaces and java counts them as characters.

 

Example-2: Check if java string length is empty

It is possible to have an empty string and the size of such string will be zero. But how can we validate if a string is empty or not.

Let us take an example and print out a message if the string is empty, else we will print the size of the string. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // Java string
        String string1 = "Welcome to golinuxcloud tutorials";
        String string2 = "";
        // calculate and get java string length
        if(string1.length()==0){
            System.out.println("String1 is empty");
        }else{
            // print java string length 
            System.out.println("The size of string1 is :" + string1.length());
        }
        // get java string length
        if(string2.length()==0){
            // print java string length
            System.out.println("String is empty");
        }else{
            // print java string length 
            System.out.println("The size of string2 is :" + string1.length());
        }  
    }
}

Output:

The size of string1 is :33
String is empty

Notice that the second string was an empty string and we get the result accordingly.

 

Example-3: Iterating over a string to get the string size

It is very important to know the size of the string to iterate over it and if a string is too long it is not a good idea to count the characters manually. We can directly use the length method in for loop to find the length of the string and iterate over it. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // Define Java string
        String string1 = "golinuxcloud";
        // looping using string length method to get string length
        for (int i = 0; i<string1.length(); i++){
            // printing individual characters
            System.out.println(string1.charAt(i));
        } 
    }
}

Output:

g
o
l
i
n
u
x
c
l
o
u
d

Notice that we used the length method to iterate over the string using for loop.

 

Example-4: Get the number of whitespaces in Java string

Sometimes we might want to know how many whitespaces are there in our string. The length method in java can also be used to find only the white spaces present in the string. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // Java string
        String string1 = "Welcome to go linux cloud";
        int totalSize = string1.length();
        // replacing whitespaces
        String string2 = string1.replace(" ", "");
        int whitespace = string2.length();

        // printing the total number of white spaces
        System.out.println("total whitespaces are : "+ (totalSize - whitespace));
    }
}

Output:

total whitespaces are : 4

Notice we had used replace method to replace the whitespaces and then subtracted total the total whitespaces by subtracting the length of string without whitespaces from the length of a string having white spaces.

 

Example-5: Find the length of Java string without whitespaces

Finding the length of string without whitespaces is very similar to the one that we did in the last example. We will just replace the whitespaces and find the length of the remaining string. See the example below;

// class
public class Main  { 
    public static void main(String[] args){
        // Java string
        String string1 = "Welcome to go linux cloud";
        // replacing whitespaces
        String string2 = string1.replace(" ", "");

        // printing the total number of white spaces
        System.out.println("Total length with whitespaces is : "+ string1.length());
        System.out.println("Total length without whitespaces is:" + string2.length());
    }
}

Output:

Total length with whitespaces is : 25
Total length without whitespaces is:21

Notice that there were four spaces and we get the result correctly.

 

Example-6: Get the length of String typed array

n array in Java is a set of variables referenced by using a single variable name combined with an index number. Each item of an array is an element. All the elements in an array must be of the same type. You can read more about arrays from the article java arrays. In this section, we will see how we can find the length of an array using java length method. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        //java array
        String[] array = {"welcome","to", "go", "linux", "cloud"};
        // length of array using java length method
        System.out.println("The size of the array is: "+ array.length);
    }
}

Output:

The size of the array is: 5

 

Summary

Strings in Java are Objects that are backed internally by a char array. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created. In this tutorial, we learned about finding java string length. We learned how we can use the length method available in java to find the length of a string by taking various examples.

Moreover, we also covered how we can find the total number of whitespaces in a string and how we can find the length of a string without counting the whitespaces. Furthermore, we also learned how we can find the size of a string typed array using the length method. All in all, this tutorial covers everything about java string length.

 

Further Reading

java string length 
String documentation in java
More about strings

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment