Any chance of Object auto casting to Integer? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Any chance of Object auto casting to Integer? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am wondering whether the below code should work in any scenario?

Object value = attValue.getValue(); // Returns an Object, might contain an Integer
        if (value instanceof Integer) { 
            if (mAccount.getValue() != value) { // mAccount.getValue() return int
               // Do something here
            }
        }

It works in my Android studio but not in some other’s PC. What is making it work for me?

Answer

Yes, that’s entirely feasible given the way autoboxing is guaranteed to work on small values, and is permitted to work on larger values. For example, this is guaranteed to print true:

Object x = 5;
Object y = 5;
System.out.println(x == y);

This might print true, but isn’t guaranteed to:

Object x = 10000;
Object y = 10000;
System.out.println(x == y);

I would definitely try not to rely on this in code though, partly because while values in the range of -128 to 127 inclusive are guaranteed to be reused (see JLS 5.1.7), the fact that some JVMs may reuse a wider range of values could lead you into a false sense of security about your code.

In your case, we don’t know whether you’re seeing a difference in platforms (also bearing in mind that we’re talking about Android rather than a JVM) or just that when it “worked” the value being boxed was small, and when it “didn’t work” it wasn’t.

We are here to answer your question about Any chance of Object auto casting to Integer? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji