Saturday, January 4, 2025
HomeProgrammingJava String Length Method with Examples

Java String Length Method with Examples

 

The length() method in Java is used to determine the number of characters in a String. It returns the total count of characters, including spaces, special characters, and digits.

Syntax:
java
int length = string.length();

Parameters:
– The length() method does not take any parameters.

Return Value:
– Returns an integer representing the number of characters in the String.

Examples:

Example 1:

Basic Usage
java
public class Main {
public static void main(String[] args) {
String str = “Hello, World!”;
System.out.println(“The length of the string is: ” + str.length());
}
}

See also  How to Get Current Date and Time in Java

Output:

The length of the string is: 13

Example 2:

Length of an Empty String
java
public class Main {
public static void main(String[] args) {
String str = “”;
System.out.println(“The length of the string is: ” + str.length());
}
}

Output:

The length of the string is: 0

Example 3:

Length with Spaces
java
public class Main {
public static void main(String[] args) {
String str = ” Java Programming “;
System.out.println(“The length of the string is: ” + str.length());
}
}

Output:

The length of the string is: 23

Example 4:

Using length() with Special Characters
java
public class Main {
public static void main(String[] args) {
String str = “Hello@2025#”;
System.out.println(“The length of the string is: ” + str.length());
}
}

See also  How to Drop a Table If It Exists in SQL Server

Output:

The length of the string is: 11

Example 5: Checking String Length in a Loop
java
public class Main {
public static void main(String[] args) {
String[] strings = { “Java”, “Python”, “C++”, “” };
for (String str : strings) {
System.out.println(“The length of \”” + str + “\” is: ” + str.length());
}
}
}

Output:

The length of “Java” is: 4
The length of “Python” is: 6
The length of “C++” is: 3
The length of “” is: 0

See also  How to Remove Item from a List in Python

Key Notes:
1. The length() method does not count surrogate pairs as a single character.
2. It is different from the array’s .length property and the StringBuilder’s .length() method, but they all provide similar functionality for their respective data types

RELATED ARTICLES

Leave a Reply

- Advertisment -

Most Popular

Recent Comments