Java String length()The Java String class length() method finds the length of a string. The length of the Java string is the same as the Unicode code units of the string. SignatureThe signature of the string length() method is given below: Specified byCharSequence interface ReturnsLength of characters. In other words, the total number of characters present in the string. Internal implementationThe 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; therefore, the length variable can not be exposed to the outside world. Hence, the Java developers created the length() method, the exposes the value of the length variable. One can also think of the length() method as the getter() method, that provides a value of the class field to the user. The internal implementation clearly depicts that the length() method returns the value of then the length variable. Java String length() method exampleFileName: LengthExample.java Test it NowOutput: string length is: 10 string length is: 6 Java String length() Method Example 2Since the length() method gives the total number of characters present in the string; therefore, one can also check whether the given string is empty or not. FileName: LengthExample2.java Output: String is not empty and length is: 10 String is empty now: 0 Java String length() Method Example 3The length() method is also used to reverse the string. FileName: LengthExample3.java Output: Reverse of the string: 'Welcome To JavaTpoint' is tniopTavaJ oT emocleW Java String length() Method Example 4The length() method can also be used to find only the white spaces present in the string. Observe the following example. FileName: LengthExample4.java Output: In the string: ' Welcome To JavaTpoint ' Total number of whitespaces present are: 4 Next TopicJava String replace() |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India