How to input char in Java

Java Scanner doesn't provide any method for taking character input similar to nextInt(), nextLine(), etc.

There are a few ways we can take character input using Scanner.

Let's first create an input string:

String input = new StringBuilder().append("abc\n")
  .append("mno\n")
  .append("xyz\n")
  .toString();

3. Using next()

Let's see how we can use the next() method of Scanner, and the charAt() method of String class to take a character as input:

@Test
public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() {
    Scanner sc = new Scanner(input);
    char c = sc.next().charAt(0);
    assertEquals('a', c);
}

The next() method of Java Scanner returns a String object. We are using the charAt() method of the String class here to fetch the character from the string object.

4. Using findInLine()

This method takes a string pattern as input, and we'll pass “.” (dot) to match only a single character. However, this will return a single character as a string, so we'll use charAt() method to get the character:

@Test
public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() {
    Scanner sc = new Scanner(input);
    char c = sc.findInLine(".").charAt(0);
    assertEquals('a', c);
}

5. Using useDelimeter()

This method also scans only one character but as an object of string similar to findInLine() API. We can similarly use the charAt() method to get the character value:

Community driven content discussing all aspects of software development from DevOps to design patterns.

Latest Blog Posts

  • The config-interface constructor design pattern in TypeScript
  • Deliver software better, not faster
  • How to program to an interface in TypeScript
  • See More

  • Share this item with your network:

Related Content

  • Java Scanner User Input Example – TheServerSide.com
  • Java Scanner next() vs nextLine() methods: What's the... – TheServerSide.com
  • Java Scanner String input example – TheServerSide.com

Sponsored News

  • Optimizing Your Digital Workspaces? Look to Analytics –Citrix
  • What Work 2035 Will Look Like –Citrix

Vendor Resources

  • Dive Deeper into PowerShell Functions –TechTarget
  • The Role of Hackers in Security Assessments for Product Development –HackerOne

How to add Java Scanner char support

The Java Scanner class provides methods that take String input and convert that String into any Java primitive type you might need, except for one: the char.

The Java Scanner class provides the following self-explanatory methods:

  • nextInt()
  • nextByte()
  • nextBoolean()
  • nextFloat()
  • nextDouble()
  • nextLong()
  • nextShort()

But the one method it doesn’t have is nextChar().

Implement a Java Scanner nextChar method

Naturally, all Java developers, after learning the Java Scanner class has no nextChar method, want to implement one of their own. It’s not that hard.

By default, the Scanner class reads a line of input from a user and tokenizes the contents based on whitespaces found in the input.

nextInt()0

Sets this scanner’s delimiting pattern to the specified pattern.

This allows a developer to loop through input one text String at a time.

But you don’t have to accept the Scanner’s defaults. The Scanner class’ nextInt()1 method allows you to change the delimiter from a blank space to any character you want.

Simple Java user input made approaches

There are many ways to take input from the user and format the output in Java.

  • Top 3 Java user input strategies
  • How to import the Java Scanner class
  • A simple Java Scanner String input example
  • Use the Java Scanner for user input
  • How to format output with Java printf

Scanner input one char at a time

The trick is to change the delimiter to nothing.

Just set the delimiter to two double-quotes with nothing inside: nextInt()2. The empty quotes make the Scanner chunk out the line one char at a time.

At this point, the Scanner still returns a String, although the String contains only one character. To complete the use case, you must convert this one-character String into a single Java char with the nextInt()3 method.

Java Scanner char input code example

The code to get Scanner input one char at a time looks like this:

import java.util.Scanner;
public class NextCharScanner{
  
  // implement a nextChar Scanner method
  public static void main(String[] args) {
    System.out.println("Input char data to the Java Scanner: "); 
    Scanner charScanner = new Scanner(System.in); 
    charScanner.useDelimiter("");
    while (charScanner.hasNext()) {
      char name = charScanner.next().charAt(0);
      if (name == '\n') {
        return;
      }
    }
  }
}

Notice that the code has a check for the newline character, as this will be treated as an input character if not filtered out.

How to read the next char with Java’s Scanner

To summarize the process, follow these steps to read user input with the Java Scanner one char at a time:

How to create a char in Java?

You can create a Character object with the Character constructor: Character ch = new Character('a'); The Java compiler will also create a Character object for you under some circumstances.

How to receive char in Java?

To read a char, we use next(). charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string.

How to input a char in Java using scanner?

To summarize the process, follow these steps to read user input with the Java Scanner one char at a time:.
Read a line of text with the Scanner as you normally would do..
Change the Scanner's delimiter to an empty set of double quotes, "" ..
Convert each single-character to a char with the charAt(0) method..

Can char be added in Java?

The easiest and most commonly used method to add char to a String is the Concatenation operator “+”. It concatenates the character to a String. You can add additional characters either at the start, middle, or at the end of the String with the help of the “+” operator.