aspose file tools*
The moose likes Beginning Java and the fly likes String And instanceof? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String And instanceof?" Watch "String And instanceof?" New topic
Author

String And instanceof?

Craig Oliver
Greenhorn

Joined: Aug 25, 2003
Posts: 21
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");
}
}
}
<<<
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8718
    
    6

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();.


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String And instanceof?
 
Similar Threads
instanceof example not compiling
Kathy/Bert book ch 3 self test q 2
instanceof Problem
Q about instanceof
1.4....K$B question