Java puzzle -Set 1

Disclaimer : I do not claim that contents available here are my own , it's compiled by me after reading various pages on internet to make others life easy. :) Happy learning!!

Question 1:   Static block trap!! What will be the output of this program ?
public class Test {  
   static {  
     main(new String[]{"[Static call]"});  
   public static void main(String[] args) {  
     System.out.println(args.length > 0 ? args[0] : 
                                        "[From main]");  
Solution : Here two time main method will be called one originated from static block (Since on loading a class by class loader static block elements are scanned from top to bottom and executed one by one) So in this case static block code will be executed and main method will be executed. Later since execution of program is starts from main(Its golden rule in java) so second time again main method will be executed.Sample output is :
 Static call
 From main
Question 2: Give a try with ternary operator!! What will be the output of this program ?
public class TernaryOperation{  
   public static void main(String[] args) {  
     char x = 'X';  
     int i = 0;  
     System.out.print(true ? x : 0);  
     System.out.print(false ? i : x);   
Solution: At first look it appears easy and output flashes in mind ,match your output with sample output below. We will go into delve of problem and concept behind it , from first SOP it is clear that conditional expression is true so value of x will be printed (i.e : X) but what happened to second SOP ?  it did not printed 'X' again , instead printed ASCII value of 'X'. As per JLS(Java language specification) automatic conversion of type comes into picture in ternary operator if type is integer or double is there.please refer this and this for detail.
Some general rules to workout such problem :
1. If any operand is double final result will be of double type.
2. If operand is of reference type the unboxing will happen there.
3. If one operand char and other is variable of type int then final result will be of type int. Sample output is:
  X 88
Question 3 : Do you recognize me ">>" and ">>>" ? Verify your output with sample outcome.
 public class ShiftOperators {  
   public static void main(String[] args) {    
      System.out.println("I(>>) maintain sign so (-4 >> 2) is : 
                                                      "+ -4>>2);  
      System.out.println("I(>>) maintain sign so (4 >> 2) is :
                                                       "+ 4>>2);
      System.out.println("I do not (>>>) maintain sign so  
                               (-4 >>> 2) is :" + -4>>>2);
      System.out.println("I do not (>>>) maintain sign so 
                                (4 >>> 2) is :" + 4>>>2);
Solution:  Java supports following two right shift operators : signed right shift operator >> and
Unsigned right shift operator >>>.
The operator ‘>>’ uses the sign bit (left most bit) to fill the trailing positions after shift. If the number is negative, then 1 is used as a filler and if the number is positive, then 0 is used as a filler.
On the other hand, the operator ‘>>>’ is unsigned right shift operator. It always fills 0 irrespective of the sign of the number. Before going to our problem, we should understand how internally negative numbers are stored: Negative numbers are stored in 32 bit 2's complement form. For example, Binary representation of -1 is all 1s (111..1) 32 times ,left most bit of this is 1, it indicates that it is negative number. How do we find 2's complement of a number?
Now come back to our problem, in case of first SOP statement with signed shift operator:
2's complement representation of -4 =  1111...100 and after doing shift operation (-4>>2) it shift number by 2 and outcome becomes 111...001(1 at 3rd position from right is shifted 2 position right) and sign is maintained as stated earlier with left most bit as 1, So final outcome is -1(111...001).
Similarly, for second SOP, (4>>2), the outcome is 1 (left most bit is 0, since it is positive number).
Now we will look for third SOP statement, binary representation of -4 is 111...100. After performing right shift unsigned operation(-4>>>2) outcome becomes : 011....001, here leftmost bit is 0 because this operator (>>>) does not retain sign and It always fills 0 irrespective of the sign of the number.
So it prints 1073741823.
For fourth SOP statement it prints 1. It is similar to second one because it is positive number and sign bit is 0.Sample output is:
Question 4 : Predict the outcome. (Hint: Program start from main method, Opps!! We have two main method here)
class MainBuster{
    public static void main(){
         System.out.println("Hello!! I will execute too.");
    public static void main(String[] args) {
         System.out.println("Do not worry!! I will execute.");
Solution:What is your sample output ? Compile time error because of two main method or something else.This program compiles with ease. We can have multiple main method in a class with once exception ONLY one main method signature can have String array as method argument.
so it works as usual.Sample output is :
 Do not worry!! I will execute.
 Hello!! I will execute too.
Question 5: What is outcome of following snippet, when doThis() is being called?

class TryFinally{  
  public static int doThis() {
        try {
            System.out.println("Hello try");
            return 12;
        } finally {
            System.out.println("Hello finally");
            return 13;
   public static void main(String[] arg) {
Solution: finally block is always executed except in system failure( or System.exit()).So, finally block will be always executed and 13 will be returned instead of 12. So , what will happen to statement "return 12" ? Answer of this question lies in when finally gets executed? Answer : finally is always executed just before any return statement in try block, As it can be verified from following snippet :
public static int tryFinallyTest()
   try {  
    return 1;  
   finally {  
     System.out.println("finally block is run before 
                            method returns.");
 public static void main(String args[]) 
   // call the prtryFinallyTest method and print the return value
Outcome of the above snippet is :
finally block is run before method returns
Now it's evident that, finally block is executed just before return statement of try block if available. Now we apply the same logic in our main problem and we can conclude that return value in the finally block (“13″) will override the return value in the try block (“12″) and ultimately 13 will be returned to calling method.Sample output is
 Hello try
 Hello finally
                   ================End of article ===============

Happy learning!!!


Previous Post Next Post