How to define an array size in java without hardcoding?


To avoid hard coding you can read the size of the array from the user using command line arguments of the reader classes like Scanner. Then using this value create an array:

Example

import java.util.Arrays;
import java.util.Scanner;

public class PopulatingAnArray {
   public static void main(String args[]) {
      System.out.println("Enter the required size of the array :: ");
      Scanner s = new Scanner(System.in);
      int size = s.nextInt();
      int myArray[] = new int [size];
      System.out.println("Enter the elements of the array one by one ");
      for(int i=0; i<size; i++) {
         myArray[i] = s.nextInt();
      }
      System.out.println("Contents of the array are: "+Arrays.toString(myArray));
   }
}

Output

Enter the required size of the array ::
5
Enter the elements of the array one by one
78
96
45
23
45
Contents of the array are: [78, 96, 45, 23, 45]

Updated on: 19-Feb-2020

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements