Length of the string without using length() function in Java
Understanding String Length Calculation
The length of a string is the number of characters it contains. In Java, we can determine this without using the built-in length() function.
We will explore three different methods to find the length of a string in Java.
Method 1: Using a Loop
This method uses a loop to count the characters in the string.
import java.util.Scanner;
public class StringLengthLoop {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
scanner.close();
int length = 0;
for (char ch : str.toCharArray()) {
length++;
}
System.out.println("Length of the string is " + length);
}
}
Input: Hello
Output: Length of the string is 5
Output: Length of the string is 5
Method 2: Using Recursion
This method calculates the length of the string recursively.
import java.util.Scanner;
public class StringLengthRecursion {
public static int findLength(String str, int index) {
if (index >= str.length())
return index;
return findLength(str, index + 1);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
scanner.close();
System.out.println("Length of the string is " + findLength(str, 0));
}
}
Input: World
Output: Length of the string is 5
Output: Length of the string is 5
Method 3: Using Character Array
This method converts the string to a character array and counts its elements.
import java.util.Scanner;
public class StringLengthArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
scanner.close();
char[] charArray = str.toCharArray();
int length = 0;
for (char c : charArray) {
length++;
}
System.out.println("Length of the string is " + length);
}
}
Input: Programming
Output: Length of the string is 11
Output: Length of the string is 11