• 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

String And instanceof?

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I was under assumption that String is just another object type and instanceof can be used to test if a particular object is of a particular type or descended from that type.
When I try to test if an object is of type String with instanceof operator(haven't found need for this, but still think concept should work) receive compile error as below. In this case t is instance of basic class Ticker which extends component. Source code shown below.
I was expecting this to compile with first two tests to be true and last test to be false, but do not get that far.
>>>
C:\TestTicker2.java:20: inconvertible types
found : Ticker
required: java.lang.String
if (t instanceof String)
^
1 error
<<<
Ticker.java
>>>
import java.awt.*;
class Ticker extends Component
{
int tick;
}
<<<
TestTicker2
>>>
import java.awt.*;
public class TestTicker2
{
public static void main(String args[])
{
Ticker t = new Ticker();
if (t instanceof Ticker)
{
System.out.println("Is a Ticker");
}

if (t instanceof Component)
{
System.out.println("Is a Component");
}

if (t instanceof String)
{
System.out.println("Is a String");
}
}
}
<<<
 
Bartender
Posts: 9626
16
Mac OS X Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Java is strongly typed. The compiler examines everything to make sure the correct types are being used and can tell that since t is a Ticker, it can be a Ticker or a Component, but you could never assign a String to that variable (if you did, you'd get a compile error!). Try declaring t to be an Object, something you could set both a String or a Ticker value to:
Object t = new Ticker();.
 
I wasn't selected to go to mars. This tiny ad got in ahead of me:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic