To find length of a String you can use length() method of the Java String class. This method returns the count of characters in the String object including spaces.
Java String length() method examples
1. In the examples there are two strings and length of those String is calculated using length()
method.
public class StringLength { public static void main(String[] args) { String str1 = "String length method"; //separated by 4 spaces String str2 = "Hello World"; System.out.println("Length of str1- " + str1.length()); System.out.println("Length of str2- " + str2.length()); } }Output
Length of str1- 20 Length of str2- 14
2- Printing each character by iterating a String, using String’s length() method to limit the iteration.
public class StringLength { public static void main(String[] args) { String str = "Hello"; for(int i = 0; i < str.length(); i++) { System.out.println(str.charAt(i)); } } }Output
H e l l o
That's all for the topic Java String length() Method With Examples. If something is missing or you have something to share about the topic please write a comment.
You may also like
- Java StringJoiner Class With Method Examples
- Java String split() Method
- Java String repeat() Method
- Java Multithreading Interview Questions And Answers
- Java Spliterator With Examples
- How to Convert File to Byte Array in Java
- Exclude Bean From Autowiring in Spring
- How to Read And Write Avro Files in Hadoop
No comments:
Post a Comment