In Java, String.length() method yields the total number of characters (or Unicode code units) in the specified string. It is crucial to remember that the length provided by this method may not match the length that humans perceive, particularly when working with strings that contain characters from multi-byte encoding languages like UTF-8.
Specified by: Length in CharSequence interface.
Returns: Length of the given string. In other words, the total number of characters present in the string.
The String class internally uses a char[] array to store the characters. The length variable of the array is used to find the total number of elements present in the array. Since the Java String class uses this char[] array internally.

Output:
string length is: 10 string length is: 6
Explanation
In the above program, two strings, "TpointTech" and "python", are stored in variables s1 and s2 respectively. The length() method is called on each to find the length (number of characters). The output shows that s1 has a length of 10 and s2 has a length of 6.
Output:
String is not empty and length is: 10 String is empty now: 0
Explanation
In the above example, the string str is initialized to "TpointTech", and the code checks if its length is greater than 0 or not. Since it prints that the string is not empty along with its length.
Then, str is updated to an empty string "", and the code checks if its length is 0. As the condition is true, it prints that the string is now empty.
Output:
Reverse of the string: 'Welcome To TpointTech' is tniopTavaJ oT emocleW
Explanation
In the above program, we have defined and initialized a string in str variable. The length method determines the length of the given string. We have used a for loop that iterates over the string. For reversing the string we have used str.charAt(str.length() - i - 1). This technique combines the length() method with charAt() to efficiently reverse the string.
Output:
In the string: ' Welcome To TpointTech ' Total number of whitespaces present are: 4
Explanation
The String.length() method can also be used to find only the white spaces present in the string. It first calculates the length of the string, including all spaces. Then it removes all spaces using the str.replace(" ", "") method and calculates the new length. By subtracting the new length from the original one, the code determines the total number of whitespace characters.
We request you to subscribe our newsletter for upcoming updates.