Monday, June 11, 2012

Tricky Java interview questions and answers

Q. Can interfaces contain inner classes?
Yes, but not recommended as it can compromise on clarity of your code.
The interface with an inner class for demo purpose only


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package innerstatic;
 
public interface InterfaceWithInnerClass {
     
     
    public static final Util UTIL = new Util( );
     
 
    public String getName(); // next node in this list
 
    public final static InterfaceWithInnerClass FIELD =
      //anonymous inner class as the interface field declaration 
      new InterfaceWithInnerClass() {
          public String getName() {
            return "Peter";
        }
    };
 
     
 //static inner class
    public static class Util {
        public String getDetail(){
            return FIELD.getName() + " age 25";
        }
    }
}


The class that implemnts the above interface.

1
2
3
4
5
6
7
8
9
10
11
12
13
package innerstatic;
 
public class Test implements InterfaceWithInnerClass {
 
    @Override
    public String getName() {
        return FIELD.getName() + " : " + UTIL.getDetail();
    }
     
    public static void main(String[] args) {
        System.out.println(new Test().getName());
    }
}

The output is:

Peter : Peter age 25


Q. What happens if you pass a primitive int value to a method that accepts

a) long primitive
b) float primitive
c) Float object
d) Number object

A.
a) A widening conversion takes place from int to long. So, no compile or run time error.
b) A widening conversion takes place from int to float. So, no compile or run time error.
c) compile-time error. primitive type int can be auto-boxed to type Integer, but type Integer and Float are derived from type Number, and don't have the parent child relationship. So, they cannot be implicityly or exlplicitly cast to each other.
d) primitive type int can be auto-boxed to type Integer, and then implicitly cast to type Number as Number and Integer have the parent child relationship. So, no compile or run time error.

No comments:

Post a Comment