0

I'm making this array where the first number in the array should be 15 and the third as well. Then I need to print the array on the screen but I get an error when I do this, I've read that I got to write a loop when printing an array. How's that possible?

This is my current code.

    int[] i = {15,0,15,0,0};
    System.out.println(i);

And what's the difference in using this method or using

int [] i = new int [5];

Thanks in advance,

Michael.

6 Answers 6

5

To print an array use Arrays.toString();

import java.util.Arrays;

System.out.println(Arrays.toString(i));


// or print it in the loop
for(int e : i) {
   System.out.print(e);
}

About differences between two methods:

int [] i = new int [5]; // five evements are allocated

// the number of elements are determined by the initialization block
int[] i = {15,0,15,0,0}; 
Sign up to request clarification or add additional context in comments.

1 Comment

Like this? int[] i = {12,0,12,0,0}; System.out.println(Arrays.toString(i)); That doesn't work. Do I need to import something to be able to use it? And isn't it better with a loop? That's just what I've heard so I'm wondering how to print it as a loop. Thanks
2

You could write a loop like this:

for(int j=0; j < i.length; j++) {
  System.out.println("Value at index " + j + ": " + i[j]");
}

Comments

1

It's considered a "mistake" in java that there's no implementation for toString() - you get java.lang.Object implementation.

Instead, you must use the static method Arrays.toString(array).

Writing this int [] i = new int [5]; allocates memory for 5 elements, but they are all intitialized to zero (0). You would have to write more code to assign values to the elements.

Comments

1

That code executes just fine, although it's probably not the string you expect as the default value for toString() (which is what gets executed) is defined as:

getClass().getName() + '@' + Integer.toHexString(hashCode())

To print the actual contents of the string you should employ the method suggested by e.g., @Oleg.

The statement int[] i = {15,0,15,0,0}; is just shorthand for the more verbose

 int [] i = new int [5];
 i[0] = 15;
 i[1] = 0;
 i[2] = 15;
 i[3] = 0;
 i[4] = 0;

Comments

0

Either you could print like this:

for (int index=0; index<i.length; index++)
System.out.println("Array's value at index " + index  + "is: " + i[index] );

Or you can use toString() function.

Comments

0

The difference between the two is that

int[] i = {15,0,15,0,0};
System.out.println(i);

the elements are determined by a initialization block , while

int [] i = new int [5]; 

five elements are allocated in the int i.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.