In java, to print the length of given string we can use default length() method of the String class or loop concept such as for loop. If the input string is “Hello” then the length of the string is 5.
In this article we will learn writing Java program to print the length of the given string through examples, detailed logic and programming explanation for better understanding.
What is String?
- A String is a class, which can be used as a non-primitive data type in Java. As it is not a primitive data type, it has no default size and it is capable of holding text which might be alphabets, characters, numbers etc.
- While using as a data type, we will start the first letter in capital as String represents class.
Required Knowledge
- Java programming basics
- Loop concepts
- Java Operators
- String Concept
Problem Statement
We need to write a Java program to print the length of the given String. The program should take an input string and should find its length including spaces and print it as an output.
In this tutorial we will learn how we can achieve the same using Java programing language. Let’s see an example,
Example:
For a given input String str “Namaste, India”, Output should be 14.
Explanation:
Input String str: Namaste, India
str has 12 alphabets, 1 comma and 1 space
Length is combination of all the spaces, alphabets and special characters as well as numbers.
Hence, length of the str is 14.
Logic to print the length of the String
There are multiple logics to print the length of the string in the java programming language.
Logic 1: Using length() method
- To find length of a given string using length() method from the String class, first we need to initialize the string ‘str’ with some text by asking the user.
- Now, initialize the variable strLength to hold the length of the string str (strLength = str.length()).
- Now, print this strLength variable to display the result.
Logic 2: Using loop concept (for loop)
- To find length of a given string using for loop, first we need to initialize the string ‘str’ with some text by asking the user.
- Initialize an integer variable length to 0 (which holds length of the string).
- Then iterate through each character of the string using a for-each loop. For each character encountered, it increments the length variable.
- After iterating through all characters, the print the length of the string str to display the length.
Java Program to print the length of the String
✅ Program 1: Using length() method
In the below program we are using length method from the String class to print the length of the string.
import java.util.Scanner;
public class LengthString {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a text");
String str = s.nextLine();
int strLength = str.length();
System.out.println("Length of the text: " + strLength);
s.close();
}
}
Output:
Enter a text
Hi, how are you??
Length of the text: 17
🔍 Explanation:
- The program asks the user to enter a text string.
- It reads the input string using a
Scanner
object and stores it in a variable calledstr
. - The program calculates the length of the input string using the
length()
method of theString
class and stores it in an integer variable namedstrLength
. - It then prints the length of the text string to the console.
- Finally, it closes the
Scanner
object to release system resources.
✅ Program 2: Using for loop
In the below program we are using for loop to print the length of the string.
import java.util.Scanner;
public class LengthString {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a text");
String str = s.nextLine();
int length =0;
for(char ch: str.toCharArray()) {
length++;
}
System.out.println("Length of the text : " +length);
s.close();
}
}
Output:
Enter a text
Learn Well, Stay Focused.
Length of the text: 25
🔍 Explanation:
- The program asks the user to enter a text string.
- It reads the input string using a
Scanner
object and stores it in a variable calledstr
. - It initializes an integer variable named
length
to store the length of the string. - It iterates through each character of the string using an enhanced for loop (
for each
loop) and increments thelength
variable for each character encountered. - After iterating through all characters, it prints the length of the text string to the console.
- Finally, it closes the
Scanner
object to release system resources.
There are still multiple version of the code to achieve the same task. Lets see all of them one by one.
✅ Program 3: Hardcoded String (No Input Required)
public class HardcodedLengthCheck {
public static void main(String[] args) {
String sample = "Coding is creative!";
int count = sample.length();
System.out.println("String: \"" + sample + "\" has " + count + " characters.");
}
}
🔍 Explanation:
- Define String:
sample
is assigned a predefined value. - Find Length:
.length()
is used to find how many characters are present. - Display Result: Shows the string and its length in a friendly message.
✅ Program 4: Length via Recursion (Creative Style)
public class RecursiveStringLength {
public static void main(String[] args) {
String message = "Recursive way";
int length = findLength(message);
System.out.println("Total characters: " + length);
}
static int findLength(String str) {
if (str.equals("")) {
return 0;
} else {
return 1 + findLength(str.substring(1));
}
}
}
🔍 Explanation:
- We define a method
findLength()
that uses recursion. - Base case: If the string is empty, return 0.
- Recursive case: Cut off the first character using
substring(1)
and add 1. - This continues until the whole string is processed
✅ Program 5: Using Java 8 Streams (Modern Style)
public class StreamBasedLength {
public static void main(String[] args) {
String sentence = "Streams are powerful";
long length = sentence.chars().count();
System.out.println("Length using streams: " + length);
}
}
🔍 Explanation:
.chars()
converts the string into anIntStream
of character codes..count()
counts the number of elements (characters).- Very clean and modern approach using Java 8+ features
Conclusion
The programs we did here gives us length of the string using length() method of the string class and a for loop.