Java Data Type How to - Convert String of length 1 to the associated int value of ASCII code (0-255)








Question

We would like to know how to convert String of length 1 to the associated int value of ASCII code (0-255).

Answer

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*from  w w  w.  j a v a 2s. c  o m*/
public class Main {
  public static void main(String args[]) throws IOException {
    BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the char:");
    String str = buff.readLine();
    for (int i = 0; i < str.length(); ++i) {
      char c = str.charAt(i);
      int j = (int) c;
      System.out.println("ASCII OF " + c + " = " + j + ".");
    }
  }

}