• Arrays

    Multiple values of common type.

    Loop style handling.

final String
      karen = "Karen Smith",
      john = "John Duncan",
      paul = "Paul Jacobs",
      suzanne = "Suzanne Enders",
      peter = "Peter Phillips";  // 10 more to come ...

    System.out.println(karen);
    System.out.println(john);
...
  • Generate Comma separated list:

    Karen Smith, John Duncan, Paul Jacobs, Suzanne Enders, Peter Phillips
  • Generate HTML list emphasizing family names:

    <ul>
      <li>Karen <emph>Smith</emph></li>
      <li>John <emph>Duncan</emph></li>
      <li>Paul <emph>Jacobs</emph></li>
      <li>Suzanne <emph>Enders</emph></li>
      <li>Peter <emph>Phillips</emph></li>
    </ul>
final int[] primes  = new int[5]; 

primes[0] = 2; 
primes[1] = 3;
primes[2] = 5;
primes[3] = 7;
primes[4] = 11;
  1. Assignment to final variable?
for (int i = 0; i < 5; i++) {
  System.out.println("At index " + i + ": value == " + primes[i]);
}

Result:

At index 0: value == 2
At index 1: value == 3
At index 2: value == 5
At index 3: value == 7
At index 4: value == 11
for (int i = 0; i < 6; i++) {
  System.out.println("At index " + i + ": value == " + primes[i]);
}
Result:
At index 0: value == 2
At index 1: value == 3
At index 2: value == 5
At index 3: value == 7
At index 4: value == 11
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
  at qq.arrayex.Motivate.main(Motivate.java:27)
System.out.println("primes.length == " + primes.length);
for (int i = 0; i < primes.length; i++) {
  System.out.println("At index " + i + ": value == " + primes[i]);
}
Result:
primes.length == 5
At index 0: value == 2
At index 1: value == 3
At index 2: value == 5
At index 3: value == 7
At index 4: value == 11
for (final int p: primes) {
  System.out.println("value == " + p);
}
Result:
value == 2
value == 3
value == 5
value == 7
value == 11
final int[] primes = new int[5]; // Last index is 4 rather than 5!

primes[0] = 2;
primes[1] = 3;
primes[2] = 5;
primes[3] = 7;
primes[4] = 11;
primes[5] = 13; // Excessing array limit
Result:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
  at qq.arrayex.Motivate.main(Motivate.java:25)

Combining array allocation and value assignment:

final int[]
  primes = {2, 3, 5, 7, 11};
final int[] primes = new int[5];
primes[0] = 2;
primes[1] = 3;
primes[2] = 5;
primes[3] = 7;
primes[4] = 11;

Combining array allocation and value assignment:

public class Rectangle {
    private int width, height;
    private boolean hasSolidBorder;
    public Rectangle(int width, int height,
                   boolean hasSolidBorder) {
        this.width = width;
        this.height = height;
        this.hasSolidBorder = hasSolidBorder;
    }
}
final Rectangle[] rectList = new Rectangle[] {
  new Rectangle(2, 5, true),
  new Rectangle(4, 1, false)
};
  1. Converting string arrays to HTML.
  2. Route navigation
  3. Examinations and mark frequencies
  4. Pangram checker
  • Series of objects having identical type.

  • Array consists of array elements.

  • Element access by index value.

  • Holding either primitive types or object references (Class instance or array).

  • Contiguous storage in memory.

  • Arbitrary array dimensions by virtue of nesting: One-dimensional, two-dimensional etc.

  1. type[] arrayName; // preferred
  2. type arrayName[];
...println("        String: " + "".getClass().getTypeName());
...println("         int[]: " + new int[]{}.getClass().getTypeName());
...println("      double[]: " + new double[]{}.getClass().getTypeName());
...println("     boolean[]: " + new boolean[]{}.getClass().getTypeName());
...println("StringBuffer[]: " + new StringBuffer[]{}.getClass().getTypeName());
        String: java.lang.String
         int[]: int[]
      double[]: double[]
     boolean[]: boolean[]
      String[]: java.lang.String[]
StringBuffer[]: java.lang.StringBuffer[]
Image layer 1
Image layer 2
Image layer 3
Image layer 4
Image layer 5
public static void main(String[] args) {
  final int [] lectures = new int[3]; // Three lectures
  fill(lectures, 25); // Default lecture having 25 participants
  System.out.println("Second lecture has got " + lectures[1] +
          " participants");
}
/**
  * Initialize array with default value.
  *
  * @param values Array to be initialized.
  * @param common New value for all array elements.
  */
static void fill(final int[] values, final int common) {
  for (int i = 0; i < values.length; i++) {
    values[i] = common;
  }
}
Second lecture has got 25 participants
Image layer 1
Image layer 2
Image layer 3
Image layer 4
Image layer 5
Image layer 6
Image layer 7
Image layer 8
Image layer 9
Image layer 10
Image layer 11
Image layer 12
// Value type
final boolean values[] = new boolean[]{true, true, false, true};

// Reference type
final String shapes[] = new String[]{"Triangle", "Circle"};

Same result:

final boolean values[] = {true, true, false, true};

final String shapes[] = {"Triangle", "Circle"};
  1. Reconsidering System.out.format().
  • Arrays
    • java.util.Arrays helpers

      Sorting and searching arrays.

      Fill in values.

      Compare array contents.

final String[] names = {"Eve", "Aaron", "Paul", "Mandy"};

System.out.println("     toString: " + Arrays.toString(names));

Arrays.sort(names);

System.out.println("sort|toString: " + Arrays.toString(names));

Result:

     toString: [Eve, Aaron, Paul, Mandy]
sort|toString: [Aaron, Eve, Mandy, Paul]
final String[] names = {"Aaron", "Eve", "Mandy",  "Paul"};

// Precondition: Array must be ordered!
...println("sort|find(Mand): " + Arrays.binarySearch(names, "Mand"));
...println("sort|find(Mandy): " + Arrays.binarySearch(names, "Mandy"));
...println("sort|find(Mandyer): " + Arrays.binarySearch(names, "Mandyer"));

Result:

sort|find(Mand): -3
sort|find(Mandy): 2
sort|find(Mandyer): -4
  1. Understanding search results
final String[] names = 
  {"Eve", "Aaron", "Paul", "Mandy"};

System.out.println("toString: " +
   Arrays.toString(names));

Arrays.fill(names, "N.N");

System.out.println("toString: " + 
    Arrays.toString(names));
toString: [Eve, Aaron, Paul, Mandy]
toString: [N.N, N.N, N.N, N.N]
final String[] names = {"Eve", "Aaron", "Paul", "Mandy"};

final String[] lastTwoNames = Arrays.copyOfRange(names, 2, 6);

System.out.println("toString: " + Arrays.toString(lastTwoNames));

Result:

toString: [Paul, Mandy, null, null]
final String[]
  l1 = {new String("Eve"), new String("Aaron"), 
        new String("Paul"), new String("Mandy")},

  l2 = {new String("Eve"), new String("Aaron"), 
        new String("Paul"), new String("Mandy")},

  l3 = {new String("Eve"), new String("Aaron"), 
        new String("Paul"), new String("Mobile")};

System.out.println("l1.equals(l2):" + Arrays.equals(l1, l2));
System.out.println("l1.equals(l3):" + Arrays.equals(l1, l3));

Result:

l1.equals(l2):true
l1.equals(l3):false
  • Arrays
    • ➟ Extending arrays

      Dealing with fixed size.

final String[] member = {"Eve", "John", "Peter", "Jill"};

final String newCourseMember = "Ernest";

member.length = 5; // Error: Size unchangeable

member[4] =  newCourseMember;
public static void main(String[] args) {
  String[] member = {"Eve", "John", "Peter", "Jill"};
  final String newMember = "Ernest";
  member = append(member, newMember);
}
static String[] append (final String[] values, final String newValue) {
  final String[] copy =  new String[values.length + 1];
  for (int i = 0; i < values.length; i++) { 
    copy[i] = values[i]; 
  }
  copy[copy.length - 1] = newValue; 
  return copy;
}
final String[] member = {"Eve", "John", "Peter", "Jill"};
System.out.println("Original array: " + Arrays.toString(member));
final String newMember = "Ernest";
member = append(member, newMember);
System.out.println("Extended array: " + Arrays.toString(member));
Original array: [Eve, John, Peter, Jill]
Extended array: [Eve, John, Peter, Jill, Ernest]
public static void main(String[] args) {
    final int [] start = {1,7,-4},
    added = append(start, 77);
    System.out.println("added: " + Arrays.toString(added));
  }
static public int[] append(final int[] values, final int newValue) {
  final int[] result = Arrays.copyOf(values, values.length + 1);
  result[values.length] = newValue;
  return result;}

Result:

added: [1, 7, -4, 77]
  1. Implementing append directly
  2. Purge duplicates
  3. A container of fixed capacity holding integer values
  4. Allow for variable capacity holding integer values
  • Arrays
    • ➟ Understanding static public int main(String[] args)

      main(...) and its array argument.

      Implementing parameter passing.

package myapp;
public class Cmd {
  public static void main(String[] args) {
    for (int i = 0; i < args.length; i++) {
      System.out.println("Parameter " + (i + 1) + ": " + args[i]);
    }
  }
}
java myapp.Cmd 21 334 -13
Parameter 1: 21
Parameter 2: 334
Parameter 3: -13
 run configuration

Entry class myapp.Cmd containing ... main(String[] args).

Parameters 21, 334 and -13 being passed to String[] args.

 run configuration
<artifactId>maven-shade-plugin</artifactId>
...
<transformer ...>
  <manifestEntries>
    <Main-Class>myapp.Cmd</Main-Class>
  </manifestEntries>...
unzip ww-1.0-SNAPSHOT.jar
cat  tmp/META-INF/MANIFEST.MF
...
Created-By: Apache Maven 3.5.0
Build-Jdk: 1.8.0_151
Main-Class: myapp.Cmd
mvn package ...
java -jar target/ww-1.0-SNAPSHOT.jar 21 334 -13
Parameter 1: 21
Parameter 2: 334
Parameter 3: -13
  1. Reading console input
  2. Prettifying output representation
  • Arrays
    • ➟ Multi-dimensional arrays

      Multiple dimensions by nesting of arrays.

final int[][] matrix = new int[2][3];

for (int row = 0; row < 2; row++) {
  for (int col = 0; col < 3; col++) {
    matrix[row][col] = col + row;
  }
}
for (int row = 0; row < 2; row++) {
  System.out.println(Arrays.toString(matrix[row]));
}
final int[][] matrix = new int[2][]; // Array containing two int arrays
matrix[0] = new int[3];              // first int array
matrix[1] = new int[3];              // second int array
Image layer 1
Image layer 2
Image layer 3
Image layer 4
Image layer 5
Image layer 6
Image layer 7
Image layer 8
Image layer 9
Image layer 10
Image layer 11
Image layer 12
Image layer 13
Image layer 14
Image layer 15
Image layer 16
Image layer 17
Image layer 18
Image layer 19
Image layer 20
Image layer 21
  1. 2-dimensional arrays and .length
final int[][] matrix = new int[][] {
  {0, 1, 2},
  {1, 2, 3}
};
final String[][] groups = new String[][] {
  {"Jill", "Tom"},
  {"Jane", "Smith", "Joe"},
  {"Jeff"}
};

for (int row = 0; row < groups.length; row++) {
  System.out.println(Arrays.toString(groups[row]));
}
[Jill, Tom]
[Jane, Smith, Joe]
[Jeff]
  1. External array and string exercises
  2. Tic-tac-toe using a two-dimensional array
  3. Changing the game's internal representation
  4. Tic-tac-toe, Computer vs. human
  5. Adding support to retrieve statistical data.
  6. Testing an implementation
  7. Improving prime number calculation performance
  8. Calculating the median
  9. A simple character based plotting application