-2

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

antonpug
  • 12,894
  • 27
  • 80
  • 122

4 Answers4

8
if(object instanceof String)
{
    // Do Stuff
}
Baz
  • 35,635
  • 11
  • 69
  • 91
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,154
  • 3
  • 20
  • 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
  • 9,883
  • 26
  • 96
  • 199
1
   if( obj instanceof String ) {}

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

kosa
  • 64,776
  • 13
  • 121
  • 163