While I was practicing Java problems on CodingBat I came across following problem statement.

**Problem**

Given an integer array of any length, return a new array of its first 2 elements. If the array is smaller than length 2, use whatever elements are present.

**Example**

frontPiece([1, 2, 3]) → [1, 2]
frontPiece([1, 2]) → [1, 2]
frontPiece([1]) → [1]

**My solution**

public int[] frontPiece(int[] nums) {
if (nums.length < 2) {
return nums;
}
int[] myArray = new int[2];
myArray[0] = nums[0];
myArray[1] = nums[1];
return myArray;
}

**My question**

Though I have solved this question, my solution looks a bit long. So I’m looking for shorter while still accurate other solutions. Can you help me with this?

## Answer

If you just want a shorter method and if returning the parameter itself when empty or with a single element is valid, then you can write this:

public static int[] frontPiece(int[] nums) {
// if the argument is empty or has just a single element
if (nums.length < 2) {
// return the array itself
return nums;
} else {
// otherwise, return a new array with the first two elements of argument
return new int[] { nums[0], nums[1] };
}
}

## Recent Comments