Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] data = { 1, 2, 3, 4, 5 };

        // Expand the data array to 7 elements
        int[] eData = expandArray(data, 7);

        // Truncate the data array to 3 elements
        int[] tData = expandArray(data, 3);

        System.out.println("Original  Array: " + Arrays.toString(data));
        System.out.println("Expanded Array: " + Arrays.toString(eData));
        System.out.println("Truncated  Array: " + Arrays.toString(tData));

    }

    // Uses a for-loop to copy an array
    public static int[] expandArray(int[] oldArray, int newlength) {
        int originallength = oldArray.length;
        int[] newArray = new int[newlength];
        int elementsToCopy = 0;

        if (originallength > newlength) {
            elementsToCopy = newlength;
        } else {

            elementsToCopy = originallength;
        }
        for (int i = 0; i < elementsToCopy; i++) {
            newArray[i] = oldArray[i];
        }
        return newArray;
    }
}