• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem with Variable decleration and assigning the values.  RSS feed

 
sandy chauhan
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Twisty{

{ index=1;}

int index;

public static void main(String[] args)
{
new Twisty.go();
}

void go()
{
int [][] dd={{9,8,7},{6,5,4},{3,2,1,0}};
System.out.pritnln(dd[index++][index++]);
}
}



I have confusion with the value of index, this program takes value of index as one but when we declare index we have not provided any value to it
is it taking its value from index(which have been provided value 1 in a local code block)???
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the future, please UseCodeTags(⇐click) when posting code, so that it will be readable.

sandy chauhan wrote:
I have confusion with the value of index, this program takes value of index as one but when we declare index we have not provided any value to it
is it taking its value from index(which have been provided value 1 in a local code block)???


That code doesn't even compile. If you're going to ask questions about how code behaves at runtime, you should at least post code that compiles.

If we fix the compiler errors in the above, the code produces output of 4.

As for the 1, it is not a "local code block". There is no such thing. It is an instance initializer. It is executed just before the constructor when an object is created. So we create a new Twisty, the instance initializer sets index to 1, and we print out index[1][2], which is 4.
 
sandy chauhan
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the valuable answer can you please provide me some more information about instance initilizer???
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sandy chauhan wrote:Thanks for the valuable answer can you please provide me some more information about instance initilizer???


The main thing you need to know is what I already said: It runs before the constructor every time you create a new object.

For more details, see the relevant section of the JLS or google for java instance initializer.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!