How to Find String Length in Java Program
Here you will get program code to find string length in java program by using 2 different ways.
1. using length() method
2. without using length() method
Program to Find String Length in Java Program using length()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import java.util.Scanner; public class FindStringLength{ public static void main(String[] args) { String str; Scanner in = new Scanner(System.in); System.out.print("Enter a string : "); str = in.nextLine(); // find length using length() method int length = str.length(); // Print length of string System.out.println("The length of the string is: " + length); } } |
Output
C:\CodeRevise\java>javac FindStringLength.java
C:\CodeRevise\java>java FindStringLength
Enter a string : Coderevise.com
The length of the string is: 14
Find String Length in Java Program without using length()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import java.util.Scanner; public class FindStringLength{ public static void main(String[] args) { String str; int length=0, index=0; Scanner in = new Scanner(System.in); System.out.print("Enter a string : "); str = in.nextLine(); // find String length while (index < str.length()) { length++; index++; } // Print length of string System.out.println("The length of the string is: " + length); } } |
Output
C:\CodeRevise\java>javac FindStringLength.java
C:\CodeRevise\java>java FindStringLength
Enter a string : Welcome to Code Revise
The length of the string is: 22
Check out our other Java Programming Examples