How can I check if a sequence is alternating?
It's not correct for short sequences with less than 3 items.
The method incorrectly returns true for these example sequences:


empty sequence
singleton list (one item)
sequence with two items that are equal


For the first 2 cases you might even want to throw IllegalArgumentException as arguably it doesn't make much sense to test for alternation in lists with 0 or 1 item, but I think returning false is reasonable.

You can do this by adding these conditions at the start of the method:

    if (sequence.length &lt; 2) {
        return false;
    }
    if (sequence.length == 2) {
        return sequence[0] != sequence[1];
    }


But actually I would simplify the body of the for loop like this:

    if (sequence.length &lt; 2) {
        return false;
    }
    int prevCompare = Integer.compare(sequence[0], sequence[1]);
    if (prevCompare == 0) {
        return false;
    }
    for (int i = 1; i &lt; sequence.length - 1; ++i) {
        int compare = Integer.compare(sequence[i], sequence[i + 1]);
        if (prevCompare != -compare) {
            return false;
        }
        prevCompare = compare;
    }
    return true;


To verify the implementation I recommend adding some unit tests, for example:

@Test
public void testEmptyList_Is_NotAlternating() {
    assertFalse(alternating(new int[0]));
}

@Test
public void testSingletonList_Is_NotAlternating() {
    assertFalse(alternating(new int[]{1}));
}

@Test
public void test2Items_Increasing_Is_Alternating() {
    assertTrue(alternating(new int[]{1, 2}));
}

@Test
public void test2Items_Decreasing_Is_Alternating() {
    assertTrue(alternating(new int[]{3, 2}));
}

@Test
public void test2Items_Same_Is_NotAlternating() {
    assertFalse(alternating(new int[]{3, 3}));
}

@Test
public void test3Items_Same_Is_NotAlternating() {
    assertFalse(alternating(new int[]{3, 3, 3}));
}

@Test
public void test4Items_Same_Is_NotAlternating() {
    assertFalse(alternating(new int[]{3, 3, 3, 3}));
}

@Test
public void test3Items_Increasing_Is_NotAlternating() {
    assertFalse(alternating(new int[]{3, 4, 5}));
}

@Test
public void test4Items_Increasing_Is_NotAlternating() {
    assertFalse(alternating(new int[]{3, 4, 5, 6}));
}

@Test
public void test3Items_Decreasing_Is_NotAlternating() {
    assertFalse(alternating(new int[]{43, 34, 25}));
}

@Test
public void test4Items_Decreasing_Is_NotAlternating() {
    assertFalse(alternating(new int[]{43, 34, 25, 16}));
}

@Test
public void test4Items_AlternatingThenMonotonic_Is_NotAlternating() {
    assertFalse(alternating(new int[]{43, 34, 35, 16, 16, 16}));
}

@Test
public void test4Items_Alternating_Is_Alternating() {
    assertTrue(alternating(new int[]{43, 34, 35, 16}));
}