• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in char array and byte array

 
GopiKrishnan Chelliah
Greenhorn
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you please explain why the output comes as 2340 and not 3451?
public class ForEach1
{
public static void main(String arg[])
{
byte arr[]=new byte[]{2,3,4};
for(final int i:getCharArray(arr))
System.out.print(i);
}
static char[] getCharArray(byte []arr){
char[] carr=new char[4];
int i=0;
for(byte c:arr){
carr[i]=(char)c++;
i++;
}
return carr;
}
}
 
Christophe Verré
Sheriff
Pie
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because c++ return the value of c before the incrementation. Please see this FAQ.
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok,

First tell me two concept:

1) When we write following

int[] num = new int[4];

what will be the values of num[0],num[1],num[2],num[3] ?
Or when an array object is created what are the values by which its elements are initiated..?

2) What do you mean by pre-increment and post-increment operator?

Or what will be the output of the following:

int i,j;
j = 0;
i = j++;
System.out.println(i);
Or
j = 0;
i = ++j;
System.out.println(i);


If you know these two concept and you can answer them correctly..!!
then you think about your question..you must be knowing your answer..!!
 
Siphiwe Madi
Ranch Hand
Posts: 70
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi G Chelliah,

This is what happens:

inside the loop, the elements are initialized as follows

carr[0] = 2 (value 2 is assigned to char[0], then c is incremented to 3)
carr[1] = 3 (value 3 is assigned to char[1], then c is incremented to 4)
carr[2] = 4 (value 4 is assigned to char[2], then c is incremented to 5)

end of loop
carr[3] = 0 (default value of char)

so basically after the loop the values held in the array elements are:

carr[0]=2, carr[1]=3, carr[2]=4, carr[3]=0

(note: the 0 in the last element is the default value that was assigned when the
array char[] carr was declared and initialized.)

Importantly to note the c++ in the statement, is a post-increment, not a pre-increment.
carr[i] = (char)c++;

Hope this helps.

Regards,
Siphiwe Madi
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic