MMM
MMM

Reputation: 77

Which is better in use between int and Integer to determine the values?

I would like to know when I am checking for integers input, should I use int or Integer for checking?

Below is some mock-up codes:

This one uses int:

public State editState (int stateID, String stateCode) {
    if (stateID == 0) {
        throw new Exception("State id not set.");
    }
    ...
    State s = new State();
    ...

    return s;
}

This one uses Integer:

public State editState (Integer stateID, String stateCode) {
    if (stateID == null) {
        throw new Exception("State id not set.");
    }
    ...
    State s = new State();
    ...

    return s;
}

Which approach is better in use?

Upvotes: 1

Views: 88

Answers (3)

Sunny Gupta
Sunny Gupta

Reputation: 21

Well, in Java an int is a primitive while an Integer is an Object. Meaning, if you made a new Integer:

Integer i = new Integer(6);

You could call some method on i:

String s = i.toString(); //sets s the string representation of i

Whereas with an int:

int i = 6;

You cannot call any methods on it, because it is simply a primitive. So:

String s = i.toString(); //will not work!!!

would produce an error, because int is not an object.

I think if you have not any requirement to use such operation then go with int instead of Integer and you can also avoid a unnecessary Java object creation.

Upvotes: 1

A_P
A_P

Reputation: 21

There is no much difference performance wise or functionality wise. Both would be almost equal. It depends more on how the input is in the method invoking the editState(...) method. If the invoking method has primitive type int or wrapper Integer, corresponding editState(...) is better to use. Also, if the invoking method has the possibility of different numeric types (byte, short etc.) that fits into int, then first one is preferred. Similarly if it has object that can be autoboxed to Integer, then second one is preferred.

Upvotes: 1

Anonymous
Anonymous

Reputation: 67

when you will invoke editState(..,..) and stateId is not set then two cases arise-

1)editState(0,"some code");

2)editState(null,"some code");

It depends upon the criteria you set for the unacceptance of stateID.

If you set criteria for unacceptance as null then you will have to use 'Integer' and if 0 then you can use both 'Integer' and 'int' ...

so it depends upon the criteria you set at the invoking side..

And i think Integer (wrapper class ) is better due to excellent auto boxing ,unboxing features as well as various methods provided to you for manipulations if required...

Upvotes: 2

Related Questions