Possible Loss of Precision
I have this code.
Code :
char[] clearText = clearString.toCharArray();
char[] key = keyString.toCharArray();
char[] cypherText = new char[clearText.length];
for (int x = 0; x < clearText.length; x++) {
cypherText[x] = key[x] + clearText[x];
System.out.println(cypherText[x]);
}
It is giving the error a Possible Loss of Precision at this line, for apparently no reason.
Code :
char letter = key[x] + clearText[x];
Please note that the strings that are not shows are just strings, and are the same length.
EDIT: Made the code less confusing
Re: Possible Loss of Precision
Quote:
Originally Posted by
Canadian_Pirate
for apparently no reason.
Of course there is a reason. do you really think that the creators of Java are in the habit of making up stuff gfro no reason?
The result of your addition is a 32 bit int. You are trying to stuff it into a 16 bit char. Hence the loss of precision.
Re: Possible Loss of Precision
Quote:
Originally Posted by
Junky
Of course there is a reason. do you really think that the creators of Java are in the habit of making up stuff for no reason?
Sometimes the reason's quite poor :P
@OP:
When you try to add characters, Java will first implicitly cast them to an int. The reason for this is because the creators of Java are trying to get people away from the mentality that the char data type can be used as a number data type. However, since there's a lot of times that using the data from a char as an integer data type is very useful, you couldn't completely segregate the two types. So they just had math operations on char data types implicitly cast up to int's (bytes are too small, shorts technically work except for the issue of being signed where-as char's are technically unsigned, though there's not much of a difference other than interpretation).
Once you have an integer result, you can't implicitly cast back to a char (due to the possible loss of precision), you must explicitly cast it back.