#RANDOM QUESTION
24 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @glossy forge! Please use
/closeor theClose Postbutton above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 720 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
Hey so I was wondering
Why can I do that
char[] testChar = new char[1];
testChar = input.next().toCharArray();
System.out.println(testChar);
But not that
char[] testChar = new char[0];
testChar[0] = input.next().toCharArray();
System.out.println(testChar);
I triend changing toCharArray() but I didnt find a way so I was just wondering
Because in the first example you are reassigning the whole testChar variable to another char[] array.
In the second case you are trying to assign an array to a single char.
If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
It's not resizing, it is overwriting the variable with a new array.
You can also do char[] testChar = input.next().toCharArray();
and toCharArray will "choose" the size of my array ig ?
or if you want to overwrite an individual character:
char[] testChar = new char[1];
testChar[0] = input.next().toCharArray()[0];
or
char[] testChar = new char[1];
testChar[0] = input.next().charAt(0);
toCharArray creates a new array which testChar is assigned to
new char[1] creates a char[] and String#toCharArray does so as well
okok, thats some wierd behavior to me id never figure that out by myself
arrays are just objects
This is not like in C where you have to preallocate some buffer and then fill it/write to it.
In your code the new char[1] is thrown away after the toCharArray() assignment.
testChar is not an array. It is a reference to an array.
toCharArray() is returning a reference to a new array. so you're just replacing one reference with another.
This behaviour of the assignment operator is the same for all types in Java.
The code should probably have been (unless you can be certain the next token isn't empty - and we're ignoring the fact that there may not be a next token)
String nextToken = input.next();
if (!nextToken.isEmpty()) {
char firstChar = nextToken.charAt(0);
...
}
Ok that make sense
💤 Post marked as dormant
This post has been inactive for over 720 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use/help ping.
Warning: abusing this will result in moderative actions taken against you.