Block B

Entry Access Done via the [] opearator. This gives access to individual entries.


jshell> int[] x = new int[20];
x ==> int[20] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }

jshell> x[0] = 3
$2 ==> 3

jshell> x
x ==> int[20] { 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }

Arrays are really second-class objects. They don't have a decent toString() method.


jshell> System.out.println(x)
[I@34a245ab

Here we make an array of object type using a comma-separated list.


jshell> String[] names = {"abraham", "bartholamew", "charles"};
names ==> String[3] { "abraham", "bartholamew", "charles" }

jshell> names.length
$6 ==> 3

jshell> names.getClass()
$7 ==> class [Ljava.lang.String;

No appening. Array size is fixed.


jshell> names.append("David")
|  Error:
|  cannot find symbol
|    symbol:   method append(java.lang.String)
|  names.append("David")
|  ^----------^

args Matey, I'm a pirate! args is an array parameter to main. It captures command-line arguments.

for Works the same as in a list.

for(Type item: array)
{
}

The Ovipositor This zeroe sout primitive arrays and booleans are initialized to false.

The dreaded NullPointerException This occurs when you try to call a method on the graveyard object null. This object is like Python's None Arrays of object type are filled with this value by default.


jshell> String[] empty = new String[5];
empty ==> String[5] { null, null, null, null, null }

Steel yourself for punishment.


jshell> empty[2].toUpperCase()
|  Exception java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "REPL.$JShell$22.empty[2]" is null
|        at (#10:1)

The static service class Arrays

Arrays.toString:  pretty-prints an array.
Arrays.binarySearch: fast search of a sorted array
Arrays.sort: sorts an array in-place
Arrays.fill: fills an arraay
Arrays.copyOfRange:  subssets a subarray.