Int vs Integer


#1

in lessons 7 and 8 (https://www.codecademy.com/en/courses/learn-java/lessons/data-structures/exercises/for-each-loop?action=resume) for loops are discussed. In the initialization I have seen both int and Integer used, though the former was used for the increment format, while Integer was used for the format below. Both seem to work fine.
Is there a difference between the two or is there a best practice?

for (Integer temperature:weeklyTemperatures) {
			System.out.println(temperature);
		}
for (int temperature:weeklyTemperatures) {
			System.out.println(temperature);
		}

#2

int char long boolean etc are primitive types, they are not classes. Values of these types are not objects, they are primitives.

Integer Character Long, Boolean etc are classes that wrap around their respective primitive types.

When you do something like this:

Class MyClass {
    static Integer add(Integer a, Integer b) {
        return a + b;
    }

    public static void main(String[] args) {
        int a = 3;
        int b = 1;
        int c = add(a, b);
    }
}

Then Java will convert back and forth between int and Integer, which isn't so great. Adding two integers is a single cpu instruction, creating objects is.. many. The above will box/unbox a total of 6 times.

When you deal with generics (like an ArrayList) then you'll have to use objects, so you can't have an ArrayList<int>

So try to stick with primitives if doing operations on them, avoid excessive auto-boxing (the add method should only use int)

This is also something you should avoid:

Integer a = 1000;
Integer b = 1000;
System.out.println(a == b);  // true? false?

The compiler will probably use the same Integer object for a and b, so that probably prints true. But two Integers could be equal, but not be the same objects, which is what == tests for.

The above should be:

System.out.println(a.equals(b));

In the code you posted, it really does not matter much. Most of the time there is spent on I/O either way. Write correct code, watch for performance in inner loops, don't worry too much when something else is slower or if it just doesn't happen very many times. The real thing to complain about there is the indentation and spacing!


#3

Thank you, that explains a lot.