1
public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] nums= {3,5,2,8,9,11,1};
        Arrays.stream(nums).forEach(System.out::print);
        System.out.println();
        rotate(nums,3);
        Arrays.stream(nums).forEach(System.out::print);

    }
     public static void rotate(int[] nums, int k) {
            int[] arr=new int[nums.length];
            int j=0;
            int x=k;
            for(int i=nums.length-k;i<nums.length && k>0;i++, j++)//3
            {
                arr[j]=nums[i];
                k--;
            }
          //  Arrays.stream(arr).forEach(System.out::println);
            for(int i=0;i<nums.length-x;i++)
            {
                arr[j]=nums[i];
                j++;
            }
            //Arrays.stream(arr).forEach(System.out::println);
            nums=Arrays.copyOf(arr, arr.length);
            
        }

This is the program I wrote to rotate array elements. In rotate method nums is getting modified,but it's not reflecting in main method.What am I doing wrong here?

This is the output I'm getting:

Rachanaa
  • 43
  • 1
  • 5
  • You could do this using `System.arraycopy(arr, 0, nums, 0, nums.length)` instead. – Andy Turner Aug 28 '21 at 17:25
  • (btw, you can also do efficient in-place rotation of an array, using reversals). – Andy Turner Aug 28 '21 at 17:25
  • but what is causing the current problem? I have a feeling it is related to the last line `nums=Arrays.copyOf(arr, arr.length);` you re-assign the reference to the new Arrays.copyOf, but when the function returns the nums reference in main() is still pointing at the original nums – BabyishTank Aug 28 '21 at 17:29
  • 1
    @BabyishTank yes: that reassignment is changing the parameter, essentially a variable local to the `rotate` method, not the variable passed in at the call site. – Andy Turner Aug 28 '21 at 17:33

0 Answers0