In this tutorial we will see how to get char input in java . We can read character in java using different methods . We will see java program for how to take character input in java using Scanner.next().charAt(0) ,System.in.read() and InputStreamReader .
Example 1 : Get Char input in Java Using Scanner.next().charAt(0)
In this example we will use Scanner class for char input in java .We create Scanner class object for get input char in java. Here scanner.next().charAt(0) is use to read the input as char from Scanner input. charAt(0) reads first character from the scanner input.
import java.util.Scanner;
public class CharInputInJava {
public static void main(String[] args) {
//create scanner object
Scanner scanner = new Scanner(System.in);
System.out.println("Please input a character value: ");
//scanner.next().charAt(0)
char ch = scanner.next().charAt(0);
//print value for char
System.out.println("enter char is : " + ch);
}
}
Output:
Please input a character value:
A
enter char is : A
Example 2 : Take Char input in Java Using System.in.read()
In this example we will get char input in java using System.in.read() . System.in.read() reads one byte and returns an int and then we will convert int to characters .
import java.io.IOException;
import java.util.Scanner;
public class CharInputInJava2 {
public static void main(String[] args) throws IOException {
System.out.println("Please input a character value: ");
//read chars using System.in.read()
char ch = (char) System.in.read();
//print value for char
System.out.println("Enter char is : " + ch);
}
}
Output:
Please input a character value:
A
Enter char is : A
Example 3 : Get Char input in Java Using InputStreamReader
In this example we will read char from input using InputStreamReader. We will create object of java.io.Reader and then use read() method of it . read() method of InputStreamReader return int of input characters then we will convert int to character .
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
public class CharInputInJava3 {
public static void main(String[] args) throws IOException {
System.out.println("Please input a character value: ");
Reader reader = new InputStreamReader(System.in);
//return the character as an integer
int charAsInt = reader.read();
char ch = (char) charAsInt;
//print value for char
System.out.println("Enter char is : " + ch);
}
}
Output:
Please input a character value:
A
Enter char is : A
In this tutorial we learned how to take char input in java using Scanner.next().charAt(0) ,System.in.read() and InputStreamReader . We have read character in java using these different methods. You can know how to scan character in java now . You can learn more nice java program for interview .