0

When using the code below, I am a beginner testing what String methods do. Though, whenever using hello and using a char i to represent 0, why is it not printing out h and instead 104. And if there is a reason why it is printing 104, why?

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        String hello = "hello";
        char i  = hello.charAt(0);
        System.out.println(+i);
    }
}
CryptoFool
  • 21,719
  • 5
  • 26
  • 44

1 Answers1

3

The '+' is messing you up. Remove that one character and you'll get the result you desire:

class Solution {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String hello = "hello";
        char i  = hello.charAt(0);
        System.out.println(i);
    }
}

Result:

h

104 is the ASCII value that represents the 'h' character. I couldn't have told you this in advance, but apparently putting a'+' in front of a character value causes it to be converted to an integer that is its ASCII value.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44