April 06, 2016

#Java: Part 8-Core Java Interview Questions and Answers (Interface, final, finalize, finally)

> > Part 7-Core Java Interview Questions and Answers (Generics)

What is an interface and what are the advantages and disadvantage of using interfaces in Java?
  • With interfaces, we can achieve abstraction in Java along with abstract class.
  • Interface in java is declared using keyword interface and it represent a Type like any Class in Java. A reference variable of type interface can point to any implementation of that interface in Java.
  • All variables declared inside interface is implicitly public final variable or constants. which brings a useful case of using Interface for declaring Constants.
  • All methods declared inside Java Interfaces are implicitly public and abstract, even if you don't use public or abstract keyword. You can not define any concrete method in interface (till java 7). That's why interface is used to define contracts in terms of variables and methods and you can rely on its implementation for performing job.

Advantages:
  • Interfaces allow several classes to share a standard set of methods and constants without requiring these methods and constants to be implemented by a common superclass.
  • Interfaces are mainly used to provide polymorphic behavior and a standard framework for accessing classes.
  • Interfaces function to break up the complex designs and clear the dependencies between objects.
Disadvantages:
  • Java interfaces are slower.
  • Interface should be used multiple number of times else there is hardly any use of having them.
What is the difference between an interface and an abstract class?
  • An abstract class usually contains abstract and non-abstract methods that subclasses are forced to provide an implementation for. We cannot instantiate an abstract class, it need to be subclassed. An interface is a completely 'abstract class', that is used to group related methods with empty bodies.
  • An abstract class can have final, static, or class member variables whereas in interface all the variables are by default static and final by default.
  • An abstract class can have static, abstract, or non-abstract methods. An interface can have static, abstract, or default methods.
  • Members of an abstract class can have varying visibility of private, protected, or public. Whereas, in an interface all methods and constants are public.
  • A class can only extend another class, but it can implement multiple interfaces. Similarly, an interface can extend multiple interfaces, but an interface never implements a class or an interface.
  • Use an abstract class when subclasses share state or use common functionality. Or you require to declare non-static, non-final fields or need access modifiers other than public. Use an interface if you expect unrelated classes would implement your interface. e.g Comparable and Cloneable are implemented by many unrelated classes.
Can an Interface implement another Interface?
Interfaces doesn't provide implementation hence a interface cannot implement another interface.

Can an Interface extend another Interface?
Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.

Can a class be defined inside an Interface?
Yes it's possible.

Can an Interface be defined inside a class?
Yes it's possible.

What will be output of below program?
public class A implements Interface1, Interface2{

    public static void main(String args[])
    {
        System.out.println(testval);
    }
}

interface Interface1
{
    String testval="Interface1";
}

interface Interface2
{
    String testval="Interface2";
}

It will throw an error that the field is ambiguous. We can access testval of Interface1 by Interface1.testval.

What will be the output of below code?
public static void main(String args[])
    {
        ArrayList testArray=new ArrayList<>();
        testArray.add(1);
        testArray.add(2);
        testArray.add(3);
   
        for (int i:testArray)
        {
            System.out.print(i);
        }   
    }
Ans: 123

What will be the output of below code?
public static void main(String args[])
    {
        int i=1;
        switch(i)
        {
        case 1: System.out.print("One");
        case 2: System.out.print("Two");
        case 3: System.out.print("Three");
        }
    }
Ans: OneTwoThree

What will be the output of below code?
public static void main(String args[])
    {
        int i=1;
        switch(i)
        {
        case 1: System.out.print("One"); break;
        case 2: System.out.print("Two"); break;
        case 3: System.out.print("Three");break;
        }
    }
Ans:One

What will be the output of below code?
public static void main(String args[])
    {
        String a="Hello";
        String b="Hello";
        String c =new String("Hello");
        String d=new String("Hello");
   
        System.out.println(a==b);
        System.out.println(c==d);
        System.out.println(c.equals(d));
    }
Ans:
true
false
true


What will be the output of following programs?
public class MyTestClass {
    public static String toString(){
        System.out.println("inside toString()");
        return "";
    }
    public static void main(String args[]){
        System.out.println(toString());
    }
}


The code won’t compile because we can’t have an Object class method with static keyword, you will get compile time error as, “This static method cannot hide the instance method from Object”.

What will be the output of following programs?
public class MyTestClass {
    public static String foo(){
        System.out.println("inside foo");
        return "";
    }

    public static void main(String args[]){
        Test obj = null;
        System.out.println(obj.foo());
    }
}


It will not throw NullPointerException, instead it will print 'inside foo'. The reason for this is the java compiler code optimization. When the java code is compiled to produced byte code, it figures out that foo() is a static method and should be called using class. So it changes the method call obj.foo() to Test.foo() and hence NullPointerException is not thrown.

What is the right data type to represent a price in Java?
If memory is not a concern and performance is not critical, use BigDecimal. Else use double with predefined precision.

How do you convert bytes to String in Java?
Simple toString() cannot be used, since it will not display the original text but byte value. We can convert bytes to the string using string constructor which accepts byte[], just make sure that right character encoding otherwise platform's default character encoding will be used which may or may not be same. e.g: String s = new String(bytes);

How do you convert bytes to long in Java?
public static long convertToLong(byte[] array) {
    ByteBuffer buffer = ByteBuffer.wrap(array);
    return buffer.getLong();
}

public static void main(String[] argv) {
    System.out.println(convertToLong(new byte[]{1,2,3,4,5,6,7,8,9,8,67}));
}

Can we cast an int value into byte variable? If yes, what will happen if the value of int is larger than byte?
Yes, we can cast, but since int is 32 bit long in java while byte is 8 bit long, that's why when we cast an int to byte higher 24 bits are lost and a byte can only hold a value from -128 to 128.

Can you store a double value in a long variable without casting?

No, we cannot store a double value into a long variable without casting because the range of double is more then long.

What will this return 3*0.1 == 0.3?
It will return false, because floating point numbers can not be represented exactly (3*0.1 will return 0.30000000000000004).

Which one will take more memory, an int or Integer?

Integer, because it stores the meta data overhead about the object and int is primitive type so its takes less space.

What is the difference between final, finalize and finally?
  • The final is a modifier which we can apply to variable, methods and classes. If we make a variable final, it acts as a constant, which means its value cannot be changed once initialized. If we make a method final in Java, we can not override it in subclass. final keyword helps to write Immutable classes, if we make a class final means it can not be sub classed. When a class is declared as final it will automatically make all its method final.
  • finally is a keyword which is used in exception handling along with try and catch. the finally block is always executed irrespective of whether an exception is thrown from try block or not.
  • finalize is a method, which is called just before an object is a garbage collected. This is the last chance for an object to perform any cleanup but since it's not guaranteed that whether finalize() will be called, its bad practice to keep resource till finalize call. Though we can build a safety net on finalize by double checking scarce resources. 
What is a compile time constant in Java?
Variable's which are declared as 'public static final' are also known as a compile time constant (public is optional). They are replaced with actual values at compile time because compiler know their value up-front and also knows that it cannot be changed during run-time.

What is the risk of using compile time constant in Java?

If we happened to use a public static final variable from some in-house or third party library and their value changed later than our client will still be using old value even after you deploy a new version of JARs. To avoid this, we need to compile our program when we upgrade dependency JAR files.

What is bytecode in context of Java?

It is the type of code generated by Java Compiler.

What will be the output of this program?
Integer a=100, b=100;
Integer c=1000, d=1000;
System.out.println(a==b);
System.out.println(c==d);


The first sysout will return true, whereas the second will return false.

Whenever you compile a number literal in Java and assign it to a Integer ('Integer a=100') the compiler emits Integer a =Integer.valueOf(100);

Above line of code is also generated when you use autoboxing. valueOf is implemented such that certain numbers are 'pooled', and it returns the same instance for values smaller than 128. In Java valueOf is implemented as:
public static Integer valueOf(int i) {
    if(i >= -128 && i <= IntegerCache.high)
        return IntegerCache.cache[i + 128];
    else
        return new Integer(i);
}

That means Integer objects with the values -128 to 127 are immutable (that is, for one particular integer value, say 27, all Integer objects instantiated through your program with the value 27 points to the exact same object).

If you want to increase IntegerCache, then you need to configure 'IntegerCache.high' with the system property.
-Djava.lang.Integer.IntegerCache.high=999

If you set this, then 'System.out.println(c==d)' will return true.

For the uninitiated, == operator compares by reference (does the variables point to the same object). Its better never rely on two references being identical, always compare them with .equals() method. So c.equals(d) will print true for all logically equal values of c,d.

ALSO CHECKCore Java Interview Questions And Answers

-K Himaanshu Shuklaa..

No comments:

Post a Comment