Java char type read from the Console

Introduction

To read a character from the console:

  • Use the nextLine() method to read a string and
  • Invoke the charAt(0) method on the string to return a character.

For example, the following code reads a character from the keyboard:

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      System.out.print("Enter a character: ");
      String s = input.nextLine();
      char ch = s.charAt(0);
      System.out.println("The character entered is " + ch);

      input.close();/* w  ww.  j  ava2  s .c  o m*/
   }
}



PreviousNext

Related