The String length in Java is the total amount of unicode characters of a string. In this tutorial, you will learn how to find the string length in Java, along with examples.
What Is the Method Used to Find String Length in Java?
The Java String class provides the redefined method length(), specified in the CharSequence interface. The string length in Java is used to calculate the length of the specified string.
Java String Length() Method Syntax:
Written below is the general syntax of using the Java string length() method.
public int length()
As you can see in the syntax, the string length in Java accepts no parameter. The internal implementation of the length() method is:
public int length(){
return value.length;
}
Java String Length Return Value
The length() method returns an integer value that defines the string’s length in unicode characters.
String Length in Java Examples
Since you now know what string length in Java is, and the method used to find out the length, look at some of these examples and see it in action.
Finding the Length of a Null String
In the example below, you will try to find the length of a null value. Let’s see what it returns.
As you can see in the result, the null value’s length is always 0, as you might have already guessed.
Finding the Length of a Single Word
Let’s use the string length in Java to find how long is “Simplilearn” and “Java.”
Finding the Length of Multiple Words in a String
Now, it’s time to find the length of a string with multiple words.
As you can see in the above example, string length in Java considers a “ ” and other special characters as a unit, and increases the length by one on each instance of a special character.
Finding String Length in Java Using If and Else Statements
In the example below, you must declare two strings. One string has a null value, and the other has “Simplilearn.” You will have to write the if… else statements to display the string length in Java.
Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.
Summing It Up
This tutorial has helped you understand string length in Java. You can refer to Simplilearn’s Java Tutorial for Beginners guide to learn about the other methods available in the Strings class. Besides the Strings class, it will also help you learn about arrays, OOPs concepts, and much more. You can also opt for our Online Java Certification Course to understand all the basic and advanced Java programming concepts and become a certified developer.
Check out our next tutorial on the reverse a string in java.
Do you have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same as soon as possible.
Happy learning!