Home »
Java programming language
Java | String.charAt(index) | Getting character by Index from string
Java String.charAt(index) method with Example: Here, we will learn how to get character by index from a given string?
Submitted by IncludeHelp, on July 03, 2018
String.charAt() function is a library function of String class, it is used to get/retrieve the specific character from a string. Where, the index starts from 0 and ends to String.lenght-1.
For example, if there is string "Hello", its index will starts from 0 and end to 4.
Note: If you try to access the character out of bounds, an exception StringIndexOutOfBoundsException will generate. So, be careful while using index in the string.
Example1:
In this example, there is string initialized by "Hello world!" and we have to access its 0th and 7th character.
public class Example1
{
public static void main (String[] args) throws java.lang.Exception
{
String msg = "Hello world!";
System.out.println("Character at 0th index: "+ msg.charAt(0));
System.out.println("Character at 7th index: " + msg.charAt(7));
}
}
Output
Character at 0th index: H
Character at 7th index: o
Example2:
In this example, we have to read a string and print it character by character
import java.util.*;
public class Example2
{
public static void main (String[] args) throws java.lang.Exception
{
//string Object
String msg = null;
//Scanner class Object
Scanner scan = new Scanner(System.in);
//input a string
System.out.println("Input a string: ");
msg = scan.nextLine();
//printing string character by character
System.out.println("Input string is: ");
for(int loop =0; loop<msg.length(); loop++)
System.out.print(msg.charAt(loop));
}
}
Output
Input a string: I love programming.
Input string is:
I love programming.
TOP Interview Coding Problems/Challenges