Core Java

Java puzzlers from OCA part 4

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

1
2
3
4
5
6
7
8
9
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

1
2
3
4
5
6
7
8
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.

Published on Java Code Geeks with permission by Sezin Karli, partner at our JCG program. See the original article here: java puzzlers from oca part 4

Opinions expressed by Java Code Geeks contributors are their own.

Sezin Karli

Mathematics Engineer & Computer Scientist with a passion for software development. Avid learner for new technologies. Currently working as Senior Software Engineer at Sahibinden.com.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button