Java OCA OCP Practice Question 1449

Question

What will the following program print when compiled and run?

class MyClass  { 
    private int x = 0; 
    private String y = "Y"; 
    public MyClass (int k){ 
        this.x = k;  
     } /*from  ww  w  .j  a v  a2 s .co  m*/
    public MyClass (String k){ 
        this.y = k;  
     }     
    public void showMe (){ 
        System.out.println (x+y); 
     } 
} 
public class Main  { 
    public static void main (String [] args) throws Exception  { 
        new MyClass (10).showMe (); 
        new MyClass ("Z").showMe (); 
     } 
} 

Select 1 option

  • A. 0Z
  • 10Y
  • B. 10Y
  • 0Z
  • C. It will not compile.
  • D. It will throws an exception at run time.


Correct Option is  : B

Note

Note that + operator is overloaded for String.

If you have a String as any operand for +, a new combined String will be created by concatenating the values of both the operands.

Therefore, x+y will result in a String that concatenates integer x and String y.




PreviousNext

Related