Java Program to display the length of a string.
Objective
Write a Java program to accept a string from the user and display its total length.
Algorithm / Approach
- Use the
Scannerclass to accept a line of text from the user usingnextLine(). - Store the input in a
Stringvariable. - Use the built-in
length()method of the String class to find the total number of characters. - Print the calculated length.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter String: ");
String name=s.nextLine();
int len = name.length();
System.out.print("Length = "+len);
}
}
Expected Output
Enter String: Java Prowesss Length = 12
Explanation of the Program
- In Java, a String is an object that represents a sequence of characters.
- Unlike arrays where
lengthis a property, for strings,length()is a method that returns the number of characters in the string, including spaces and punctuation.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)