Sunday 4 November 2018

Frequently Asked JAVA Interview Question and Answer Part 2

Hi Guys, In this post I'll share some more interview questions and answers which i have faced or asked in interview panel.you can read my previous post related to JAVA QA  JAVA QA PART 1.

1). Can an interface implement or extend another interface?
Ans).Interfaces don’t implement another interface, they extend it. Since interfaces can’t have method implementations, there is no issue of diamond problem. That’s why we have multiple inheritance in interfaces i.e an interface can extend multiple interfaces.
From Java 8 onwards, interfaces can have default method implementations. So to handle diamond problem when a common default method is present in multiple interfaces, it’s mandatory to provide implementation of the method in the class implementing them.
2). What is Marker interface?
Ans).A marker interface is an empty interface without any method but used to force some functionality in implementing classes by Java. Some of the well known marker interfaces are Serializable and Cloneable.
3). What are Wrapper classes?
Ans).Java wrapper classes are the Object representation of eight primitive types in java. All the wrapper classes in java are immutable and final. Java 5 autoboxing and unboxing allows easy conversion between primitive types and their corresponding wrapper classes.
4). What is Enum in Java?
Ans).Enum was introduced in Java 1.5 as a new type whose fields consists of fixed set of constants. For example, in Java we can create Direction as enum with fixed fields as EAST, WEST, NORTH, SOUTH.
enum is the keyword to create an enum type and similar to class. Enum constants are implicitly static and final.
5). What is Java Annotations?
Ans).Java Annotations provide information about the code and they have no direct effect on the code they annotate. Annotations are introduced in Java 5. Annotation is metadata about the program embedded in the program itself. It can be parsed by the annotation parsing tool or by compiler. We can also specify annotation availability to either compile time only or till runtime also. Java Built-in annotations are @Override, @Deprecated and @SuppressWarnings.
6). What is composition in java?
Ans).Composition is the design technique to implement has-a relationship in classes. We can use Object composition for code reuse.
Java composition is achieved by using instance variables that refers to other objects. Benefit of using composition is that we can control the visibility of other object to client classes and reuse only what we need.
7). What is the benefit of Composition over Inheritance?
Ans).One of the best practices of java programming is to “favor composition over inheritance”. Some of the possible reasons are:
1.      Any change in the superclass might affect subclass even though we might not be using the superclass methods. For example, if we have a method test() in subclass and suddenly somebody introduces a method test() in superclass, we will get compilation errors in subclass. Composition will never face this issue because we are using only what methods we need.
2.      Inheritance exposes all the super class methods and variables to client and if we have no control in designing superclass, it can lead to security holes. Composition allows us to provide restricted access to the methods and hence more secure.
We can get runtime binding in composition where inheritance binds the classes at compile time. So composition provides flexibility in invocation of methods.
8). How to sort a collection of custom Objects in Java?
Ans).We need to implement Comparable interface to support sorting of custom objects in a collection. Comparable interface has compareTo(T obj) method which is used by sorting methods and by providing this method implementation, we can provide default way to sort custom objects collection.
However, if you want to sort based on different criteria, such as sorting an Employees collection based on salary or age, then we can create Comparator instances and pass it as sorting methodology.
9). What is inner class in java?
Ans).We can define a class inside a class and they are called nested classes. Any non-static nested class is known as inner class. Inner classes are associated with the object of the class and they can access all the variables and methods of the outer class. Since inner classes are associated with instance, we can’t have any static variables in them.
We can have local inner class or anonymous inner class inside a class.
10). What is anonymous inner class?
Ans).A local inner class without name is known as anonymous inner class. An anonymous class is defined and instantiated in a single statement. Anonymous inner class always extend a class or implement an interface.
Since an anonymous class has no name, it is not possible to define a constructor for an anonymous class. Anonymous inner classes are accessible only at the point where it is defined.
11). What is Classloader in Java?
Ans).Java Classloader is the program that loads byte code program into memory when we want to access any class. We can create our own classloader by extending ClassLoader class and overriding loadClass(String name) method Class Loader.
12). What are different types of classloaders?
Ans).There are three types of built-in Class Loaders in Java:
1.      Bootstrap Class Loader – It loads JDK internal classes, typically loads rt.jar and other core classes.
2.      Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
3.      System Class Loader – It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options.
13). What is ternary operator in java?
Ans).Java ternary operator is the only conditional operator that takes three operands. It’s a one liner replacement for if-then-else statement and used a lot in java programming. We can use ternary operator if-else conditions or even switch conditions using nested ternary operators. 
14). What does super keyword do?
Ans).super keyword can be used to access super class method when you have overridden the method in the child class.
We can use super keyword to invoke super class constructor in child class constructor but in this case it should be the first statement in the constructor method.
package com.journaldev.access;
public class SuperClass {
   public SuperClass(){
   }
   public SuperClass(int i){}
   public void test(){
             System.out.println("super class test method");
   }}
Use of super keyword can be seen in below child class implementation.
package com.journaldev.access;
public class ChildClass extends SuperClass {
   public ChildClass(String str){
             //access super class constructor with super keyword
             super();
             //access child class method
             test();
             //use super to access super class method
             super.test();
   }
   @Override
   public void test(){
             System.out.println("child class test method");
   }}
15). What is break and continue statement?
Ans).We can use break statement to terminate for, while, or do-while loop. We can use break statement in switch statement to exit the switch case. We can use break with label to terminate the nested loops.
The continue statement skips the current iteration of a for, while or do-while loop. We can use continue statement with label to skip the current iteration of outermost loop.
16). What is this keyword?
Ans).this keyword provides reference to the current object and it’s mostly used to make sure that object variables are used, not the local variables having same name.
//constructor
public Point(int x, int y) {
    this.x = x;
    this.y = y;}
We can also use this keyword to invoke other constructors from a constructor.
public Rectangle() {
    this(0, 0, 0, 0);}public Rectangle(int width, int height) {
    this(0, 0, width, height);}public Rectangle(int x, int y, int width, int height) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;}
17). What is default constructor?
Ans).No argument constructor of a class is known as default constructor. When we don’t define any constructor for the class, java compiler automatically creates the default no-args constructor for the class. If there are other constructors defined, then compiler won’t create default constructor for us.
18). Can we have try without catch block?
Ans).Yes, we can have try-finally statement and hence avoiding catch block.
19). What is Garbage Collection?
Ans).Garbage Collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. In Java, process of deallocating memory is handled automatically by the garbage collector.
We can run the garbage collector with code Runtime.getRuntime().gc() or use utility method System.gc(). For a detailed analysis of Heap Memory and Garbage Collection,please read Java Garbage Collection. 
20). What is Serialization and Deserialization?
Ans).We can convert a Java object to an Stream that is called Serialization. Once an object is converted to Stream, it can be saved to file or send over the network or used in socket connections.
The object should implement Serializable interface and we can use java.io.ObjectOutputStream to write object to file or to any OutputStream object.The process of converting stream data created through serialization to Object is called deserialization. 
21). How to run a JAR file through command prompt?
Ans).We can run a jar file using java command but it requires Main-Class entry in jar manifest file. Main-Class is the entry point of the jar and used by java command to execute the class. 
22). What is the use of System class?
Ans).Java System Class is one of the core classes. One of the easiest way to log information for debugging is System.out.print() method.
System class is final so that we can’t subclass and override it’s behavior through inheritance. System class doesn’t provide any public constructors, so we can’t instantiate this class and that’s why all of it’s methods are static.
Some of the utility methods of System class are for array copy, get current time, reading environment variables.
23). What is instanceof keyword?
Ans).We can use instanceof keyword to check if an object belongs to a class or not. We should avoid it’s usage as much as possible. 
Sample usage is:public static void main(String args[]){
   Object str = new String("abc");
             
   if(str instanceof String){
             System.out.println("String value:"+str);
   }
             
   if(str instanceof Integer){
             System.out.println("Integer value:"+str);
   }}

Since str is of type String at runtime, first if statement evaluates to true and second one to false.
24). Can we use String with switch case?
Ans).One of the Java 7 feature was improvement of switch case of allow Strings. So if you are using Java 7 or higher version, you can use String in switch-case statements.

25). Java is Pass by Value or Pass by Reference?
Ans).This is a very confusing question, we know that object variables contain reference to the Objects in heap space. When we invoke any method, a copy of these variables is passed and gets stored in the stack memory of the method. We can test any language whether it’s pass by reference or pass by value through a simple generic swap method.

Cheers :)

No comments:

Eclipse With Python

Hi Guys, Today i'll share how to start python project in eclipse IDE. to start Py development in eclipse we need to add Py Dev plugi...