JetBrains Academy: Arrays as parameters - Kamil-Jankowski/Learning-JAVA GitHub Wiki

JetBrains Academy: Arrays as parameters

Adding values:

Write a method named addValueByIndex.

The method should take an array of longs and adds a value to the specified element by its index.

Here are description of the parameters:

1. an array of longs; 2. the index of an element (int); 3. a value for adding (long).

The method must return nothing.

private static void addValueByIndex(long[] array, int index, long add){
    array[index] += add;
}

Inverse boolean flags:

Write a body and a parameter of the method inverseFlags. The method must take an array of booleans and negates each of them. Do not make a copy of the parameter, change elements of a passed array.

public static void inverseFlags(boolean[] status) {
    for (int i = 0; i < status.length; i++){
        status[i] = !status[i];
    }
}

Get first and last elements:

Write a method named getFirstAndLast. The method should take an array of ints and return a new array of ints. The returned array must contain two elements - the first and the last elements of the input array.

It's guaranteed, the input array always has at least one element.

public static int[] getFirstAndLast(int[] input){
    int[] result = new int[2];
    result[0] = input[0];
    result[1] = input[input.length-1];
    return result;
}