Akshay Akshay - 18 days ago 6
Java Question

I have written the below code to check the elements of array

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]+""+);
}
}
}

Answer

"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

int counter=1;
for (counter=1; counter<=4; counter++)
    System.out.print(counter+", ");
//after loop print last element without comma
System.out.println(counter);

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 like

System.out.print(b[i]+", ");

I used print instead println since 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

  1. iterate over array and set every element

    for (int index = 0; index < b.length; index++) {
        b[index] = index + 1;
    }
    
  2. provide all values while creating array, like
    • int[] b1 = { 1, 2, 3, 4, 5 }; this version can be used only with reference
    • int[] 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 like Arrays.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

for (int i = 0; i < b.length - 1; i++) {// b.length - 1 I don't want to
    // print last element here since I don't want to add comma
    // after it
    System.out.print(b[i] + ", ");
}
// now it is time for last element of array
System.out.println(b[b.length - 1]);
//since b[]={1,2,3,4,5} b.length=5 so it will print b[4] -> 5