jQuery in Action, 2nd edition*
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Declaration inside an if block" Watch "Declaration inside an if block" New topic

Declaration inside an if block

Rajat Sharmanaive
Ranch Hand

Joined: Jun 30, 2011
Posts: 41


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)

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.
I agree. Here's the link: http://aspose.com/file-tools
subject: Declaration inside an if block
Similar Threads
Sun Cirtification
Confused with instanceof, please help
Upcasting.....Its confusing
instanceof doubt...
generic question