Java - length() method in String
In this tutorial, we will learn how to find the length of the string in Java.
For finding the length of a String in Java, we have got a method called the length() method which is present in the String class as we can see in the below picture.
ABOUT LENGTH() METHOD
Syntax:
public int length()
The method length() is present inside the class String which is present inside Java.lang package.
Returns:
It returns the length of this string. The length is equal to the number of Unicode code units in the string.
Or in simple language, we can say it returns the total number of characters present in the string.
Example:
public class LengthDemo {
public static void main(String[] args) {
String string1 = "Code";
String string2 = "Code With Murad"; // here it will count space also
int lengthOfString1 = string1.length(); // 4
int lengthOfString2 = string2.length(); // 15
System.out.println("Length of String1 is : "+lengthOfString1);
System.out.println("Length of String2 is : "+lengthOfString2);
}
}
The output of the program:
The length of String1 is: 4
The length of String2 is: 15
Cases:
1) If we try to find the length of String="" then it will return 0 as shown below:
String string3 = "";
System.out.println("Length of String1 is :"+lengthOfString3);
// for this output will be Length of String1 is :0
2) Whereas, If we try to find the length of String=null then it will throw NullPointerException as shown below:
String string4 = null;
System.out.println("Length of String4 is :"+lengthOfString4);
// for this it will throw NullPointerException
I hope that you find this article useful. I'll love to hear from you. Let me know if you have any questions about the length() method in String in Java.
FINAL YEAR PROJECTS
Online Watch Shopping Project with PAYPAL integrated
(click on it to read more about the project )
Other practical projects using React & Spring Boot
I will give you the full project SOURCE CODE and I will do a COMPLETE SET-UP of the project on your PC or Laptop remotely.
MAIL ME AT mjmuradali31@gmail.com
DM ME ON INSTAGRAM at @muradalimj
DM ME ON FACEBOOK at Murad Ali
DM ME ON TELEGRAM at @muradalimj
Connect on My Discord Server: CLICK HERE
-----------------------------------------------------------------------------------------------------------------------------
CODE WITH MURAD
0 Comments