As static block is used to initialize static data member in dynamic way, I have this code:
class Temp {
static int x;
static {
try {
x = System.in.read();
} catch (Exception e) {
//Do nothing
}
}
}
class Temp1 {
public static void main(String args[]) {
System.out.println(Temp.x);
}
}
class Temp2 {
public static void main(String args[]) {
System.out.println(Temp.x);
}
}
While running Temp1, Temp2 the normal value of x should be what I entered from keyboard, but I got 49 and 50 always no matter whatever I entered from keyboard.
I already see the read() method of inputstream class it should return the same. Why it is returning 49 and 50 in every case?
The direct question you are asking is not really the first thing that you should be informed of here because the very approach you are taking is quite misguided:
System.inis a byte stream) and storing it as anint.mainmethods in them. This makes no sense: nothing will be “done twice” in any sort of meaning with that code.This list is by no means exhaustive, it’s just what I managed to think of right now.
To conclude, you should redesign your code in the first place just to make the basic approach sane, and only then try to make it work.