Saturday, 5 November 2016

Java String interview questions

Hi,

We can get below type of questions in interview for java strings.

public class StringExample {

    public static void main(String a[]) throws Exception {
            String s11 = "ABC";
            String s111 = "ABC";
            String s234 = new String("ABC");
            System.out.println(s11.equals(s111));
            System.out.println(s11==s111);
//below line prints false as new object will created for s234(hashcode will different for two objects)
            System.out.println(s11==s234);
//below line prints true as it will check for string value(ABC) not for object
            System.out.println(s11.equals(s234));
  }
}

What is the out put:

correct answer is
true
true
false
true

Java Constructor Interview Program

Hi ,

We can find below type of questions in interviews. Please write the out put for below program.

public class ConstructorExample1 {

    static int j;
    public ConstructorExample1() {
        System.out.println("default");
    }

    public ConstructorExample1(int i) {
        this();//It will call default constructor
        System.out.println("p1");
    }

    public ConstructorExample1(String i, int j) {
//        ConstructorExample1();
        this(j);//it will call current class constructor which has one integer as variable
        System.out.println("p2");
    }
   
    public static void getData(){
        j = 2*7;
        System.out.println(j);
    }
   
    public  void getData1(){
        j = 2*7;
        System.out.println(j);
    }
    public static void main(String a[]){
//        ConstructorExample1 constructorExample1 = new ConstructorExample1();
//        ConstructorExample1 constructorExample11 = new ConstructorExample1(1);
//Below line of code will print all constructor outputs
ConstructorExample1 constructorExample111 = new ConstructorExample1("bal", 2);
    }
}

Below are the options which we will get in exam: Correct answer is option d
a.) compilation error
b) default
    p1
c) runtime error
d) default
    p1
    p2
e) p2