Java Program example to demonstrate String charAt method

Program

import java.util.Scanner;
public class StringCharAt
{
	public static void main(String args[])
	{
		String str = "Welcome to oodlescoop";
		int pos;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter an integer number:");
		pos = sc.nextInt();
		System.out.println("Character at pos " + pos + " is: " + str.charAt(pos));
	}
}

This Java program demonstrates how to use the charAt method of the String class to extract a character at a specific position in a string.

1. Import the Scanner Class

import java.util.Scanner;

  • Allows the program to take input from the user.

2. Class Definition

public class StringCharAt

  • Defines the class StringCharAt.

3. Main Method

public static void main(String args[])

  • The entry point of the program where execution begins.

4. Declare and Initialize Variables

String str = "Welcome to oodlescoop";
int pos;
  • str: Stores the string "Welcome to oodlescoop".
  • pos: Will store the position entered by the user to fetch the character from the string.

5. Take Input from the User

Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer number:");
pos = sc.nextInt();
  • Step 1: Create a Scanner object to take input.
  • Step 2: Prompt the user to enter an integer, which will represent the index of the character in the string str.
  • Step 3: Store the entered integer in the variable pos.

6. Fetch and Display the Character

System.out.println("Character at pos " + pos + " is: " + str.charAt(pos));

  • Step 1: Call str.charAt(pos) to get the character at the specified position (pos).
    • The charAt method returns the character at the zero-based index pos in the string.
  • Step 2: Display the result to the console.

Important Notes

  1. Indexing in Java Strings:

    • Java strings are zero-indexed, meaning:
      • The first character is at index 0.
      • The second character is at index 1, and so on.
  2. Potential Exception:

    • If the user enters a position (pos) that is negative or greater than or equal to the string’s length, the program will throw an exception:
      • java.lang.StringIndexOutOfBoundsException.

Key Methods and Concepts

  1. String.charAt(int index):

    • Returns the character at the specified index of the string.
    • Throws an IndexOutOfBoundsException if the index is out of bounds.
  2. Input Handling:

    • The program assumes valid input. To handle invalid inputs (like out-of-bounds indexes), you could add error handling.

Output

Enter an integer number:
11
Character at pos 11 is: o