• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Declaration inside an if block

 
Ranch Hand
Posts: 41
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 55
Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you can go through this topic: https://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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Nilesh. That was very helpful. Infact that nailed it.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic