Home » Java » Slice Array to left by K time in java

Slice Array to left by K time in java

This tutorial teaches you how to slice elements in an Array by K time in Java. The class name is SliceArray and the array name is “givenArray” and that has 2,4,6,4,2,1,7,8,9 as elements. The array is declared in the main method. The variable numOfTime” contains an integer number that equals the number of slicing times. Here it is equal to 5.

The method “sliceArray” will be called with two parameters. The parameters are the givenArray and numOfTime. The method sliceArray declared as static. So, it can be called without creating objects.

Note – This code shows how to slice elements to left.

Because of slicing elements to left we have to save the last element as the first step. This is done in line 2. Outer for loop runs numOfTimes. Inner for loop runs through the array from light to left.

In the inner for loop, each element slice to left as line 4. Then, the first element is filled by the last element. line 5.

Step 2 will print sliced array on cmd.

public class SliceArray {

    public static void main(String[] args) {
        int[] givenArray = new int[]{1,5,2,1,6,7,5,8}; 
        int numOfTimes = 5;
        sliceArray(givenArray, numOfTimes);
    private static void sliceArray(int A[], int K) {
        // Step 1
        for (int a = 1; a < K + 1 ; a++) { //line 1
            // get the first element
            int last = A[A.length - 1]; // line 2

            // Shift element to left by one
            for (int i = A.length - 1; i > 0; i--) { //line 3

                A[i] = A[i - 1]; //line 4


            // Fill first lement by last element
            A[0] = last; // line 5

	// Step 2 - print new array
        for (int j = 0; j < A.length; j++) {
            System.out.print(A[j] + ",");
Please follow us:

Leave a Reply

Your email address will not be published. Required fields are marked *