-5
Object obj = "1234";
System.out.println(obj instanceof Integer);

What else should I do to check such Object if its an instanceof Integer or Float.

Muhammad Imran Tariq
  • 22,654
  • 47
  • 125
  • 190
  • Because it's false. It's a String. – user207421 Apr 03 '14 at 10:33
  • 1
    Reading your profile, this almost feels like a troll question - you have a masters degree in CS, you're working for IBM on banking and security applications, your major language is Java, but you don't know the difference between an Integer and a String literal? You're too late, April 1st was two days ago... But seriously, you should refresh your knowledge of the basics. [This section](http://docs.oracle.com/javase/tutorial/java/data/index.html) of the official tutorial deals with Strings and numbers, [this one](http://docs.oracle.com/javase/tutorial/java/data/converting.html) with conversions. – l4mpi Apr 03 '14 at 10:45
  • instead of checking instanceof I should parse it. – Muhammad Imran Tariq Apr 03 '14 at 10:50

4 Answers4

4

Well it returns false because obj is not an Integer, it's a reference to a String object.

Object obj = "1234";

try {
    int value = ((Integer) obj);
} catch (ClassCastException e) {
    // failed
}

or

Object obj = "1234";

try {
    int value = Integer.parseInt((String)obj);
} catch (NumberFormatException e) {
    // failed
}
ifloop
  • 8,079
  • 2
  • 26
  • 35
2

Your obj is a String, the one below can return true

Object obj = new Integer(1234);

Or

Object obj = 1234;
betteroutthanin
  • 7,148
  • 8
  • 29
  • 48
  • I get String like "1234" as an argument. So I cannot use Object obj = 1234; – Muhammad Imran Tariq Apr 03 '14 at 10:06
  • 1
    @ImranTariq If you know you have a String, why do you think it is an Integer? – Joe Apr 03 '14 at 10:12
  • There are many possible values @Joe. So it can be String, Integer, Float etc. I and checking types and changing business logic based on it – Muhammad Imran Tariq Apr 03 '14 at 10:15
  • @ImranTariq Well, are they really typed as String, Integer and Float ? Or are they numbers encoded in a string ? "123.2" is a string, just as "Joe" or "53" is. If they are encoded as strings, you need to start parsing the string and guess what kind of type it might be. – nos Apr 03 '14 at 10:26
1

Try this

try {
    int a = Integer.parseInt("1234");
    // No need to check instance of now, if supplied argument is number
    // then parseInt() will pass otherwise you will get exception.
} catch (NumberFormatException e) {
    System.out.println("Supplied argument is not valid number");
}
Gaurav Gupta
  • 4,586
  • 4
  • 39
  • 72
0

Any thing between "" is String. You are checking String against Integer that's why it's giving false.

Try Object obj = 1234;

It will change the primitive type int to Integer by autoboxing.

or

Object obj=new Integer(123);
Deepu--Java
  • 3,742
  • 3
  • 19
  • 30