To get the ASCII value of a letter in a String
in Java, you can use the charAt()
method of the String
class to get the character at a specific index, and then cast it to an int
to get its ASCII value.
Here's an example of how to get the ASCII value of a letter in a String
in Java:
String s = "abcdef"; int asciiValue = (int) s.charAt(0); System.out.println("The ASCII value of '" + s.charAt(0) + "' is: " + asciiValue); // The ASCII value of 'a' is: 97
In the above example, the charAt()
method is used to get the character at index 0 of the String
s
, which is the letter 'a'. The character is then cast to an int
to get its ASCII value, which is 97.
You can also use a loop to get the ASCII values of all the letters in a String
. For example:
for (int i = 0; i < s.length(); i++) { int asciiValue = (int) s.charAt(i); System.out.println("The ASCII value of '" + s.charAt(i) + "' is: " + asciiValue); }
In this case, the for
loop is used to iterate over the characters in the String
s
, and the ASCII value of each character is printed to the console.
For more information on working with characters in Java, you can refer to the documentation for the char
data type in the Java Language Specification.