String name = "Just for Testing";
int greatestVal = 0;
for (int i = 0; i < name.length(); i++)
{
int curVal = (int)name.charAt(i);
if(curVal > greatestVal)
greatestVal = curVal;
}
char asChar = (char)greatestVal;
System.out.println("The character with the highest ASCII (encoding) number was " + asChar + " (with ASCII (encoding) " + greatestVal + ")");
Now to explain this a little bit:
What happens at the line int curVal = (int)name.charAt(i);
is called explicit casting. .charAt()
returns a char
, which is casted by us to an int
(by using (int)
in front of it). This is where "the magic" happens. curVal
now contains the corresponding value for the character at position i
in the platform's default encoding (for more infos see this post). What nearly all of those encodings have in common is that the first 128 characters match to ASCII, more details in this question.
This can now be compared with greatestVal
, and by looping over the whole String, we can find the character with the highest underlying ASCII value. Here a link to an ASCII table, so you can check yourself which character corresponds to which value.
At char asChar = (char)greatestVal;
we just do the same again, we cast the int
back to a char
, which may then be printed.
As shown in another answer, you can also compare char
s to each other, like name.charAt(i) > greatestChar
. What happens behind is that those two characters are compared based on their encoding value, just as I showed you manually in the above example.