aspose file tools*
The moose likes Beginning Java and the fly likes Declaration inside an if block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Declaration inside an if block" Watch "Declaration inside an if block" New topic
Author

Declaration inside an if block

Rajat Sharmanaive
Ranch Hand

Joined: Jun 30, 2011
Posts: 41

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.


Rajat Sharma
N Sahni
Ranch Hand

Joined: Jul 07, 2011
Posts: 55

you can go through this topic: http://www.coderanch.com/t/545186/java/java/difference-two-code-snippets


Thanks and Regards,
Nilesh Sahni | nsahni@infocepts.com | www.infocepts.com
Rajat Sharmanaive
Ranch Hand

Joined: Jun 30, 2011
Posts: 41

Thanks Nilesh. That was very helpful. Infact that nailed it.
 
Don't get me started about those stupid light bulbs.
 
subject: Declaration inside an if block