Javatpoint Logo
Javatpoint Logo

How to Read Character in Java

Java Scanner class provides nextInt() method for reading an integer value, nextDouble() method for reading a double value, nextLong() method for reading a long value, etc. But there is no nextChar() method in the Scanner class to read a character in Java. In this section, we will learn how to take character input in Java.

To read a character in Java, we use next() of the Scanner class method followed by chatAt() at method of the String class.

Java next() Method

The next() method is a method of Java Scanner class. It finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. It may block while waiting for input to scan, even if a previous invocation of hasNext() return true.

Syntax:

The method throws the NoSuchElementException if no more tokens are available. It also throws IllegalStateException if the scanner is closed.

Java chatAt() Method

The charAt() is a method of the Java String class. It returns the char value at the specified index (range from 0 to length()-1). In a character sequence, the first character index value is 0, the next at index 1, and so on.

Syntax:

The method throws IndexOutOfBoundsException if the index argument is negative or not less than the length of the string.

To read a character in Java, we use next() method followed by charAt(0). The next() method returns the next token/ word in the input as a string and chatAt() method returns the first character in that string.

We use the next() and charAt() method in the following way to read a character.

The following program takes a character from user, as input and prints the same character.

CharacterInputExample1.java

Output:

Input a character: R
You have entered R

CharacterInputExample2.java

Output:

Input a character: W
You have entered W

Next TopicJava Tutorial





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA