Reputation: 21
class ArrayPrint {
static void arrayPrinter(int[] x) {
for (int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
}
public static void main(String... S) {
int[] x = {3, 3, 4, 2, 7};
x = new int[5];
arrayPrinter(x);
System.out.println(x.length);
}
}
The expected array is not printing, it is instead printing 0 0 0 0 0
. What could be the error?
Upvotes: 0
Views: 331
Reputation: 2184
you are re-initializeing your array, you should either use
int[]x = new int[5];
x[0] = 3;
x[1] = 3;
// and the rest of your array
OR
int[]x = {3,3,...};
then you can print your array,
try
import java.util.*;
// ... some code
System.out.println(Arrays.toString(x));
Upvotes: 1
Reputation: 279910
int[] x = {3,3,4,2,7};
x = new int[5]; // re-initializing
You are re-initializing the array. By default, the element values in the new array will all be 0.
Just remove the
x = new int[5];
This notation
int[] x = {3,3,4,2,7};
Creates an int array of size 5, with the element values you've specified.
Upvotes: 4
Reputation: 4375
Well, you are re-initializing the array to 0, 0, 0,0.
When you write int[] x = {3,3,4,2,7}; it initializes the array with your desired values, but in the next line you overwrite it with a "new" int[5], therefore five 0's
Upvotes: 1
Reputation: 8473
You are re initialized x
array with the statement
x = new int[5];
By default, the values of array will be 0.That is the reason you are getting the output. So remove it
public static void main(String...S) {
int[] x = {3,3,4,2,7};
arrayPrinter(x);
System.out.println(x.length);
}
Upvotes: 1
Reputation: 10810
x = new int[5];
Re-initializes your array to all zeroes. Remove that line.
Upvotes: 1