- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]
- Related Articles
- How to extend the size of an array in Java
- How to define an array in C#?
- How to define an array class in C#?
- Java Program to double the size of an array
- How to declare Java array with array size dynamically?
- Java program to reverse an array in groups of given size
- Can we define an abstract class without abstract method in java?\n\n
- How to create an array in Kotlin like in Java by just providing a size?
- Java Program to extend the size of an Integer array
- How to splice an array without mutating the original Array?
- How to define the rank of an array in C#?
- How to sorting an array without using loops in Node.js?
- Find size of array in C/C++ without using sizeof
- How to convert an object array to an integer array in Java?
- How to shuffle an array in Java?

Advertisements