Question

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.

Était-ce utile?

La solution

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
}

Autres conseils

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

Object obj = new Integer(1234);

Or

Object obj = 1234;

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");
}

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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top