
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.