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.


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));


    Character at 0th index: H
    Character at 7th index: o


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++)


    Input a string:  I love programming.
    Input string is: 
    I love programming.

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.