Java Array shift elements

Introduction

The following code shifts the array elements one position to the left and filling the last element with the first element:


import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    System.out.println(Arrays.toString(array));
    int temp = array[0]; // Retain the first element

    // Shift elements left array
    for (int i = 1; i < array.length; i++) {
      array[i - 1] = array[i];/*from w w  w .  ja  v a  2  s .  co  m*/
    }

    // Move the first element to fill in the last position
    array[array.length - 1] = temp;

    System.out.println(Arrays.toString(array));
  }
}



PreviousNext

Related