Java String length (String size)

By | September 29, 2021
Java String length

Introduction

There is only one method to find the length of a string i.e. the length() method. We will see multiple examples to see how the method works.

How to find String length in Java

Using the length() is very straightforward, but we need to handle few conditions, especially if we are taking inputs from a user. Let us start with a simple example:

Vamware
Scanner scan = new Scanner(System.in);
System.out.println("Enter a string: ");
String input = "";
input = scan.nextLine();
int length = input.length();
System.out.println("Length of String you entered is: " + length);

We are taking String input from the user. Note that we are using the nextLine() method in place of next(). With the next() method, space becomes a delimiter, hence if we have a statement with more than one word, those won’t be counted. Using nextLine() will take all the words before the user presses enter. By using nextLine(), the length() method also counts the white spaces. If you don’t want that, you can use the replace() method to remove the white spaces.

input = input.replace(" ", "");

We can also use the replaceAll() method to achieve the same.

It is also a good idea to trim the input received to remove any leading or trailing white spaces given accidentally by a user:

input = input.trim();

You can also hard code the string and get the length:

String input = "08098098@#@$@#$@##@#sfsslslsllsll";

This will give the output as 33.

Note that we usually check for ‘null’ before doing a dot operation to get Java String length, but here we need not do so, as while hard-coding, we are making sure to give a value. While taking user input, when we press enter, the string value is rendered empty and not null.

Conclusion

We have learned a very simple method to calculate the length of a Java String. Note that anything that is put inside those double quotes is considered as a String and length takes it in, unless you manipulate the string specifically, just like we did for the white space.

People are also reading: 

 

Leave a Reply

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