This week's book giveaway is in the Cloud/Virtualization forum.
We're giving away four copies of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds and have James Denton on-line!
See this thread for details.
Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

instanceof operator  RSS feed

 
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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
  • 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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!