Java string length without using length() method

This article shows you how to find the string length without using length() method of String class. The String is a sequence of characters. Strings are widely used in Java programming.

Here, we use the toCharArray() method of the String class and for-each loop for length calculation. The java string toCharArray() method converts a string into a character array. It returns a newly created character array.

Find string length using toCharArray() method

package com.javacodepoint.string;

import java.util.Scanner;

public class FindStringLength {

	public static void main(String[] args) {

		// Create scanner object to read user inputs
		Scanner sc = new Scanner(System.in);

		// Read a string from user
		System.out.println("Enter a string: ");
		String str = sc.next();

		// Declare a variable to find length
		int length = 0;

		// for-each loop
		for (char ch : str.toCharArray()) {
			// increment the count for each character
			length++;
		}

		// Print the length
		System.out.println("The length of the string (" + str + ") is: " + length);
	}

}

OUTPUT:

Enter a string:
Javacodepoint
The length of the string (Javacodepoint) is: 13

See also:
Java Program to Count characters from the string in Java.
Java Program to Count the Number of Vowels in a String.

Java logical programs list


Java Basic Programs

Java String Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *