Write a Java program to swap the first and last elements of an array and create a new array

Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..

import java.util.Arrays; 
 public class Javaexcercise {
 public static void main(String[] args)
 {
    int[] array_nums = {10, 20, 30};
    System.out.println("Original Array: "+Arrays.toString(array_nums)); 
    int x = array_nums[0];
    array_nums[0] = array_nums[array_nums.length-1];
    array_nums[array_nums.length-1] = x;
    System.out.println("New array after swaping the first and last elements: "+Arrays.toString(array_nums));  
 }
}

Result

Write a Java program to swap the first and last elements of an array and create a new array
Write a Java program to swap the first and last elements of an array and create a new array

Leave a Comment