Search code examples
javacharprimitivecharat

Why does charAt work differently depending on the data type it is printed as


public class MyClass 
{
    public static void main(String args[]) 
    {
        String a = "(4 + 4i)";
        String b = "(2 + 3i)";
        int g = 1;
        int c = a.charAt( g ); // sets c to 52
        System.out.println( c ); // prints 52
        System.out.println( (double) a.charAt( g ) ); // prints 52.0
        System.out.println( a.charAt( g ) ); // prints 4
        System.out.println( 2 * a.charAt( g ) ); // prints 104
    }
}

I was trying to write code to multiply imaginary numbers which is why I have "i" in the strings. So I thought take first and and convert to int or double. This gave me 52 which baffled me. However when I printed directly to console, it worked but only without the double. This is useless because I need to use it elsewhere. So what is going on here? Would it better to try to parse parts of strings a and to int or double and are there alternatives to manipulating numbers within strings without using parse? And are there methods that can deal with imaginary numbers i.e. "e^pi * i = 1"?


Solution

  • A String is a sequence of symbols, such as letters, punctuation, and digits, called characters. Each character is associated with a number. One common way to do this is with what is called the ASCII characters. In this case, you see that the character '4' is represented by the number 52.

    With this in mind, let's look at some of your code:

    int c = a.charAt( g );
    

    This line silently converts the character to its numerical value. By "numerical value" I mean the number that represents the character, not the value of the digit itself. In this case, the character '4' has the numerical value 52.

    System.out.println( a.charAt( g ) ); // prints 4
    

    This prints out the character '4', not the int 4. It is extremely important that you learn the difference between the digit characters and their integer values.

    In order to get the number 4 so that you can perform arithmetic operations, you must parse the String. The function Integer.valueOf() will help a lot with this.

    You should also learn about classes and objects. For example, you can create a Complex class which will allow you to use complex numbers as a single entity with its own operations.

    To get the numerical values that you want, you need to use Integer.valueOf() or Double.valueOf() depending on whether you want an int or a double:

    int c = Integer.valueOf(a.charAt(g))
    

    You will need to use more sophisticated parsing methods if you want to allow numbers with multiple digits or decimal points.