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

Java

Ene Catalin
Ene Catalin
1,931 Points

I don't understand how the values from the returned array["chars" (readChars method)], are copied in the char[] message.

I thought that copying the values from one array to another, you must use a for loop(I know there may be more options), otherwise only the reference address is copied.

Imgur

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,735 Points

Arrays in Java have to be allocated in memory with a specific length when they get created. We can allocated an empty array with a certain size/length, and then fill it with values later. The readChars method takes an integer parameter. Then the first thing it does is allocate a new char array with that integer size, with nothing in the array yet.

Then it opens a for loop, iterating that same number of times - the int parameter that was passed in which is now the length of the chars array. I assume ITools.readChar() prompts the user for a character. So each time through the for loop, we get another character from the user, and we assign it to the position in the char array with the i index value. By the end of this function, we'll have assembled an array full of chars from the user, with a length according to the argument passed in, and it returns the array.