Tuesday, 8 May 2012

Core Java Interview Questions -Language Fundamentals

Question:What is the out of below program? 


package com.lac.faq;

class A {
 public int i;
}

public class ParamPassDemo {
 public static void main(String[] args) {
  A a =new A();//Create an object of A
  a.i=10;
  change(a);
  a=null;
  System.out.println(a.i); //Guess result of print statement
 }
 private static void change(A a){
  a=null; //assign null
 }
 
}
Answer: The out put of the above program is 10. Most of us think the out put can be "java.lang.NullPointerException" but it is not because Objects in java are passed by copy of reference. When 'a' is passed to function 'change' the copy of reference 'a' is passed, so making the copied reference 'null' doesn't have any impact.


Question: Determine the Output of below program?

package com.lac.faq;

public class MyString extends String {
 public static void main(String[] args) {
  MyString s1="abc",s2="xyz";
  System.out.println(s1+s2);
  
 }

}
Answer: Compilation Error "MyString.java:3: cannot inherit from final java.lang.String"
Explanation: String class is a final class and it is not possible to inherit from a final class.

4 comments:

  1. i really like that you are giving information on core and advance java concepts. Being enrolled at http://www.wiziq.com/course/1779-core-and-advance-java-concepts i found your information very helpful indeed.thanks for it.

    ReplyDelete
  2. Hey hi
    the output of the first program is NullPointerException. Though you have passed copy of reference variable a in method and assign it Null but on line 12 you have Null the value of original and single reference variable a. So it will throw an Exception not because of line 16 but because of line 12.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command.
    Java Training in Chennai

    ReplyDelete