I have written the code below to check the elements of array. I got the required answer. I just want to know what changes should I do so that it gives me the output as 1, 2, 3, 4, 5.
Also when I write a[] instead of b[], the code gives me the error a is already defined in main(java.lang.String[]). Could you please help me?
class ArrayDemo15
{
public static void main(String a[])
{
int b[]=new int[5];
for(int i=0;i<5;i++)
{
System.out.println(b[i]+""+);
}
}
}
“I just want to know what changes should I do so that it gives me the output as
1, 2, 3, 4, 5“If you just want to print those numbers then you dont need array at all. Just use for loop like
But if you insist in improving your code and using array continue reading this answer…
Right now your code gives compilation error in
System.out.println(b[i]+""+);since+in this case is two argument operator and you give it only one argument. Change it to something likeI used
printinsteadprintlnsince you don’t want to have new line signs between numbers.Also currently your array is filled with zeros, because all new arrays are filled with some default values:
– for arrays of primitive numbers type (int, byte, double and so on) default value is 0,
– for primitive boolean it is false,
– and for Objects (like Strings) it is null.
So you need to fill your array first with your values. To do that you have two options
iterate over array and set every element
int[] b1 = { 1, 2, 3, 4, 5 };this version can be used only with referenceint[] b2 = new int[]{ 1, 2, 3, 4, 5 };this version doesn’t need reference and can be used everywhere for example as argument of some method that accepts array of int likeArrays.sort(new int[]{ 5, 3, 1, 4, 2 })When all elements of array are set to correct values you need to print it. You can do it with built-in utility as A. R. S. pointed
System.out.println(java.util.Arrays.toString(b))or do it yourself with loops for example