Java Online Compiler
Example: AccessingCharacters in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// AccessingCharacters public class Main { public static void main(String[] args) { // Step 1: Initialize a string String word = "EXAMPLE"; // Step 2: Access the character at index 0 (first character) char firstChar = word.charAt(0); // Step 3: Access the character at index 3 (fourth character) char fourthChar = word.charAt(3); // Step 4: Access the last character (length - 1) char lastChar = word.charAt(word.length() - 1); // Step 5: Print the accessed characters System.out.println("Original word: " + word); System.out.println("First character: " + firstChar); System.out.println("Fourth character: " + fourthChar); System.out.println("Last character: " + lastChar); // Note: Accessing an index out of bounds will throw a StringIndexOutOfBoundsException // char invalidChar = word.charAt(10); // This would cause an error } }
Output
Clear
ADVERTISEMENTS