-2

How can I check if an object is of type string?

2
  • 2
    obj instanceof String? Commented Jul 20, 2012 at 16:17
  • 1
    The better question is: why are you designing code that needs to check? That's usually a bad sign. Polymorphism should be the thing. Commented Jul 20, 2012 at 17:11

4 Answers 4

9
if(object instanceof String)
{
    // Do Stuff
}
Sign up to request clarification or add additional context in comments.

Comments

3

By using the instanceof operator in java:

if(object instanceof String){
    System.out.println("String object");
    // continue your code here
}
else{
     System.out.println("it is not a String");
}

Comments

3

Like this:

Integer myInt = 3;
if (myInt instanceof String)
    System.out.println("It's a String!");
else
    System.out.println("Not a String :(");

2 Comments

This is a bad example, as the String is already declared as String, and not as Object (or other super class of String).
I thought more of declaring an Object, because declaring an Integer or a String makes this a compile time decision. Only for a super class of String (which neither Integer nor String are) this is a runtime decision. But anyway, I removed my down vote.
1
   if( obj instanceof String ) {}

is a way to check for the object you got is of String

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.