In this section we will learn what the String charAt() method is and how to use it in Java.
What is Java String charAt() Method?
The charAt() method is used to get a character at the specified index of a string value.
Java charAt () Method Syntax:
public char charAt(int index)
charAt() Method Parameters:
This method takes one argument and that is an integer number. This number represents the index in which we want to get the character in that location.
charAt() Method Return Value:
The return value of this method is of type char and is the character at the specified location.
charAt() Method Exceptions:
The value we set as the argument of the method should be in the range of the length of the target String. Otherwise we will get the StringIndexOutOfBoundsException exception.
The first element of a string is at index 0 and the last one is at index (length-1). So make sure the number is in the range.
Example: using String charAt() method
public class Simple { public static void main(String[] args) { String s = "HELLO"; char c = s.charAt(4); System.out.println(c); } }
Output:
O
Char to Int in Java
In Java you can create a variable of type integer and then pass the value of a character variable to it. Behind the scene Java will cast a value of type char and returns its integer representation.
Example: converting char to Int in Java
public class Simple { public static void main(String[] args) { char c = ‘1’; int i = c; System.out.println(i); } }
Output:
1