Search code examples
javaoutputstatic-block

Unexpected output using static block in Java


I am trying to execute this code but its giving me random values everytime:

Output:

Output

Code:

public class Temp  {
    static int x;
    static {
        try {
            x = System.in.read();
        } catch (IOException ex) {
            System.out.println(ex);
        }
    }
}


class TempA {
    public static void main(String[] args) {
        System.out.println(Temp.x);
    }
}

Solution

  • The values aren't random, they're:

    [...] the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read()

    This means if you type a and hit Enter you'll get 97.

    If you're looking for content of what was typed (and not the raw byte value) you'll need to make some changes... The easiest way it to use the Scanner class. Here's how you get a numerical value:

    import java.util.Scanner;
    
    public class Temp  {
        static int x;
        static {
            Scanner sc = new Scanner(System.in);
            x = sc.nextInt();
        }
    }
    
    
    class TempA {
        public static void main(String[] args) {
            System.out.println(Temp.x);
        }
    }
    

    See also System.in.read() method.