CS 117: Integers versus ints

In class on Friday, we talked about the difference between an object (like an Integer) and a primitive (like an int). One of the differences is about efficiency. If you write
int x = 42;
you only have to store the number 42 itself, in a memory location called x. But for
Integer y = new Integer(42);
you have to create an Integer object containing the number 42 plus a bunch of methods (toString(), equals(), ...), store it in some memory location (say, 17), and you also have to store "go to 17" in a memory location called y.

In this lab, your task is to figure out how much less efficient (in terms of memory usage) the Integer approach is compared to the int approach. Namely, I want you to figure out how much memory is consumed by an int, and how much is consumed by an Integer. Figuring this out will require some detective work on your part!
  1. Create a directory called lab6 to hold your code for this assignment.
  2. Figure out how many int variables you can store in memory before you get an error message about running out of memory. Here's a small class that you might use to get started:
    class Hint { 
       public static void main(String[] args) {
          int size = 5000000; 
          int[] foo = new int[size];
          System.out.println(size + " succeeded");
    
          size = 50000000;
          foo = new int[size];
          System.out.println(size + " succeeded");
       }
    }
    
  3. Figure out how many Integer variables you can store in memory before you get an error message.
  4. Figure out how much of the memory used by the Integer version is used the Integer itself and how much is used the "go to 17" part. (Hint: if you do Integer x = null, then you've created a "go to nowhere" part, but you haven't built the Integer part.)
  5. Figure out how much memory (in bits) is consumed by a single int. You may find Chapter 1 of your book helpful.
  6. Using answers to previous parts, figure out approximately how much space using a single Integer requires. How much more efficient is an int? (Why is your answer only approximate?)
  7. Write up your conclusions and the methods by which you reached them in a file called lab6.txt. Be sure to include answers to questions 2 through 6 above, and reference the code in your lab6 directory to explain what you did and how you did it.

Submit your solutions via hsp by Tuesday, 24 May 2006, at 11:59p.