Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

What will be the output  RSS feed

 
Rajarsi Ghosh
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I came across the following question:

public class test
{

static int x,y;
static {
int x= 5;
}

public static void main(String args[])
{
x++;
System.out.println("X " + x + " Y "+y );
}
}

The output is:
------------------------------------
X 1 Y 0
------------------------------------

Can anybody explain why X is 1 instead of six and why an compile time error is not thrown when x was declared twice.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you are creating a new, local variable in the static initializer block that hides the member variable named x. You set the local variable to 5, but the local variable disappears at the end of the static block.

Local variables can hide member variables. You are not declaring the variable x in the same scope twice, so you don't get an error about a double variable declaration.

The member variable x is by default initialized to 0, and with the statement x++, x becomes 1.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!