hi there now I got a situation here.
String myStrings = new String();
myStrings = "10.42.0.1";
char[] charNum = myStrings.toCharArray(); //convert string to char array
char checkSum = 0;
A:
for(int i = 0; i <= 8; i++) {
checkSum += charNum[i];
}
B:
for(int i = 0; i <= 8; i++) {
checkSum = checkSum +charNum[i];
}
compile A: works just what I expect
compile B: Type mismatch: cannot convert from int to char
Since I know java will convert a+=b
to a=char(a+b)
implicitly, that why A works fine.
But what really concern me is what's wrong with charNum[i]
. ok, HeadFirstJava tells me
that array is an object, so charNum[i]
is a reference variable(4bytes), and I accept that. And charNum[i]
(reference variable) points to an char
(2bytes), and I want to use that char
(2bytes) to do arithmetical operation, but it looks like JAVA says NO. When I type
checkSum = checkSum+charNum[i];
( 2bytes ) = ( 2bytes ) + ( 4bytes )
it means that charNum[i]
have 4bytes in memory, and it really confuse me, because I use char
(2bytes) to do the math, not charNum[i]
(reference variable). And if it really use charNum[i]
(4bytes, reference variable) to do the math, why do I get the right value of checksum? SO can anyone tell me do I mistaken HeadFirstJava or do I miss some concept here?
And if you can explain this in detail, that would be highly appreciated.
thanks in advance.