Sunday, November 25, 2012

I Will be Out on Monday

Due to a death in my family, I will be out on Monday but will return to school first thing on Tuesday morning. All your assignments that were previously due Monday (the 5 free-response questions and all the ArrayList problems on practice-it) are now due on Tuesday instead of Monday.

Mr. Sarkar

Tuesday, November 20, 2012

ArrayList Problems Now Due after Thanksgiving

Most of you are struggling with the ArrayList problems so I have moved the due date to after Thanksgiving break. Remember that in addition to these problems you also need to do three FRQ problems from the 2009 exam (this is the Juno assignment 99.23) and any two other FRQ's from previous exams. These are due after the break as well.

Sunday, November 18, 2012

Initialization of an ArrayList

When we declare and define a traditional array like this:

int [] x = new int [5];

The compiler creates an array of 5 integers and initializes them all to zero (which is the default initialization for integers).

But when we declare and define an ArrayList like this:

ArrayList<Integer> y = new ArrayList<Integer>(5);

Although the compiler sets aside the memory to hold 5 Integers, no actual Integers are created. Furthermore, not even pointers for these Integers are created (not even null pointers). Thus, if we try to print one of the elements, such as the first element in this ArrayList:

System.out.println(y.get(0));

The code will compile but a run time error of "ArrayIndexOutOfBounds" will be produced. That is because the ArrayList currently has a size of 0 (not 5) because no elements have been yet loaded into it.

Hopefully, this is clear.

Mr. Sarkar

Thursday, November 15, 2012

Using For-Each Loops with Strings

Someone in class today asked if it was possible to use for-each loops in java with Strings. The answer is "yes," and "no." You can use the for-each loop to parse an array of Strings but you cannot use it to parse as single String. Here is an example of a legal use of a for-each loop for a String array:

String array[] = {"Hi", "There", "My", "Son"};
for(String x : array)
     System.out.print(x);


The above example will print:

HiThereMySon

Mr. Sarkar

Wednesday, November 14, 2012

Where the for-each is appropriate


Although the enhanced for loop can make code much clearer, it can't be used in some common situations.

  • Only access. Elements can not be assigned to, eg, not to increment each element in a collection.
  • Only single structure. It's not possible to traverse two structures at once, eg, to compare two arrays.
  • Only single element. Use only for single element access, eg, not to compare successive elements.
  • Only forward. It's possible to iterate only forward by single steps.
  • At least Java 5. Don't use it if you need compatibility with versions before Java 5.