Saturday, May 2, 2020

java puzzlers from oca part 4

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


1public class Puzzler {
2 
3    public static void main(String[] args){
4        char myChar = 'a';
5        myChar++;
6 
7        System.out.println(myChar);
8    }
9}

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


1public class Puzzler {
2 
3    public static void main(String[] args){
4        char myChar = 'a';
5 
6        System.out.println(myChar + myChar);
7    }
8}
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.

java puzzlers from oca part 3

In this third part of Java puzzlers, we will see a surprise in variable naming restrictions.


If I show you this, I'm sure you won't be surprised that this does not compile. static is one of the reserved keywords so why should it work?
1public class Puzzler {
2 
3    public static void main(String[] args){
4 
5        int static = 2;
6    }
7 
8}
Now I'll ask you a more difficult one. What you think about the below code. Will this compile?
1public class Puzzler {
2 
3    public static void main(String[] args){
4        int bool = 0;
5        int integer = 1;
6        int const = 2;
7        int goto = 3;
8    }
9}
None of these should be reserved keyword. This is not C right? If you thought that it will compile, you're wrong. const and goto are reserved keywords, but bool and integer are fine.