Java String length() method
The length() of a String object returns the length of this string. The length of java string is same as the unicode code units of the string. Syntax:
public int length()
There is no parameter for length() and it returns the count of total number of characters. Also note that the method is not static, this means that the method can only be invoked through a Java String instance.
Example
class TestClass{
public static void main (String[] args){
String str = "Halo World!";
System.out.print("The length of the String is :" + str.length() );
}
}
Output:
The length of the String is :11
How check the String is empty or not?
The following Java program check whether the string is empty or not.
class TestClass
{
public static void main (String[] args){
String str = "Halo World!";
int len = str.length();
if(len<=0)
System.out.println("String is Empty !!");
else
System.out.println("String is not Empty !!");
}
}
Output:
String is not Empty !!
Printing one char on each line in Java
The following program display each character in a string one by one.
class TestClass
{
public static void main (String[] args){
String str = "Halo World!!";
int len = str.length();
for (int idx = 0; idx <len; idx++) {
char ch = str.charAt(idx);
System.out.println(ch);
}
}
}
Output:
H
a
l
o
W
o
r
l
d
!
!
What is the maximum size of string in Java?
Strings contain an array of chars. You should be able to get a String of length Integer.MAX_VALUE (always 2147483647 (2^31 - 1) by the Java specification, the maximum size of an array, which the String class uses for internal storage) or half your maximum heap size (since each character is two bytes), whichever is smaller.
Related Topics
- Java String charAt() Method
- String indexOf() method
- Java String replace()
- Java String contains()
- String Comparison in Java
- Java String substring()
- Java String concat() Method
- Java String split() method
- Convert String to int
- Java StringBuilder Class
- StringTokenizer in Java
- How to convert int to String in Java?