Java Online Compiler
Example: Get String Length using charAt() and try-catch in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Get String Length using charAt() and try-catch import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Initialize a string and a counter String str = "Hello Java"; int lengthCounter = 0; // Step 2: Use a try-catch block to iterate and detect end try { while (true) { str.charAt(lengthCounter); // Attempt to access character lengthCounter++; // Increment counter if successful } } catch (StringIndexOutOfBoundsException e) { // Step 3: The exception is caught when lengthCounter exceeds string bounds // The value of lengthCounter at this point is the string's length System.out.println("String: \"" + str + "\""); System.out.println("Length (using charAt and try-catch): " + lengthCounter); } } }
Output
Clear
ADVERTISEMENTS