Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Beginners Java charAt() method

 
 

Share on Google+Share on Google+

Java charAt() method

Advertisement
charAt() method is used to find the character from the String.

Java charAt() method

In this section we will read about the chartAt() method in Java.

charAt() method in Java is belong to java.lang.String class. This method is used to find the character at the specified index of the specified String. This method returns the char of a String at the given index.

Syntax :

public char charAt(int index)

Index value for this method is started from the 0 (zero) and ended to the length()-1 of the String. This index value is like the array indexing. This method throws the IndexOutOfBoundsException if value of index is negative or greater than the length of the String.

Example

Here an example is being given which will demonstrate you about charAt() method in Java. In this example we will create a Java class where we will write the code for taking input through command line and then we will find the char value at the specified index of the String.

CharAtExample.java

import java.util.Scanner;

public class CharAtExample {

	public static void main(String args[])
	{
		Scanner scan = new Scanner(System.in);
		System.out.print("Enter String : ");
		String text = scan.next();
		int length = text.length();
		int lastindex = length-1;
		if(length > 0)
		{
			System.out.print("Enter the index from 0 to "+lastindex+" : ");
			int index = scan.nextInt();
			if(index >=0 && index <length)
			{
				char character = text.charAt(index);
				System.out.println("Character at index "+index+" of String "+text+" is : "+character);
			}
			else
				System.out.println("Invalid Index Value ! Index Must Be Given Within Index Range");
		}
	}
}

Output

When you will compile and execute the above example you will get the output as follows :

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 3, 2013

Related Tutorials

Discuss: Java charAt() method  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com