Sep 21, 2013

Textual description of firstImageUrl

Java puzzle - Set 3

Question 1:  What will be output of below sample program? 
public class Multicast {
 /**
  * devinline.com
  * Puzzle reference : Java puzzlers 
  */
 public static void main(String[] args) {
  System.out.println((byte) -1); // int to byte
  System.out.println((char) (byte) -1); // byte to char
  System.out.println((int) (char) (byte) -1); // char to int
 }
}

Sample output:-
-1
?
65535
Explanation:- In first SOP int is cast into byte (narrowing primitive conversion).Since java represents negative integer in 2's complement form, so all 32 bits for -1 is 1. When it is narrowed down to byte only 8 bits are preserved other bits are discarded, original value -1 is still preserved(sign indicating bits are discarded). Refer following diagram.
Before going ahead we should consider following guideline regarding when sign extension is performed:-
Sign extension is performed if the type of the original value is signed; zero extension if it is a char, regardless of the type to which it is being converted.

In second SOP signed byte is cast into unsigned 16 bit char. Here signed bit is propagated for higher order 8 bits and 16 bits char with all 1's is formed.(sign extension is performed)
Similarly, in third SOP a char is converted into signed integer and zero extension is performed.Value of integer is retained as 65535.
Question 2:  What will be output of below sample program? 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class CompundOperator {
 /**
 * devinline.com 
 * Puzzle reference : Java puzzlers
 */
 public static void main(String[] args) {
  short x = 0;
  int i = 123456;
  x = x + i;
  System.out.println(x += i);
 }
}

Sample output:-
Compilation error. Type mismatch: cannot convert from int to short (Line # 9)

Explanation
:-
An int value(i) is assigned to short(x) and it may cause possible loss of precision, so compilation error reported.

Now lets comment line # 9 and again execute the above sample program.
What will be the output after commenting line # 9 ? Output:   -7616

Explanation
:- 123456 is converted into -7616 because compound assignment expressions automatically cast the result of the computation they perform to the type of the variable on their left-hand side. Here 123456 value is cast into byte and higher order bits truncated and since leftmost bit is 1 so it indicates negative number -7616.

Question 3: What will be output of below sample program? Hint:- a char is an unsigned 16-bit primitive integer.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class SOP {

 /**
  * devinline.com
  */
 public static void main(String args[]) {
  System.out.println("D");
  System.out.println("D" + "I");
  System.out.println('D');
  System.out.print('D' + 'I');
 }

}

Sample output
:-
D
DI
D
141

Explanation:- Class PrintStream has overloaded version of println() method which takes argument of type String, char, int, float, etc and display string representation of the same.
In first SOP D is treated as String and displays D. Similarly, in second SOP two strings are concatenated and displayed as DI.
In third SOP, a char is argument of function println(), it prints a character and then terminate the line.
What about 4th SOP, their is an expression with + operator and none of the operand is String. So + operator will try to evaluate the given expression and char is promoted to int type. Conversion of unsigned int(char) to int allows zero padding in higher order bits.(16 bit char to 32 bit int with higher order padded with 0). D -> 68 and I-> 73 => 68+73= 141.

Question 4. What will be output of below sample program?

public class SOPInteger {

 /**
  * devinline.com
  */
 public static void main(String args[]) {
  System.out.println("2 + 2 = " + 2 + 2);
  System.out.println("2 + 2 = " + (2 + 2));
  System.out.println("" + 'D' + 'I');
                System.out.println('D' + 'I'+" means devinLine");
 }

}
Sample output:-
2 + 2 = 22
2 + 2 = 4
DI
141 means devinLine

Explanation:- Java does not support operator overloading except when + is used with Strings, + operator can be used as concatenation operator(String conversion on both of its operands and then to concatenate the resulting strings). Function println() calls internally toString() method and represent its argument as String and if expression inside println() starts with a string then + operator will append followed elements to the starting string. taking consideration of all above concept, lets see each SOP. 
In first SOP, expression starts with string so + operator act as concatenation operator. It will treat followed 2+2 as string rather than int.
In second SOP, expression starts with string and its followed + act as concatenation operator. However, followed 2+2 is inside ( ) so first 2+2 is evaluated followed by it is concatenated with previous string. 
Similarly, in third SOP, statement starts with an empty string so followed chars are appended with this empty string "".
In fourth SOP, Since expression starts with a char not a string so + operator will not act as concatenation operator. It will try to add both char type and chars are promoted to int.(See previous question for more detail). First sum is computed and followed by string is appended.

Question 5. What will be output of below sample program? 
package com.devinline.puzzles;

public class ToStringTraps {

/**
 * devinline.com
 */
public static void main(String[] args) {
 char[] chArr = { 'D', 'E', 'V', 'I', 'N', 'L', 'I', 'N', 'E' };
 System.out.println(chArr);
 System.out.println("Output is " + chArr);
 System.out.println("Output is " + chArr.toString());
 System.out.println("Output is " + String.valueOf(chArr));

 }
}

Sample output:-
DEVINLINE
Output is [C@1888759
Output is [C@1888759
Output is DEVINLINE

Explanation:- As mentioned earlier + operator can be used as concatenation operator(String conversion on both of its operands and then to concatenate the resulting strings).
Output of 1st SOP is expected, println() prints string representation of char array.
What happens in second SOP, "chArr" is converted into String and java.lang.Array class inherit toString() method from Object class and toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
 chArr.getClass().getName() + '@'+ Integer.toHexString(chArr.hashCode())
Here getClass().getName() for class object char[] gives string "[C" followed by @ and finally hashcode value 1888759(which might differ if you execute above sample program). So output of 2nd SOP is concentration of first string and chArr string value - Output is [C@1888759
Similarly, in 3rd SOP to.String() of chArr is used so result would be same as above.
Finally, we get intended result in 4th SOP, String.valueOf() explicitly convert the array to a string before concatenation.  
Location: Hyderabad, Telangana, India