July 27, 2017

Some Basic Core Java Interview Questions

Confusing Overloading and Overriding Questions

1). We have a Father and Son class, Son is extending Father. Father class has two methods m1() and m2(), Son has a single method m3().

What is going to happen if I do this?
Son s=new Father();
s.m1();

This will throw a compile time error 'cannot convert from Father to Son'.

Let's say the method m1() is declared as protected in Father class, I am overriding it in Son without writing protected key word. What will happen? 

It will throw a compile time error, 'Cannot reduce the visibility of the inherited method from Father'.

If Father's m1() is default , can I override it in Son and make it protected? Yes.

NOTE: Overriding method must not have more restrictive access modifier. For e.g. if the Access Modifier of base class method is public then the overriding method (child class method ) cannot have private, protected and default Access modifier as all of the three are more restrictive than public.

Father's m1() is throwing FileNotFoundException, can I throw IOException from overridden m1()? No, because we cannot throw a newer or boarder exception.

If the Father's m1() is throwing IOException, we can throw FileNotFoundException Son's m1(), because FileNotFoundException extends IOException.

NOTE: Overriding method (method of child class) can throw any unchecked exceptions, regardless of whether the overridden method(method of parent class) throws any exception or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method.

2). What will happen if I overload foo method in below manner?
void foo(){}
int foo(){}
String foo(){}

We will get a compile time error 'Duplicate method foo()'.

NOTE: Overloaded methods may have different return types; the return type alone is insufficient to distinguish two versions of a method.

3). If MyClass has below methods:
void foo(String s){}
void foo(Object o){}

Now if I call foo by passing null, which method will be called?
myclassObj.foo(null);

It will call the foo method which takes String.

Now, lets say I add another method:
void foo(int s) {}

What will happen if I call myclassObj.foo(null);? Again It will call the foo method which takes String.

Now, lets say I add another method:
void foo(Integer s) {}

What will happen if I call myclassObj.foo(null);? You will get a compile time error 'The method foo(String) is ambiguous', because the compiler is not able to decide whther to call method which takes String or Integer?

4). Can I override a static method?
private, static and final methods cannot be overridden as they are local to the class. However static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of parent class.

Static methods belong to the class and not the objects. Since they belong to the class and hence doesn't fit properly for the polymorphic behavior.

Static methods are resolved at compile time rather than runtime. Though you can declare and define static method of same name and signature in the child class, this will hide the static method from parent class, that's why it is also known as method hiding in Java.

Suppose you have declared a Father class, which is extended by Son. Both the classes have method 'static void sayHello()'.

Father f=new Son();
f.sayHello();


This will always call sayHello() method from Father class. (if sayHello() was not declared static then, sayHello() from Son will be called).

5). Let's say you have a Father class, another class Son is extending Father.

Inside my test class, have declared below methods:

static void foo(Father f) {
  System.out.println("Father's foo");
}

static void foo(Son s) {
  System.out.println("Son's foo");
}

Which method will be called when I pass null in foo: foo(null) will call the method which takes Son as input.

Now let's say I have added another class Grandson which is extending Son. After this I added another method in our test class:

static void foo(GrandSon gs) {
  System.out.println("GrandSon's foo");
}

In this case foo(null) will call the method which takes GrandSon as input.

If both Son and GrandSon extends Father class, and we declared three foo methods each taking Father, Son and GrandSon as an input. And we call foo by passing a null, we will get a compilation error "The method foo(Father) is ambiguous."

6). If the Son is extending Father class, and which line/ lines in the below code will result in compilation/ runtime error?

Father f=new Son();
Son s=new Father();//compilation error 'cannot convert from Father to Son'

Set < Father > fatherset=new HashSet < > ();
fatherset.add(new Father());//works fine
fatherset.add(new Son());//works fine
fatherset.add(f);//works fine

Set < Son > sonset=new HashSet  > ();
sonset.add(new Father());//compilation error Set is not applicable for the arguments (Father)
sonset.add(new Son());//works fine
sonset.add(f);//compilation error Set is not applicable for the arguments (Father)

7). Father class has m1() and m2() methods, Son class is extending Father and is overriding method m1(), along with this it has another method m3(). Which of the lines will throw complication error?

Father f1=new Father();
f1.m3();//compilation error method m3() is undefined for the type Father

Father f2=new Son();
f2.m3();//compilation error method m3() is undefined for the type Father

Father s2=new Son();
s2.m1();//overridden method from Son is called

Father s3=new Father();
s3.m1();//Father's m1() will be called.

Try, catch, finally block.
1). Can I write a try block without catch and finally? No.

2). Can I write a try block without catch and with finally? Yes.

3). What will be the output of below method:
int foo() {
   try {
      return 0;
   }
   catch(Exception e) {
      return 1;
   }
   finally {
      return 2;
   }
}

It will return 2. Finally block will execute, but you will get a warning 'finally block does not complete normally'.

4). What will be the output of below method?
int foo() {
   try {
    return 0;
   }
   catch(Exception e) {
    return 1;
   }
   finally {
    System.out.println("This is Finally block");
   }
}

It will print 'his is Finally block' and return 0.

5). What if I mention System.exit(0) in try block, will finally block is going to execute?
System.exit() statement behaves differently than return statement. Unlike return statement whenever System.exit() gets called in try block then Finally block doesn’t execute.

System.exit(0) gets called without any exception then finally won’t execute. However if any exception occurs while calling System.exit(0) then finally block will be executed.

6). What is the output of below code:
public static void main(String args[]) {
  try {
    System.out.println("First statement of try block");
    int num = 45 / 0;
    System.out.println(num);
  } catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Exception occurred.");
  } 
  finally {
    System.out.println("finally block");
  }
  System.out.println("Out of try-catch-finally block");
}

It will print:
First statement of try block
Exception in thread "main" finally block
java.lang.ArithmeticException: / by zero
at com.Test.main(Test.java:20)

If ArithmeticException is catched instead of ArrayIndexOutOfBoundsException, output would be:
First statement of try block
Exception occurred.
finally block
Out of try-catch-finally block

-K Himaanshu Shuklaa..


No comments:

Post a Comment