I want to declare an empty array in java and then I want do update it but the code is not working...
public class JavaConversion
{
public static void main(String args[])
{
int array[]={};
int number = 5, i = 0,j = 0;
while (i<4) {
array[i]=number;
i=i+1;
}
while (j<4) {
System.out.println(array[j]);
}
}
}
Use List. clear() method to empty an array.
Example 1 – Check if Array is Empty using Null Check To check if an array is null, use equal to operator and check if array is equal to the value null. In the following example, we will initialize an integer array with null. And then use equal to comparison operator in an If Else statement to check if array is null.
To update or set an element or object at a given index of Java ArrayList, use ArrayList. set() method. ArrayList. set(index, element) method updates the element of ArrayList at specified index with given element.
To create an empty array, you can use an array initializer. The length of the array is equal to the number of items enclosed within the braces of the array initializer. Java allows an empty array initializer, in which case the array is said to be empty.
You are creating an array of zero length (no slots to put anything in)
int array[]={/*nothing in here = array with no elements*/};
and then trying to assign values to array elements (which you don't have, because there are no slots)
array[i] = number; //array[i] = element i in the array of length 0
You need to define a larger array to fit your needs
int array[] = new int[4]; //Create an array with 4 elements [0],[1],[2] and [3] each containing an int value
Your code compiles just fine. However, your array initialization line is wrong:
int array[]={};
What this does is declare an array with a size equal to the number of elements in the brackets. Since there is nothing in the brackets, you're saying the size of the array is 0 - this renders the array completely useless, since now it can't store anything.
Instead, you can either initialize the array right in your original line:
int array[] = { 5, 5, 5, 5 };
Or you can declare the size and then populate it:
int array[] = new int[4];
// ...while loop
If you don't know the size of the array ahead of time (for example, if you're reading a file and storing the contents), you should use an ArrayList
instead, because that's an array that grows in size dynamically as more elements are added to it (in layman's terms).
You need to give the array a size:
public static void main(String args[])
{
int array[] = new int[4];
int number = 5, i = 0,j = 0;
while (i<4){
array[i]=number;
i=i+1;
}
while (j<4){
System.out.println(array[j]);
j++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With