Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

error?

 
Ankur kothari
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


above code compiles wheres this doesnt

 
Sonali Sehgal
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


In this code during the execution of the program first the compiler declares and intializes the variable and then after that the instance block executes.




In the above code the variable i is not even declared whether it is an integer ,float or what it is whereas on the first code we are declaring it.Hence it will give your a compile time error of identifier expected.
 
Ankur kothari
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
then why is there an error in this?
class Forward
{
{
System.out.println(i);
i = 10;

}

int i = 5;


}

isnt i already declared when it reaches system.out?
 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ankur, please UseAMeaningfulSubjectLine for your topics.

Do you think this will compile

You can't have anything other than method declarations (including constructors), variable/constant declaration and static and instance initializer blocks in your class body...
 
Sonali Sehgal
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


This System.out gives you an error because it is not the correct forward referencing to correct this you have to use this.i so it specifically points to the reference variable and gives the output.

Well, in the case of forward referencing, we're not trying to read from i, we're assigning a value to it. Therefore, there's no "dangerous" operation occurring here and the compiler allows it. For more information check this link of java ranch I hope it will make it more clear...



Webpage for Forward Referencing
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use java decompiler to get the idea how forward ref is resolved by compile, what compiler is doing internally. How code are placed in the last and executed.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic