Saturday, May 2, 2020

java puzzlers from oca part 4

In the fourth part of Java Puzzlers, we have something related to char type.


public class Puzzler {

    public static void main(String[] args){
        char myChar = 'a';
        myChar++;

        System.out.println(myChar);
    }
}

You may have guessed it. It will print "b" and the reason for it is that char type is unsigned numeric primitive in the disguise of a character. So if I add one then I'll get the next character in unicode representation.

Then let's take a look at that one


public class Puzzler {

    public static void main(String[] args){
        char myChar = 'a';

        System.out.println(myChar + myChar);
    }
}
Will this print "aa"? Or  which's 97 + 97 = 194 (where 97 is value of 'a'). I don't know if you guessed it right but the result is neither. It's "194". When Java sees plus it tells "hmm that's an addition not a concat" and adds myChars up and returns the int value for it.

No comments:

Post a Comment