This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Declaration inside an if block

 
Rajat Sharmanaive
Ranch Hand
Posts: 41
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I am new to both Java and Code Ranch (my question will reveal that in a minute but anyways ).

Assume that class Dog extends class Animal (trust me that much

I am aware that an if block does not require parenthesis if there is only a single statement. Take a look:

Animal a= new Animal();
if(a instanceof Animal)
{
Dog d3 =(Dog)a;
}

Now i know that every single thing about this snippet is downright wrong. I expectantly get a ClassCastException at runtime. What has been grilling me for almost a couple of hours now is this:

Animal a= new Animal();
if(a instanceof Animal)
Dog d3 =(Dog)a;

I just remove the parenthesis pair (seeing that only single statement is there) and have a syntax error. Eclipse basically shows multiple markers all of which disappear as soon as i in put this statement in parenthesis.


Simplified it totally and left the bigger problem (About possible downcasts)

if(true)
int a1=10;
Even this is a compile time error. Which vanishes as soon as i put this simple declaration in parenthesis.
I know there are certain rules regarding declarations inside try blocks. I never knew anything similar in case of simple If blocks. Even if i think along those lines, i do not understand why it becomes alright as soon as i put it into parenthesis.
I know some heavy fundamental clarity is required. Please help and prevent me from believing that i read some pirated books.
 
N Sahni
Ranch Hand
Posts: 55
Java Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can go through this topic: http://www.coderanch.com/t/545186/java/java/difference-two-code-snippets
 
Rajat Sharmanaive
Ranch Hand
Posts: 41
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Nilesh. That was very helpful. Infact that nailed it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic