-2

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

antonpug
  • 13,724
  • 28
  • 88
  • 129

4 Answers4

9
if(object instanceof String)
{
    // Do Stuff
}
Baz
  • 36,440
  • 11
  • 68
  • 94
3

Like this:

Integer myInt = 3;
if (myInt instanceof String)
    System.out.println("It's a String!");
else
    System.out.println("Not a String :(");
jrad
  • 3,172
  • 3
  • 22
  • 24
  • This is a bad example, as the String is already declared as String, and not as Object (or other super class of String). – Bananeweizen Jul 21 '12 at 06:15
  • 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. – Bananeweizen Jul 21 '12 at 15:10
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");
}
cybertextron
  • 10,547
  • 28
  • 104
  • 208
1
   if( obj instanceof String ) {}

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

kosa
  • 65,990
  • 13
  • 130
  • 167