Java top Interview Questions and latestanswers by RVH Techguru experts

Top most important Java interview questions and answers by Experts:

Here is a list of Top most important Java interview questions and answers by Experts.If you want to download Java interview questions pdf free ,you can register with RVH techguru. Our experts prepared these Java interview questions to accommodate freshers level to most experienced level technical interviews.

If you want to become an expert in Java ,Register for Java online training here.

 

 

1) What is difference between JDK,JRE and JVM?
JVM
JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which java bytecode can be executed. It is a specification.
JVMs are available for many hardware and software platforms (so JVM is platform dependent).
JRE
JRE stands for Java Runtime Environment. It is the implementation of JVM.
JDK
JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.
2) 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
3) What is JIT compiler?.
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.
4) What is platform?

A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform.
5) What is the main difference between Java platform and other platforms?
The Java platform differs from most other platforms in the sense that it’s a software-based platform that runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
6) What gives Java its ‘write once and run anywhere’ nature?
The bytecode. Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be fed to any platform.
7) What is class loader?
The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.
8) Is Empty .java file name a valid source file name?
Yes, save your java file by .java only, compile it by javac .java and run by java yourclassname Let’s take a simple example:
1. //save by .java only
2. class A{
3. public static void main(String args[]){
4. System.out.println(“Hello java”);
5. }
6. }
7. //compile by javac .java
8. //run by java A
compile it by javac .java
run it by java A
9) Is delete,next,main,exit or null keyword in java?
No.
10) If I don’t provide any arguments on the command line, then the String array of Main method will be empty or null?.
It is empty. But not null.
11) What if I write static public void instead of public static void?
Program compiles and runs properly.
12) What is the default value of the local variables?
The local variables are not initialized to any default value, neither primitives nor object references.
13) What is difference between object oriented programming language and object based programming language?
Object based programming languages follow all the features of OOPs except Inheritance. Examples of object based programming languages are JavaScript, VBScript etc.
14) What will be the initial value of an object reference which is defined as an instance variable?
The object references are all initialized to null in Java.
15) 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.
16) What is the purpose of default constructor?
• The default constructor provides the default values to the objects. The java compiler creates a default constructor only if there is no constructor in the class.

17) Does constructor return any value?
yes, that is current instance (You cannot use return type yet it returns a value)
18)Is constructor inherited?
No, constructor is not inherited.

19) Can you make a constructor final?
No, constructor can’t be final.
20) 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.
21) What is 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.

22) Why main method is static?
because object is not required to call static method if It were non-static method,jvm creats object first then call main() method that will lead to the problem of extra memory allocation 
23) What is static block?
• Is used to initialize the static data member.
• It is executed before main method at the time of classloading.
24) Can we execute a program without main() method?
Yes, one of the way is static block.
25) What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error “NoSuchMethodError”.

26) What is this in java?
It is a keyword that that refers to the current object.
27)What is Inheritance?
Inheritance is a mechanism in which one object acquires all the properties and behaviour of another object of another class. It represents IS-A relationship. It is used for Code Resusability and Method Overriding.
28) Which class is the super class for every class.
Object class.
29) Why multiple inheritance is not supported in java?
• To reduce the complexity and simplify the language, multiple inheritance is not supported in java in case of class.
30) What is composition?
Holding the reference of the other class within some other class is known as composition.
31) What is difference between aggregation and composition?
Aggregation represents weak relationship whereas composition represents strong relationship. For example: bike has an indicator (aggregation) but bike has an engine (compostion).
32) Why Java does not support pointers?
Pointer is a variable that refers to the memory address. They are not used in java because they are unsafe(unsecured) and complex to understand.
33) What is super in java?
It is a keyword that refers to the immediate parent class object.
34) Can you use this() and super() both in a constructor?
No. Because super() or this() must be the first statement.
35)What is object cloning?
The object cloning is used to create the exact copy of an object.
36) What is method overloading?
If a class have multiple methods by same name but different parameters, it is known as Method Overloading. It increases the readability of the program.
37) Why method overloading is not possible by changing the return type in java?
Because of ambiguity.
38) Can we overload main() method?
Yes, You can have many main() methods in a class by overloading the main method.
39) What is method overriding:
If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to provide the specific implementation of the method.

40) Can we override static method?
No, you can’t override the static method because they are the part of class not object.
41) Why we cannot override static method?
It is because the static method is the part of class and it is bound with class whereas instance method is bound with object and static gets memory in class area and instance gets memory in heap.
42) Can we override the overloaded method?
Yes.
43) Difference between method Overloading and Overriding.

Method Overloading Method Overriding
1) Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its super class.
2) method overlaoding is occurs within the class. Method overriding occurs in two classes that have IS-A relationship.
3) In this case, parameter must be different. In this case, parameter must be same.
44) Can you have virtual functions in Java?
Yes, all functions in Java are virtual by default.
45) What is covariant return type?
Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type.
46) What is Runtime Polymorphism?
Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time.
In this process, an overridden method is called through the reference variable of a super class. The determination of the method to be called is based on the object being referred to by the reference variable.

47) What is the difference between static binding and dynamic binding?
In case of static binding type of object is determined at compile time whereas in dynamic binding type of object is determined at runtime.
48) What is abstraction?
Abstraction is a process of hiding the implementation details and showing only functionality to the user.

49) What are the advantages of JdbcTemplate in spring?
Less code: By using the JdbcTemplate class, you don’t need to create connection,statement,start transaction,commit transaction and close connection to execute different queries. You can execute the query directly.

50) Multiple inheritance is not supported through class in java but it is possible by interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class. But it is supported in case of interface because there is no ambiguity as implementation is provided by the implementation class. For example:
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestTnterface1 implements Printable,Showable{
9. public void print(){System.out.println(“Hello”);}
10. public static void main(String args[]){
11. TestTnterface1 obj = new TestTnterface1();
12. obj.print();
13. }
14. }
Test it Now
Hello
As you can see in the above example, Printable and Showable interface have same methods but its implementation is provided by class TestTnterface1, so there is no ambiguity.

Interface inheritance
A class implements interface but one interface extends another interface .
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class Testinterface2 implements Showable{
8.
9. public void print(){System.out.println(“Hello”);}
10. public void show(){System.out.println(“Welcome”);}
11.
12. public static void main(String args[]){
13. Testinterface2 obj = new Testinterface2();
14. obj.print();
15. obj.show();
16. }
17. }
Test it Now
Hello
Welcome

51) What is marker or tagged interface?
An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.
1. //How Serializable interface is written?
2. public interface Serializable{
3. }

Nested Interface in Java
Note: An interface can have another interface i.e. known as nested interface. We will learn it in detail in the nested classes chapter. For example:
1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }
More about Nested Interface
Next TopicDifference between Abstract class and interface
52) Can there be any abstract method without abstract class?
No, if there is any abstract method in a class, that class must be abstract.
53) Can you use abstract and final both with a method?
No, because abstract method needs to be overridden whereas you can’t override final method.
54) Is it possible to instantiate the abstract class?
No, abstract class can never be instantiated.
55) What is interface?
Interface is a blueprint of a class that have static constants and abstract methods. It can be used to achieve fully abstraction and multiple inheritance.
56) Can you declare an interface method static?
No, because methods of an interface is abstract by default, and static and abstract keywords can’t be used together.
57) Can an Interface be final?
No, because its implementation is provided by another class.

58) Why use java finally
o Finally block in java can be used to put “cleanup” code such as closing a file, closing connection etc.
Usage of Java finally
Let’s see the different cases where java finally block can be used.
Case 1
Let’s see the java finally example where exception doesn’t occur.
1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println(“finally block is always executed”);}
9. System.out.println(“rest of the code…”);
10. }
11. }
Test it Now
Output:5
finally block is always executed
rest of the code…
Case 2
Let’s see the java finally example where exception occurs and not handled.
1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println(“finally block is always executed”);}
9. System.out.println(“rest of the code…”);
10. }
11. }
Test it Now
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let’s see the java finally example where exception occurs and handled.
1. public class TestFinallyBlock2{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8. finally{System.out.println(“finally block is always executed”);}
9. System.out.println(“rest of the code…”);
10. }
11. }
Test it Now
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code…

59) What is the basic difference between string and stringbuffer object?
String is an immutable object. StringBuffer is a mutable object.

60) What is the difference between StringBuffer and StringBuilder ?
StringBuffer is synchronized whereas StringBuilder is not synchronized.

61) What is the purpose of toString() method in java ?
The toString() method returns the string representation of any object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.
62) How many objects of a servlet is created?
Only one object at the time of first request by servlet or web container.
63) What is the life-cycle of a servlet?
1. Servlet is loaded
2. servlet is instantiated
3. servlet is initialized
4. service the request
5. servlet is destroyed
64) What is difference between PrintWriter and ServletOutputStream?
PrintWriter is a character-stream class where as ServletOutputStream is a byte-stream class. The PrintWriter class can be used to write only character-based information whereas ServletOutputStream class can be used to write primitive values as well as character-based information.

65) What is difference between GenericServlet and HttpServlet?
The GenericServlet is protocol independent whereas HttpServlet is HTTP protocol specific. HttpServlet provides additional functionalities such as state management etc.

66) What is servlet collaboration?
When one servlet communicates to another servlet, it is known as servlet collaboration. There are many ways of servlet collaboration:
• RequestDispacher interface
• sendRedirect() method etc.
67) What is the purpose of RequestDispatcher Interface?
The RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interceptor can also be used to include the content of antoher resource.
68) Can you call a jsp from the servlet?
Yes, one of the way is RequestDispatcher interface for example:
1. RequestDispatcher rd=request.getRequestDispatcher(“/login.jsp”);
2. rd.forward(request,response);

69) What is difference between ServletConfig and ServletContext?
The container creates object of ServletConfig for each servlet whereas object of ServletContext is created for each web application.
70) What is Session Tracking?
Session simply means a particular interval of time.
Session Tracking is a way to maintain state of an user.Http protocol is a stateless protocol.Each time user requests to the server, server treats the request as the new request.So we need to maintain the state of an user to recognize to particular user.
71) What are Cookies?
A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
72) What is difference between Cookies and HttpSession?
Cookie works at client side whereas HttpSession works at server side.
73) What is filter?
A filter is an object that is invoked either at the preprocessing or postprocessing of a request. It is pluggable.
74) How can we perform any action at the time of deploying the project?
By the help of ServletContextListener interface.
75) What is the disadvantage of cookies?
It will not work if cookie is disabled from the browser.

76) How can we upload the file to the server using servlet?
One of the way is by MultipartRequest class provided by third party.

77) What is load-on-startup in servlet?
The load-on-startup element of servlet in web.xml is used to load the servlet at the time of deploying the project or server start. So it saves time for the response of first request.