Java is a must-know programming language in today’s placement scenario. Every application we use uses Java. And so, every technical interview consists of questions from Java. To help you guys prepare for the Technical Interview, we had already discussed few of the most commonly asked Java interview questions – set 1. In this article, we will discuss the second part of the most frequently asked Java interview questions.
Array:
Generally, Array is a collection of similar type of elements that are arranged in adjacent memory addresses. In Java, Array is an object which contains similar types of elements. By default, the size of these elements stored in an array cannot be changed. i.e, you will give a size to the array and you cannot expand or reduce it later. If you want to change the size of the array, you have to create a new array and copy the data that you want. But this process is tedious. But, in Platforms such as Java 6 and Java 7, built-in classes like ArrayList are introduced.
List Interface:
The list interface is the ordered collection of objects in which you can store duplicate values. In list interface, you can insert elements in desired positions as it has insertion and positional access.
ArrayList:
The class ArrayList is an array-based implementation of the List interface. All the elements of the ArrayList are stored in a Java array and hence, it has fixed size in the beginning. For example, an array list by the name of xyz is of the size m. In the beginning, the array xyz is capable of storing a maximum of m elements. But, when the (m+1)th element is added to the array, the size of the array will be increased by 50% of its original size automatically. This is done by acquiring a bigger array and copying all the elements of the current array to the bigger array.
Synchronization:
Thread synchronization is a mechanism which ensures that two or more processes do not simultaneously execute the same program section.
Vector:
Like ArrayList, Vector also implements List interface and uses insertion order. But, unlike ArrayList, Vector is synchronized. Even though the adding, searching, updating and deleting of arrays are not carried out satisfactorily because of the synchronization, the vectors can grow and shrink as required to accommodate elements. In the beginning, using this vector class object will create an initial capacity of m. If the (m+1)th element is added, the size of the vector is doubled.
Declaring the vector in its default form as in Vector xyz = new Vector(); will create 10 initial capacity. In case of Vector xyz = new Vector(int size, int incr); the initial capacity is specified by the size and the increment of the size is specified by incr.
Differences between ArrayList and Vector:
ArrayList is not synchronized, but Vector is synchronized. Hence, the ArrayList is fast and Vector is slow.
If the element m+1 is inserted into an m array, then the size of the ArrayList is increased by 50% and that of the vector is doubled.
The ArrayList doesn’t define the increment size while the Vector can define the increment size (eg: Vector xyz = new Vector(int size, int incr);)
Poly in Greek means many and morph means forms. Polymorphism, in simple words, is the ability of one function to take up many forms. In Java, Polymorphism is the ability of the language to process objects of various types and class through a single interface. For example, you will behave as a customer in the shop, as a student in college, as an employee in the workplace and as a fan in the stadium. Here, you are polymorphic.
Polymorphism is of two types as:
Compile Time Polymorphism
Run Time Polymorphism
This type of polymorphism uses method overloading. i.e, There are multiple methods in a class with the same name and different types/ number of arguments/ parameters. At the time of compiling, Java compiler will just look at the type or the number of arguments given to know which method to invoke.
Eg:
class DemoOverload{npublic int add(int x, int y){ //method 1nreturn x+y;n}npublic int add(int x, int y, int z){ //method 2nreturn x+y+z;n}npublic int add(double x, int y){ //method 3nreturn (int)x+y;n}npublic int add(int x, double y){ //method 4nreturn x+(int)y;n}n}nclass Main{npublic static void main(String[] args){nDemoOverload demo=new DemoOverload();nSystem.out.println(demo.add(2,3)); //method 1 callednSystem.out.println(demo.add(2,3,4)); //method 2 callednSystem.out.println(demo.add(2,3.4)); //method 4 callednSystem.out.println(demo.add(2.5,3)); //method 3 calledn}n}n
This is a process where the call to the overridden method is resolved at run-time rather than during compile-time. In this process, the overridden method is called through the superclass’s reference variable. This type of polymorphism allocates the memory space for the object at runtime.
Eg:
class Car{ nvoid run(){System.out.println("running");} n} nclass Audi extends Car{ nvoid run(){System.out.println("Running safely with 70km");n} n}nclass Main{npublic static void main(String args[]){ nCar c = new Audi(); //upcasting nc.run(); n} n} n
Output:
Running safely in 70km
In the above program, we created two classes called Car and Audi. The class Audi, the child class, extends the parent class, Car. Then, the run method is called by the reference variable of the parent class, i.e, c. Since it refers to the child class’ object and also, as the child class’ method overrides the Parent class method, the subclass method is invoked at runtime.
Eg:
class Shape{nvoid draw(){System.out.println("drawing...");}n}nclass Rectangle extends Shape{nvoid draw(){System.out.println("drawing rectangle...");}n}nclass Circle extends Shape{nvoid draw(){System.out.println("drawing circle...");}n}nclass Triangle extends Shape{nvoid draw(){System.out.println("drawing triangle...");}n}nclass Main{npublic static void main(String args[]){nShape s;ns=new Rectangle();ns.draw();ns=new Circle();ns.draw();ns=new Triangle();ns.draw();n}n}n
Output:
drawing rectangle…
drawing circle…
drawing triangle…
Servlets and applets came into the picture as soon as the web was used for delivering services. This is because the service providers recognized the need for a more dynamic content. Hence, at first, the applets was developed. It completely focused on using the client Platform to provide the dynamic experience. At the same time, the servlets are developed to give the dynamic experience from the server platform.
Java servlet is a Java program that extends the capabilities of a server. A Java Servlet container provides lifecycle management which is a single process to share and manage application-wide resources and interaction with a Web server. The primary use of the Java Servlet is to define a robust mechanism for sending content to a client as according to the definition of the Client/Server model. Also, Servlets natively supports HTTP.
It processes the input from client side and generates the response in terms of the HTML page, Applets or Javascript. The lifecycle of a servlet consists of init( ), service( ), and destroy( ).
Java supports multiple inheritance through its interfaces. The reason for not supporting multiple inheritance through classes is to avoid the conflict and complexity that arises due to it and keep Java a Simple Object-Oriented Language.
This decision is taken because, in C++, there is a special case of multiple inheritance (in Diamond problem) where you have a multiple inheritance with two classes or more classes overriding a method. So, Java developers decided to avoid such conflicts and didn’t allow multiple inheritance through classes at all.
The multiple inheritance through interface is shown below:
InterfaceA.java
package com.faceprep.inheritance;
public interface InterfaceA {
public void xyz();
}
InterfaceB.java
package com.faceprep.inheritance;
public interface InterfaceB {
public void xyz();
}
Both the interfaces given above are declaring the same method. Now, an interface extending both these interfaces is implemented.
InterfaceC.java
package com.faceprep.inheritance;
public interface InterfaceC extends InterfaceA, InterfaceB { //same method is declared in both InterfaceA and InterfaceB
public void xyz();
}
The above program will generate a clean output because the interfaces are only declaring the methods and the actual implementation will be done by concrete classes implementing the interfaces. So there is no possibility of any kind of ambiguity in multiple inheritance through interfaces.
Unlike C+ +, Java doesn’t need destructors as the ‘Garbage Collector‘ automatically destroys the objects for us. If there is no reference is present to an object, Garbage Collector assumes that it is no longer needed, and hence, the memory occupied by the object can be freed. The finalize() method is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
Sometimes an object can hold non-java resources such as file handle or database connection. Hence, you have to make sure that these resources are also released before the object is destroyed. The finalize() is used as it performs many operations, including bringing the object back to life. To do this, provide the protected void finalize() in the object class. You can override this method in your class and do the required tasks. Right before an object is freed, the java runtime calls the finalize() method on that object.
Several things happen in a particular order to ensure the object is constructed properly:
1. Memory is allocated from the heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implementation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its superclasses. This process continues until the constructor for java.lang.The object is called, as java.lang.The object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
These are few of the most commonly asked Java Interview questions.
Stay in touch with FACE Prep for the set 3 of the most commonly asked Java interview questions.
Click here for the most commonly asked C language pattern printing question.