Q:

System.in.read(); comparing

In my class we are starting to learn java, we were tasked to explain why this code:
import java.io.IOEXception;

 class Inputif {
    public static void main(String args[]) throws java.io.IOException {

         char ch, ch2;

         System.out.print("Hit a key and press Enter: ");

         ch = (char) System.in.read();

         System.out.println("Hit a second key and press Enter: ");

         ch2 = (char) System.in.read();

         if (ch == ch2) System.out.println("Same"); else System.out.println("different"); 
   }
}

outputs this: 
output
in this screenshot i just started the program and typed "a" and then hit enter.
When I run the program it asks me to enter the first char, then it should ask me to enter the second one, but it skips that and prints out the "different" end. I don't know why.
The code should compare the two chars that the user inputs and if they are the same it should print "Same" else it should say "different".
Thanks for any answers!

A:

I made a few changes to your program to  give you some insigth into what is happening: 
 public static void main(String args[]) throws java.io.IOException {

    char ch, ch2;

    System.out.print("Hit a key and press Enter: ");

    ch = (char) System.in.read();

    System.out.println("Hit a second key and press Enter: ");

    ch2 = (char) System.in.read();
    int x1=ch;
    int x2 = ch2;
    System.out.println("x1="+x1+" | x2="+x2);
    if (ch == ch2) System.out.println("Same"); else System.out.println("different");
}

Run the above program two times :
 - type "a" and hit enter.
 - hit enter twice
Explication :
System.in is an instance Of InputStream and the read  method  of an InputStream https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html that "Reads the next byte of data from the input stream".
The problem is that when you re hitting enter you are adding an extra byte to the input stream and ALWAYS ch2 will store it.
 *Note : x1, x2 will display the ASCII codes of the chars you  hit.

