Java String length (String size)

By | March 18, 2022
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:

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.

Vamware

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.

Vamware

People are also reading: 

 

Author: Ramya Shankar

A cheerful, full of life and vibrant person, I hold a lot of dreams that I want to fulfill on my own. My passion for writing started with small diary entries and travel blogs, after which I have moved on to writing well-researched technical content. I find it fascinating to blend thoughts and research and shape them into something beautiful through my writing.

Leave a Reply

Your email address will not be published.