How to find length of string in java?

 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.

Java - length() method in String

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 

1) Employee Management System using Spring Boot Microservices & React.

2) Hotel Management System using Spring Boot & React.

3) E-commerce Project using Spring Boot & React.

4) Gym Management System using Spring Boot & React.

Students can use this project for learning and can submit the project for their final year or Internship projects.

IF YOU WANT THE PROJECT DO CONTACT ME. 

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.

Or You can simply Request for the Project Source Code & Set Up by clicking on the below button.

MAIL ME AT codewithmurad@gmail.com

DM ME ON INSTAGRAM at @codewithmurad

DM ME ON FACEBOOK at @codewithmurad 

DM ME ON TELEGRAM at @codewithmurad 

Connect on My Discord Server: CLICK HERE

Post a Comment

0 Comments