Jack Ng

Essay

Learning Java, Part 5: Arrays, Strings and Bitwise Operators

Study notes on one- and two-dimensional arrays, irregular arrays, array references and length, the String class and its immutability, == versus equals, StringBuilder, command-line arguments, bitwise and shift operators, and the ternary operator. Written entirely by an AI model.

Python’s list grows, shrinks and holds anything. Java’s array has a fixed length and one element type. The growable version, ArrayList, comes in Part 13. This part also covers String, where the most famous Java bug lives.

One-dimensional arrays

import java.util.Arrays;

public class Orders {
    public static void main(String[] args) {
        int[] cups = new int[4];          // four ints, all 0
        cups[0] = 3;
        cups[3] = 1;
        System.out.println(Arrays.toString(cups));

        String[] teas = {"green", "oolong", "black"};   // initialiser
        System.out.println(teas.length + " teas, last is " + teas[teas.length - 1]);

        Arrays.sort(teas);
        System.out.println(Arrays.toString(teas));
    }
}
[3, 0, 0, 1]
3 teas, last is black
[black, green, oolong]
  • new int[4] makes room for four elements set to the type’s default (0, false or null).
  • Indexes run from 0 to length - 1. There are no negative indexes: teas[-1] throws ArrayIndexOutOfBoundsException, as does teas[3].
  • length is a field, not a method: teas.length, no brackets. (For a String it is a method, s.length(). Exams like this inconsistency.)
  • Printing an array directly gives something like [I@1b6d3586. Use Arrays.toString.

Sorting by hand

The book’s first “Try This” is a bubble sort. Writing one is a standard exam task, so know it:

import java.util.Arrays;

public class Bubble {
    public static void main(String[] args) {
        int[] a = {5, 1, 4, 2};
        for (int pass = 1; pass < a.length; pass++) {
            for (int i = 0; i < a.length - pass; i++) {
                if (a[i] > a[i + 1]) {
                    int tmp = a[i];         // Java has no a, b = b, a
                    a[i] = a[i + 1];
                    a[i + 1] = tmp;
                }
            }
        }
        System.out.println(Arrays.toString(a));
    }
}
[1, 2, 4, 5]

Multidimensional arrays

A two-dimensional array is an array of arrays. Rows need not be the same length, which gives irregular (or jagged) arrays:

public class Shelves {
    public static void main(String[] args) {
        int[][] grid = new int[2][3];
        grid[1][2] = 9;

        int[][] jagged = new int[3][];
        jagged[0] = new int[1];
        jagged[1] = new int[3];
        jagged[2] = new int[2];

        int[][] table = { {1, 2}, {3, 4}, {5, 6} };
        int total = 0;
        for (int[] row : table) {
            for (int v : row) total += v;
        }
        System.out.println(grid[1][2] + " " + jagged[1].length + " " + total);
    }
}
9 3 21

Only the first dimension must be given to new. table.length is the number of rows; table[0].length is the length of row 0.

Array variables are references

An array is an object. Assigning one array variable to another copies the reference, so both names see the same elements:

import java.util.Arrays;

public class Shared {
    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        int[] b = a;
        b[0] = 99;
        int[] c = Arrays.copyOf(a, a.length);   // a real copy
        c[1] = 0;
        System.out.println(Arrays.toString(a) + " " + Arrays.toString(c));
        System.out.println(a == b);
        System.out.println(Arrays.equals(a, c));
    }
}
[99, 2, 3] [99, 0, 3]
true
false

Arrays.equals compares contents; == compares references.

Strings

String is a class, but the language gives it special treatment: literals in double quotes, and + for joining. Common methods:

Method Result for s = "Jasmine tea"
s.length() 11
s.charAt(0) 'J'
s.indexOf("tea") 8 (−1 if absent)
s.substring(0, 7) "Jasmine" (end excluded, like a slice)
s.toUpperCase() "JASMINE TEA"
s.contains("min") true
s.split(" ") {"Jasmine", "tea"}
s.trim(), s.strip() remove surrounding spaces
s.compareTo("Kava") negative: "J" sorts first

Strings are immutable

No method changes a string. toUpperCase() returns a new one, so s.toUpperCase(); on its own does nothing useful; write s = s.toUpperCase();.

== versus equals

This is the bug every Java course warns about:

public class Equality {
    public static void main(String[] args) {
        String a = "tea";
        String b = "tea";
        String c = new String("tea");
        System.out.println(a == b);          // same literal, shared object
        System.out.println(a == c);          // different objects
        System.out.println(a.equals(c));     // same characters
        System.out.println(a.equalsIgnoreCase("TEA"));
    }
}
true
false
true
true

== asks whether two references point at the same object. Identical literals happen to share one object (they are “interned”), which is why a == b can look like it works and then fail on strings read from input. Always compare string contents with equals.

Building strings in a loop

Because strings are immutable, s += x in a loop creates a new string every time. StringBuilder is the mutable alternative:

public class Builder {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 5; i++) {
            sb.append(i);
            if (i < 5) sb.append(", ");
        }
        sb.reverse();
        System.out.println(sb.toString());
        System.out.println(String.join("-", "a", "b", "c"));
    }
}
5 ,4 ,3 ,2 ,1
a-b-c

switch on a string compares with equals, so it is safe (Part 3).

Command-line arguments

main receives the words typed after the class name:

public class Greet {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("usage: java Greet NAME...");
            return;
        }
        for (String name : args) System.out.println("Hello, " + name);
    }
}
usage: java Greet NAME...

java Greet Mei Omar prints two greetings. Arguments are always strings; convert with Integer.parseInt or Double.parseDouble, which throw NumberFormatException on bad input.

Bitwise operators

These work on the individual bits of integer values:

Operator Meaning 12 op 10 (1100, 1010)
& AND 8 (1000)
| OR 14 (1110)
^ XOR 6 (0110)
~ NOT (one operand) ~12 is -13
<< shift left 12 << 1 is 24
>> shift right, keep sign -16 >> 2 is -4
>>> shift right, fill with 0 -16 >>> 28 is 15
public class Flags {
    public static void main(String[] args) {
        final int MILK = 1, SUGAR = 2, ICE = 4;   // one bit each
        int order = MILK | ICE;
        System.out.println((order & SUGAR) != 0);
        System.out.println((order & ICE) != 0);
        order ^= ICE;                                // toggle ice off
        System.out.println(order + " " + Integer.toBinaryString(12 ^ 10));
    }
}
false
true
1 110

Shifting left by one doubles a number; shifting right by one halves it, rounding down. The book’s ShowBits exercise prints every bit of a value by testing each one with & and a shifted mask.

The ternary operator

condition ? valueIfTrue : valueIfFalse is an expression, like Python’s a if cond else b but in a different order:

public class Ternary {
    public static void main(String[] args) {
        int cups = 1;
        System.out.println(cups + (cups == 1 ? " cup" : " cups"));
        int a = -5;
        System.out.println(a < 0 ? -a : a);
    }
}
1 cup
5

Exam-style checks

  • Why is a == b the wrong way to compare two strings, and when does it happen to give true?
  • Write a loop that finds the largest value in an int[]. What should it do for an empty array?
  • Draw the memory for int[][] j = new int[2][]; j[0] = new int[3];.
  • What is the difference between array.length and string.length()?
  • What do 6 & 3, 6 | 3, 6 ^ 3 and 6 << 2 evaluate to?

Where to practise

Schildt’s Chapter 5 builds a queue class backed by an array; Part 6 develops it further, so it is worth writing. Then write a method that reverses a string without StringBuilder.reverse, one that counts the vowels in a string, and one that transposes a 2D array.