Most Asked Java Interview Questions
Most Asked Java Interview Questions
Most of you are confused between methods and functions. Functions, used in C++,
and methods, used in Java, have the same functionality with a minor difference.
Functions are a set of codes that are called in any part of the program by referring to
its name. Methods are a set of codes that are called in any part of the program
by referring to its name and these are associated with an object.
There is no automatic coercion in Java, unlike C++. Coercion is to convert one data
type to another. In Java, coercion is explicitly made and is performed using code
instructions.
In Java, variables are not declared separately. They are the part of a class.
There’s no scope resolution operator (::) in Java. Java uses the dot for everything
but can get away with it since you can define elements only within a class.
JDK (Java Development Kit): This tool is necessary to compile, document and
package Java programs. The JDK includes JRE which contains tools for Java
programmers. Along with JRE, it includes an interpreter/loader, a documentation
generator (javadoc), an archiver (jar), a compiler (javac), and other tools needed in
Java development. To put it simply, it encloses the JRE and the development tools.
void: It is the return type of the method. Void defines the method that doesn’t return
any value.
main: Main is the method that is searched by the JVM as it is considered as the
starting point of the program.
In this, only the name of the string can be changed and the rest remains constant.
In variables, the value of the final variable is constant and cannot be changed.
An example for how the super keyword is used to access the data members of a
parent class is given below:
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
An example for how the super keyword is used to invoke a method of a parent class
is given below:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
An example for how the super keyword is used to invoke a constructor of a parent
class is given below:
class Animal
{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
One of the advantages of Swing components is that because the components are
not rendered on the screen by the operating system, the look, and feel of a
component does not change as the application or applet is executed on different
platforms running under different operating systems.
Furthermore, it is possible to cause Swing components to mimic the look and feel of
a specific platform no matter what platform the program is running on. This is known
as pluggable look and feel. Swing components support the JDK 1.1 Delegation Event
Model.
From an event handling point of view, Swing components operate the same as AWT
components except that Swing provides a number of new event types. Many Swing
components don't have an AWT counterpart. A number of new and exciting
components are included in the Swing library that doesn't exist in the AWT like
tooltips, progress bars, trees, etc.
If any method throws checked Exception, then the user can either handle this
exception by using the try-catch block or they can re-throw it by declaring another
‘throws’ clause during the declaration of methods.
The throw clause can be used in any part of the program like
throw
throw new Exception(“You have some exception”)
throw new IOException(“Connection failed!!”)
throws
throws IOException, NullPointerException, ArithmeticException
The above mentioned are some of the most asked Java interview questions.
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:
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, the 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.
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);)
2. What is Polymorphism?
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.
Eg:
class DemoOverload{
public int add(int x, int y){ //method 1
return x+y;
}
public int add(int x, int y, int z){ //method 2
return x+y+z;
}
public int add(double x, int y){ //method 3
return (int)x+y;
}
public int add(int x, double y){ //method 4
return x+(int)y;
}
}
class Test{
public static void main(String[] args){
DemoOverload demo=new DemoOverload();
out.println(demo.add(2,3)); //method 1 called
out.println(demo.add(2,3,4)); //method 2 called
out.println(demo.add(2,3.4)); //method 4 called
out.println(demo.add(2.5,3)); //method 3 called
}
}
Eg:
class Car{
void run(){System.out.println("running");}
}
class Audi extends Car{
void run(){System.out.println("Running safely with 70km");
}
publicstatic void main(String args[]){
Car c = new Audi(); //upcasting
run();
}
}
Output:
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{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
draw();
s=new Circle();
draw();
s=new Triangle();
draw();
}
}
Output:
drawing rectangle...
drawing circle...
drawing triangle...
5. What is a Servlet?
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( ).
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.
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.
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.
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.
Even if you don’t get placed during campus placements, it isn’t a big deal. The
experience itself teaches you a lot about what to expect during interviews, what the
interviewers want, etc. Just make sure you plan out your responses in the best way
possible and you will be good to go!