Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

instanceof operator

 
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the following code:

Public class AA{
static String s;
public static void main(String args[]){
AA a = new AA();
if (s instanceof AA){
System.out.println("true String"); }

Here the author says that s is not an instance of String because it's not initialized. Why so?? Can anybody explain it to me...


Thanks
Swapnil
 
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi...

I don't know wat author is trying to explain.

Wat my logic says dat instanceof operator is always checked at compilation time and wat compiler will check is the reference tpe of s. If its of type AA or super class of AA (e.g. java.lang.Object), then compiler is HAPPY.

otherwise compiler will give error--->>> inconvertible types.

As per above, ur code will give compilation error inconvertible types in if condition.

regards

Naseem Khan
 
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The author is correct.
s instanceof AA in your code means it is checked whether the object refered
by s is an instance of AA class.
And since you have not initialised s it will be set to null.
so s instanceof String will check whether null is instance of string, which is obviously not.

Regards,
joshua
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
15.20.2 Type Comparison Operator instanceof

No matter "s" is initialized or not.A compile-time error will occurs.
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic