Thursday, August 4, 2016

Core Java Interview Questions

What is difference between JDK, JRE and JVM?
Java Development Kit (JDK) is for development purpose and JVM is a part of it to execute the java programs.
JDK provides all the tools, executables and binaries required to compile, debug and execute a Java Program. The execution part is handled by JVM to provide machine independence.
JVM is responsible for converting byte code into machine readable code. JVM is not platform independent, that’s why you have different JVM for different operating systems
Java Runtime Environment (JRE) is the implementation of JVM. JRE consists of JVM and java binaries and other classes to execute any program successfully. JRE doesn’t contain any development tools like java compiler, debugger etc. If you want to execute any java program, you should have JRE installed. 

How many types of memory areas are allocated by JVM?
Many types:
  1. Class(Method) Area
  2. Heap
  3. Stack
  4. Program Counter Register
  5. Native Method Stack
Internal Architecture of JVM
Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine etc.

1) Classloader
Classloader is a subsystem of JVM that is used to load class files.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.
3) Heap
It is the runtime data area in which objects are allocated.
4) Stack
Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
5) Program Counter Register
PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed.
6) Native Method Stack
It contains all the native methods used in the application.
7) Execution Engine
It contains:
1) A virtual processor
2) Interpreter: Read bytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler: It is used to improve the performance.JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term ?compiler? refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.


What is classloader?
The classloader is a subsystem of JVM that is used to load classes and interfaces.
Java Classloader is the program that loads byte code program into memory when we want to access any class.
There are three types of built-in Class Loaders in Java:
·        Bootstrap Class Loader – It loads JDK internal classes, typically loads rt.jar and other core classes.
·         Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
·         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

Oops Concepts
Oops is an approach that provides a way of modularizing a program by creating partitioned memory area for both data and methods that can be used as template for creating copies of such modules on demand.
It simplifies the software development and maintenance by providing some concepts:
  • Object
  • Class
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.
It is a bundle of related variables and functions (also known methods).

Class
A class is a prototype that defines the variables and the methods common to all objects of a certain kind.

Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

  1. Inheritance is a mechanism of defining a new class based on an existing class.
  2. Inheritance enables reuse of code. Inheritance also provides scope for refinement of the existing class. Inheritance helps in specialization
  3. The existing (or original) class is called the base class or super class or parent class. The new class which inherits from the base class is called the derived class or sub class or child class.
  4. Inheritance implements the “Is-A” or “Kind of/ Has-A” relationship.
 Polymorphism
When one task is performed by different ways i.e. known as polymorphism.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

How to bring in Encapsulation
1) Make the instance variables protected.
2) Create public accessor methods and use these methods from within the calling code.
3) Use the JavaBeans naming convention of getter and setter.
Eg: getPropertyNamesetPropertyName.



Difference Between Method Overloading and Method Overriding in Java
1.      When a class has more than one method with same name but with different arguments, then we call it as method overloading. Whereas If subclass (child class) has the same method as declared in the parent class, it is known as method overriding.

Why Method Overloaing is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let's see how ambiguity may occur:

because there was problem:
class Calculation3{  
int sum(int a,int b){System.out.println(a+b);}  
 double sum(int a,int b){System.out.println(a+b);}  
 public static void main(String args[]){  
Calculation3 obj=new Calculation3();  
int result=obj.sum(20,20); //Compile Time Error  
  }  
}  

Output: int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
Can we overload main() method?
Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the simple example:
class Overloading1{  
      public static void main(int a){  
  System.out.println(a);  
      }  
  public static void main(String args[]){  
  System.out.println("main() method invoked");  
  main(10);  
  }  
}

Covariant Return Type
The covariant return type specifies that the return type may vary in the same direction as the subclass.
Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type. Let's take a simple example:

class A{  
A get(){return this;}  
}  
class B1 extends A{  
B1 get(){return this;}  
void message(){System.out.println("welcome to covariant return type");}  
  
public static void main(String args[]){  
new B1().get().message();  
}  
}  
As you can see in the above example, the return type of the get() method of A class is A but the return type of the get() method of B class is B. Both methods have different return type but it is method overriding. This is known as covariant return type.

Difference Between Static Binding and Dynamic Binding in Java
Binding refers to the link between method call and method definition. This picture clearly shows what is binding.

Static Binding in Java:
Static binding is a binding which happens during compilation. It is also called early binding because binding happens before a program actually runs.
Method overloading is the best example of static binding.
Private, static and final methods show static binding. Because, they cannot be overridden.
  
Dynamic Binding in Java:
Dynamic binding is a binding which happens during run time. It is also called late binding because binding happens when program actually is running.
Method overriding is the best example of dynamic binding.

Other than private, static and final methods show dynamic binding. Because, they can be overridden.


What is constructor?
  • Constructor is just like a method that is used to initialize the state of an object. It is invoked at the time of object creation.

Rules for creating java constructor
There are basically two rules defined for the constructor.
  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type
           Every class should have at least one constructor. If you don’t write constructor for your class, compiler will give default constructor. Default constructor is always public and it has no arguments (No-Arg Constructor)

What is constructor chaining?
Constructor Chaining is a technique of calling another constructor from one constructor. this() is used to call same class constructor whereas super() is used to call super class constructor.
class SuperClass
{
    public SuperClass(int i)
    {
        System.out.println("Super Class Constructor");
    }
}
class SubClass extends SuperClass
{
    public SubClass()
    {
        this(10);      //Calling same class constructor
    }
    public SubClass(int i)
    {
        super(i);      //Calling super class constructor
    }

Difference between constructor and method in java
There are many differences between constructors and methods. They are given below.
                      Java Constructor
               Java Method
Constructor is used to initialize the state of an object.
Method is used to expose behaviour of an object.
Constructor must not have return type.
Method must have return type.
Constructor is invoked implicitly.
Method is invoked explicitly.
The java compiler provides a default constructor if you don't have any constructor.
Method is not provided by compiler in any case.
Constructor name must be same as the class name.
Method name may or may not be same as class name.

Java static keyword
The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
  1. variable (also known as class variable)
  2. method (also known as class method)
  3. block
  4. nested class
 What is static variable?
  • static variable is used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees, college name of students etc.
  • static variable gets memory only once in class area at the time of class loading.
 Advantage of static variable
It makes your program memory efficient (i.e it saves memory).

Java static method
If you apply static keyword with any method, it is known as static method.
  • A static method belongs to the class rather than object of a class.
  • A static method can be invoked without the need for creating an instance of a class.
  • static method can access static data member and can change the value of it.
 Restrictions for static method
There are two main restrictions for the static method. They are:

  1. The static method cannot use non static data member or call non-static method directly.
  2. this and super cannot be used in static context.
 Why java main method is static?
Because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.


Java static block
  • Is used to initialize the static data member.
  • It is executed before main method at the time of class loading.
Example:
class StaticBlock{  
  static{System.out.println("static block is invoked");}  
  public static void main(String args[]){  
   System.out.println("Hello main");  
  }  
}  

Can we execute a program without main() method?
Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
 class A3{  
 static{  
  System.out.println("static block is invoked");  
  System.exit(0);  
      }  
  }  

In JDK7 and above, output will be:
Output: Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)


What is difference between static (class) method and instance method?
             static or class method
                   instance method
1)A method i.e. declared as static is known as static method.
A method i.e. not declared as static is known as instance method.
2)Object is not required to call static method.
Object is required to call instance methods.
3)Non-static (instance) members cannot be accessed in static context (static method, static block and static nested class) directly.
static and non-static variables both can be accessed in instance methods.
4)For example: public static int cube(int n){ return n*n*n;}
For example: public void msg(){...}.

this keyword in java
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
  1. this keyword can be used to refer current class instance variable.
  2. this() can be used to invoke current class constructor.
  3. this keyword can be used to invoke current class method (implicitly)
  4. this can be passed as an argument in the method call.
  5. this can be passed as argument in the constructor call.
  6. this keyword can also be used to return the current class instance.
super keyword in java
The super keyword in java is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.
Usage of java super Keyword
  1. super is used to refer immediate parent class instance variable.
  2. super() is used to invoke immediate parent class constructor.
  3. super is used to invoke immediate parent class method.
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and behaviours of parent object.
Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java
  • For Method Overriding (so runtime polymorphism can be achieved).
  • For Code Reusability.

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.
class A{  
void msg(){System.out.println("Hello");}  
}  
class B{  
void msg(){System.out.println("Welcome");}  
}  
class C extends A,B{//suppose if it were  
  
Public Static void main(String args[]){  
 C obj=new C();  
 obj.msg();//Now which msg() method would be invoked?  
}  
}  
Output: Compile Time Error

What is composition?
Holding the reference of the other class within some other class is known as composition.

Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.
Consider a situation, Employee object contains many information’s such as id, name, emailId etc. It contains one more object named address, which contains its own information’s such as city, state, country, zipcode etc. as given below.
class Employee{  
int id;  
String name;  
Address address;//Address is a class  
...  
}  
In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.


 Object Cloning in Java
The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object.

No comments:

Post a Comment