Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to display the length of a string.

Java Code Example — String Programs

ADVERTISEMENT

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

  1. Use the Scanner class to accept a line of text from the user using nextLine().
  2. Store the input in a String variable.
  3. Use the built-in length() method of the String class to find the total number of characters.
  4. 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 length is 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)
ADVERTISEMENT