Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Björn Norén
9,569 PointsPrint a returned array
Hello there! I want to turn an int array of elements to zeros, but I don't know how to print a returned array. I get something like: I@sdgodfnos;
Is there anyone who knows how to print a returned array? I want it to look something like this: [0, 0, 0, 0, 0]
Thanks!
public static int[] createIntArray(int l)
{
int[] array = new int[l];
for (int i=0; i<l; i++)
{
array[i] = 0;
}
return array;
}
public static void main (String[] args)
{
Integer[] C = {1, 2, 3, 4, 5};
System.out.println(createIntArray(C.length));
}
2 Answers

Steve Goldman
2,345 PointsWhen you ask Java to print an array it just prints out the memory address of the array. That is those weird mumbo-jumbo letters/numbers.
We have to tell Java to actually go through that memory address and print what's inside it. You can either make a for loop to go through the array and print out each index or you can use Java's Arrays.toString(insert your array here) method.
Hope that helps.

Kourosh Raeen
23,733 Pointsprintln
will not produce the output you want but you can write a function that does that. You can use a string declared and initialized outside a for loop:
String output = "[";
Then in the for loop keep concatenating the array elements to output
and also adding the comma. Once you're done with the loop concatenate "]" and return the string.

Björn Norén
9,569 PointsAh, I see! So the new function should be a void? Thanks!

Kourosh Raeen
23,733 PointsThe way I described it above it wouldn't be void. It would return a string like [0, 0, 0, 0, 0] so to print it you just pass the return value of that function to println()
, but you could make it a void function and do the printing inside the function. I personally prefer for the function to only return the string and do the printing elsewhere.
Björn Norén
9,569 PointsBjörn Norén
9,569 PointsYes, it helped. :) Thanks for taking your time to explain!