Access Character of a String in Java



In this article, we will access a specific character from a string by using the charAt() method in Java. The program will demonstrate how to locate and display a character at a specified position within a string.

Problem Statement

We have a string, and we need to retrieve the character at a given position. For example, if we use the string "laptop", we want to display the character located at the 4th position (0-based index).

Input

"laptop"

Output

String: laptop
Character at 4th position: t

Steps to access character of a string

The following an steps to access the character of a string ?

  • First, we will define the string "laptop".
  • Use the charAt() method with the desired position as a parameter (keep in mind indexing starts from 0).
  • Print the result to show the character at the specified position.

Java program to access character of a string

The following is an example to access the character of a string ?

public class Demo {
   public static void main(String[] args) {
      String str = "laptop";
      System.out.println("String: "+str);
      // finding character at 4th position
      System.out.println("Character at 4th position: "+str.charAt(3));
   }
}

Output

String: laptop
Character at 4th position: t

Code explanation

In this program, we first initialize a string, str, with the value "laptop". We then call the charAt(3) method to retrieve the character at the 4th position (0-based index). The charAt() method returns the character at the specified index, so str.charAt(3) returns 't', which is then printed as the output.

Updated on: 2024-11-11T19:16:55+05:30

35K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements