my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt  in char array and byte array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt  in char array and byte array" Watch "Doubt  in char array and byte array" New topic

Doubt in char array and byte array

GopiKrishnan Chelliah

Joined: Jan 27, 2008
Posts: 10
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))
static char[] getCharArray(byte []arr){
char[] carr=new char[4];
int i=0;
for(byte c:arr){
return carr;
Christophe Verré

Joined: Nov 24, 2005
Posts: 14687

Because c++ return the value of c before the incrementation. Please see this FAQ.

[My Blog]
All roads lead to JavaRanch
Sunny Jain
Ranch Hand

Joined: Jul 23, 2007
Posts: 433


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++;
j = 0;
i = ++j;

If you know these two concept and you can answer them correctly..!!
then you think about your must be knowing your answer..!!

Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
Siphiwe Madi
Ranch Hand

Joined: Aug 16, 2007
Posts: 70
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.

Siphiwe Madi

Regards, Siphiwe Madi
[SCJP, SCWCD, __] Next ... scjwsd
wood burning stoves
subject: Doubt in char array and byte array