public class Static
{
static
{
int x = 5;
}
static int x,y;
public static void main(String args[])
{
x--; myMethod();
System.out.println(x + y + ++x);
}
public static void myMethod()
{
y = x++ + ++x;
}
}
Could you please somebody help me here why it is displaying out put is 3?
You redeclare
xhere, making it a locally scoped variable (not a class member). This assignment will have no affect whatsoever, regardless of when it is run.Now, you asked about the static block and that’s what I answered. If you are confused about why a value of 3 is outputted even assuming that assignment doesn’t take place, then this becomes a question about the increment operators (
x++and++x).Full explanation
I like Paulo’s explanation quite a bit but let’s just see if we can simplify the code. To start, let’s forget about making
xandya static field (making them local, initialized to the default for a static int: 0) and inlinemyMethod():First we should eliminate complex expressions. We can do that by extracting each sub-expression into a temporary variable in the correct order (expressions are evaluated left-to-right):
Now we can label the value of
x,yand any temporary variables at each step: