How To Find or Get ASCII Value of a String in Java



A String in java is a collection of characters identified by a variable name. A character can be an Alphabet, Number, Symbol or a Punctuation. Let us find out the ASCII value of a String using a Java program. If we assign a character (char) constant to int or short data type variable, what we get is an ASCII value.

This program is a continuation of Finding the ASCII value of a character in Java.

Find or Get ASCII value of a String in Java

ASCII value of a String is the Sum of ASCII values of all characters of a String.

Step 1: Loop through all characters of a string using a FOR loop or any other loop.

String str = "ABC";
for(int i=0; i<str.length(); i++)
{
  System.out.println(str.charAt(i));
}
//OUTPUT
//A
//B
//C

Step 2: Get ASCII value of each character of the string

String str = "ABC";
for(int i=0; i<str.length(); i++)
{
  int asciiValue = str.charAt(i);
  System.out.println(str.charAt(i) + "=" + asciiValue);
}
//OUTPUT
//A=65
//B=66
//C=67

Step 3: Now add all the ASCII values of all characters to get the final ASCII value. A full example program is given below.

public class ASCIIString
{
  public static void main(String[] args)
  {
    String str = "ABC";
    int sum=0;
    for(int i=0; i<str.length(); i++)
    {
      int asciiValue = str.charAt(i);
      sum = sum+ asciiValue;
      //System.out.println(str.charAt(i) + "=" + asciiValue);
    }
    System.out.println("ASCII of " + str + "=" + sum);
  }
}
//OUTPUT
//ASCII of ABC=198

 

This is how we get or find or print ASCII value of strings in Java.

Share this Tutorial with your friends and colleagues to encourage authors.



Like or Share

Show some care. Like or Subscribe. [FB]...[Youtube]

C MCQ App by ExamTray 

Android APP

Java MCQ App by ExamTray 

Android APP
ALL MCQ App by ExamTray Android APP

Ad

 

Try Some Java Books

Book Price
1. Java - The Complete Reference  Check Price
2. Core Java: An Integrated Approach, Black Book Check Price
3. Java All-in-One for Dummies Check Price
4. OCP Java SE 8: Programmer II Check Price
5. Programming with Java Check Price
6. Head First Java Check Price

We may get some affiliate commission for the above purchases.