-3

I want to write code to take one intput integer say "n" and arrya of size "n" but I don't want to give all n number of elements in that array. can I do this in java? if yes then how?

(actually I am writing a code for taking one input n and an array of size n and give element to that array in runtime. and want to print the output YES if the number of elements are as same as the size of the array. and print output NO if number of elements given to the array are less then that of the size of the array.)

1 Answers1

1

You cannot use an array of primitive int type, as that array will be initialized with all of its indexes as 0 (default value).

But you can use Integer object, which will initialize the array with null values. Check the following:

Integer [] intArray = new Integer[10];
intArray[0] = 5;
//Rest of indexes are null
boolean isArrayFull = true;
for (Integer i:intArray){
   if (i==null){
      isArrayFull = false; //Enter here only if at least one index is null/empty.
   }
}
System.out.println(isArrayFull?"YES":"NO");

It creates an Integer type array with 10 indexes. The intArray[0] is filled with number 5 and the rest indexes are null.

Then it iterates the array and if finds null, sets the isArrayFull to false.

Ioannis Barakos
  • 1,319
  • 1
  • 11
  • 16
  • Usually it's better to use primitives where possible. https://stackoverflow.com/questions/2063556/when-we-have-wrappers-classes-why-primitives-are-supported – FailingCoder Nov 12 '19 at 16:22
  • Correct, however this use case requires a null object in the array, if the array is of int primitive type, the initial values of all indexes would be 0 and not null. Therefore, the code could not find if a value has not been assigned or was assigned later. – Ioannis Barakos Nov 12 '19 at 16:29
  • I am aware of this, but generally there is no point of having null values in an array. However, it was an odd requirement which you needed this null object for whatever reason. You answered the question correctly. – FailingCoder Nov 12 '19 at 20:09