Java Interview Questions

Leave a Comment
Candidates who are looking for Java Interview questions can just follow the below questions given and read them which are mostly important questions asked in interviews. So prepare yourself with this questions well and make your dream job happen. for any queries comment below.

Java Interview Questions

Java Interview Questions

Java Interview Questions

Q: What do you know about Java ?
Ans. Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

Q.List any five features of Java ?
Ans. Some features include Object Oriented, Platform Independent, Robust, Interpreted, Multi-threaded.

Q. What do you mean by Object ?
Ans.  Object is a runtime entity and it’s state is stored in fields and behavior is shown via methods. Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication.

Q. What is the purpose of garbage collection in Java, and when is it used ?
Ans. The purpose of garbage collection is to identify and discard those objects that are no longer needed by the application, in order for the resources to be reclaimed and reused.It automatically deleted the unwanted data from the memory that's the best feature of Garbage Collector.

Q. What do you mean by class ?
Ans. A class is a blue print from which individual objects are created. A class can contain fields and methods to describe the behavior of an object.

Q. Why Java is considered dynamic ?
Ans.It is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

Q. List two Java IDE’s ?
Ans. Netbeans, Eclipse, etc.

 Q. What is a Local Variable ?
Ans. Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and it will be destroyed when the method has completed.

Q. What is a Instance Variable ?
Ans. Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded.

Q.  What is a Class Variable ?
Ans. These are variables declared with in a class, outside any method, with the static keyword.

Q. What do you mean by Constructor ?
Ans. Constructor gets invoked when a new object is created. Every class has a constructor. If we do not explicitly write a constructor for a class the java compiler builds a default constructor for that class.

 Q. What is a static variable ?
Ans. Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.

Q. What if the main method is declared as private ?
Ans. The program compiles properly but at runtime it will give “Main method not public.” message.

Q. What gives java it’s “write once and run anywhere” nature ?
Ans. Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.

Q.What are the basic interfaces of Java Collections Framework ?
Ans. Java Collection Framework provides a well designed set of interfaces and classes that support operations on a collections of objects. The most basic interfaces that reside in the Java Collections Framework are:

    Collection - which represents a group of objects known as its elements.
    Set -which is a collection that cannot contain duplicate elements.
    List -which is an ordered collection and can contain duplicate elements.
    Map - which is an object that maps keys to values and cannot contain duplicate keys.

Q. What is the difference between processes and threads ?
Ans. A process is an execution of a program, while a Thread is a single execution sequence within a process. A process can contain multiple threads.

Q. What is the Java API ?
Ans. The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

Q.Describe the principles of OOPS.
Ans. There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Q. What is the SimpleTimeZone class ?
Ans. The SimpleTimeZone class provides support for a Gregorian calendar.

Q. What is a native method ?
Ans. A native method is a method that is implemented in a language other than Java.

Q.What is the Java Virtual Machine (JVM) ?
Ans. The Java Virtual Machine is software that can be ported onto various hardware-based platforms

Q. What is Polymorphism ?
Ans. Polymorphism is the ability of programming languages to present the same interface for differing underlying data types. A polymorphic type is a type whose operations can also be applied to values of some other type.

Q. What is Encapsulation ?
Ans. Encapsulation provides objects with the ability to hide their internal characteristics and behavior. Each object provides a number of methods, which can be accessed by other objects and change its internal data. In Java, there are three access modifiers: public, private and protected. Each modifier imposes different access rights to other classes, either in the same or in external packages. Some of the advantages of using encapsulation are listed below:
The internal state of every objected is protected by hiding its attributes.
It increases usability and maintenance of code, because the behavior of an object can be independently changed or extended.
It improves modularity by preventing objects to interact with each other, in an undesired way.
Q. What is Abstraction ?
Ans. Abstraction is the process of separating ideas from specific instances and thus, develop classes in terms of their own functionality, instead of their implementation details. Java supports the creation and existence of abstract classes that expose interfaces, without including the actual implementation of all methods.

Q. Differences between Abstraction and Encapsulation ?
Ans. Abstraction and encapsulation are complementary concepts. On the one hand, abstraction focuses on the behavior of an object. On the other hand, encapsulation focuses on the implementation of an object’s behavior. Encapsulation is usually achieved by hiding information about the internal state of an object and thus, can be seen as a strategy used in order to provide abstraction.

Q. What is the ResourceBundle class ?
Ans. The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.

Q. What is the difference between processes and threads ?
Ans. A process is an execution of a program, while a Thread is a single execution sequence within a process. A process can contain multiple threads. A Thread is sometimes called a lightweight process.

Q. What’s a deadlock ?
Ans. A condition that occurs when two processes are waiting for each other to complete, before proceeding. The result is that both processes wait endlessly.

Q. What is difference between Array and ArrayList ?
Ans. The Array and ArrayList classes differ on the following features:
   Arrays can contain primitive or objects, while an ArrayList can contain only objects.
   Arrays have fixed size, while an ArrayList is dynamic.
   An ArrayListprovides more methods and features, such as addAll, removeAll, iterator, etc.
   For a list of primitive data types, the collections use autoboxing to reduce the coding effort.      
However, this approach makes them slower when working on fixed size primitive data types.
Q.What do you know about the big-O notation ?
Ans. The Big-O notation simply describes how well an algorithm scales or performs in the worst case scenario as the number of elements in a data structure increases. The Big-O notation can also be used to describe other behavior such as memory consumption.

Q. What is the purpose of finalization ?
Ans.  The finalize method is called by the garbage collector, just before releasing the object’s memory. It is normally advised to release resources held by the object inside the finalize method.

Q. What is a native method ?
Ans. A native method is a method that is implemented in a language other than Java.

Q. What do you understand by a variable ?
Ans. Variable is a named memory location that can be easily referred in the program. The variable is used to hold the data and it can be changed during the course of the execution of the program.
Q. What are the two types of Exceptions in Java ?
Ans. Java has two types of exceptions: checked exceptions and unchecked exceptions. Unchecked exceptions do not need to be declared in a method or a constructor’s throws clause, if they can be thrown by the execution of the method or the constructor, and propagate outside the method or constructor boundary. On the other hand, checked exceptions must be declared in a method or a constructor’s throws clause. See here for tips on Java exception handling.

Q. When parseInt() method can be used ?
Ans. This method is used to get the primitive data type of a certain String.

Q. Can you have multiple main methods in the same class ?
Ans.  We can have multiple overloaded main methods but there can be only one main method with the following signature :

public static void main(String[] args)

Q. What is finalize() method ?
Ans. It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.

Q. What is an Exception ?
Ans. An exception is a problem that arises during the execution of a program. Exceptions are caught by handlers positioned along the thread's method invocation stack.

Q. Explain Runtime Exceptions ?
Ans. It is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.

Q. When throws keyword is used ?
Ans. An exception can be thrown, either a newly instantiated one or an exception that you just caught, by using throw keyword.

Q. What is Inheritance ?
Ans. It is the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.

Q. When super keyword is used ?
Ans. If the method overrides one of its superclass's methods, overridden method can be invoked through the use of the keyword super. It can be also used to refer to a hidden field.

Q. What is an Interface ?
Ans. An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

Q.Give some features of Interface ?
Ans. It includes:
    Interface cannot be instantiated
    An interface does not contain any constructors.
    All of the methods in an interface are abstract.
Q. Define Packages in Java ?
Ans. A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations ) providing access protection and name space management.

Q. Why Packages are used ?
Ans. Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations, etc., easier.

Q. What do you mean by Multithreaded program ?
Ans. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

Q.What are the two ways in which Thread can be created ?
Ans.Thread can be created by: implementing Runnable interface, extending the Thread class.

Q.What is an applet ?
Ans. An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API at its disposal.

Q. Explain the life cycle of an Applet ?
Ans. An applet may undergo the following states:
    Init: An applet is initialized each time is loaded.
    Start: Begin the execution of an applet.
    Stop: Stop the execution of an applet.
    Destroy: Perform a final cleanup, before unloading the applet.
 Q. Explain the usage of this() with constructors ?
Ans. It is used with variables or methods and used to call constructer of same class.

Q. Explain TreeSet ?
Ans. It is a Set implemented when we want elements in a sorted order.

Q. Difference between throw and throws ?
Ans. It Includes:
    Throw is used to trigger an exception where as throws is used in declaration of exception.
    Without throws, Checked exception cannot be handled where as checked exception can be propagated with throws.
Q. Define JRE - Java Runtime Environment ?
Ans. Java Runtime Environment is an implementation of the Java Virtual Machine which executes Java programs. It provides the minimum requirements for executing a Java application.

Q. What is a WAR file ?
Ans. This is Web Archive File and used to store XML, java classes, and JavaServer pages. which is used to distribute a collection of JavaServer Pages, Java Servlets, Java classes, XML files, static Web pages etc.

Q. What is JAR file?
Ans. AR files is Java Archive fles and it aggregates many files into one. It holds Java classes in a library. JAR files are built on ZIP file format and have .jar file extension.

Q. Can a constructor be made final ?
Ans.  No, this is not possible.

 Q. What is JDBC ?
Ans. JDBC is an abstraction layer that allows users to choose between databases. JDBC enables developers to write database applications in Java, without having to concern themselves with the underlying details of a particular database.

Q. What is the purpose Class.forName method ?
Ans. This method is used to method is used to load the driver that will establish a connection to the database.

Q. What is static block ?
Ans. It is used to initialize the static data member, It is excuted before main method at the time of classloading.
Q. What is function overloading ?
Ans. If a class has multiple functions by same name but different parameters, it is known as Method Overloading.

Q. What is function overriding ?
Ans.  If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding.

Q. Difference between Overloading and Overriding ?
Ans.  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 parameter must be different in case of overloading, parameter must be same in case of overriding.

Q. What is NullPointerException ?
Ans. A NullPointerException is thrown when calling the instance method of a null object, accessing or modifying the field of a null object etc.

Q. What invokes a thread's run() method ?
Ans. After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

Q. What are Wrapper classes ?
Ans. These are classes that allow primitive types to be accessed as objects. Example: Integer, Character, Double, Boolean etc.

Q. What is the difference between the paint() and repaint() methods ?
Ans. The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

Q. What is the purpose of File class ?
Ans. It is used to create objects that provide access to the files and directories of a local file system.

Q. What is Serialization and deserialization ?
Ans. Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

Q. What is a Servlet ?
Ans. The servlet is a Java programming language class used to process client requests and generate dynamic web content. Servlets are mostly used to process or store data submitted by an HTML form, provide dynamic content and manage state information that does not exist in the stateless HTTP protocol.

Q. Explain the life cycle of a Servlet ?
Ans. On every client’s request, the Servlet Engine loads the servlets and invokes its init methods, in order for the servlet to be initialized. Then, the Servlet object handles all subsequent requests coming from that client, by invoking the service method for each request separately. Finally, the servlet is removed by calling the server’s destroy method.

Q. What is the difference between doGet() and doPost() ?
Ans. doGET: The GET method appends the name-value pairs on the request’s URL. Thus, there is a limit on the number of characters and subsequently on the number of values that can be used in a client’s request. Furthermore, the values of the request are made visible and thus, sensitive information must not be passed in that way. doPOST: The POST method overcomes the limit imposed by the GET request, by sending the values of the request inside its body. Also, there is no limitations on the number of values to be sent across. Finally, the sensitive information passed through a POST request is not visible to an external client.

Q. What is meant by a Web Application ?
Ans. A Web application is a dynamic extension of a Web or application server. There are two types of web applications: presentation-oriented and service-oriented.

Q. What is a Server Side Include (SSI) ?
Ans. Server Side Includes (SSI) is a simple interpreted server-side scripting language, used almost exclusively for the Web, and is embedded with a servlet tag. The most frequent use of SSI is to include the contents of one or more files into a Web page on a Web server. When a Web page is accessed by a browser, the Web server replaces the servlet tag in that Web page with the hyper text generated by the corresponding servlet.

Q. What is Servlet Chaining ?
Ans. Servlet Chaining is the method where the output of one servlet is sent to a second servlet. The output of the second servlet can be sent to a third servlet, and so on. The last servlet in the chain is responsible for sending the response to the client.

Q. Can you write a Java class that could be used both as an applet as well as an application ?
Ans.  Yes, just add a main() method to the applet.

Q. What's the difference between constructors and other methods ?
Ans. Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

Q. Can you call one constructor from another if a class has multiple constructors ?
Ans. Yes, use this() syntax.

Q. What's the difference between the methods sleep() and wait() ?
Ans. The code sleep(2000); puts thread aside for exactly two seconds. The code wait(2000), causes a wait of up to two second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

Q. What is synchronization ?
Ans. Synchronization is the capability to control the access of multiple threads to shared resources. synchronized keyword in java provides locking which ensures mutual exclusive access of shared resource and prevent data race.

Q. What is the difference between session and cookie ?
Ans. A cookie is a bit of information that the Web server sends to the browser. The browser stores the cookies for each Web server in a local file. In a future request, the browser, along with the request, sends all stored cookies for that specific Web server.The differences between session and a cookie are the following:
 The session should work, regardless of the settings on the client browser. The client may have   chosen to disable cookies. However, the sessions still work, as the client has no ability to disable them in the server side.
The session and cookies also differ in the amount of information the can store. The HTTP session is  capable of storing any Java object, while a cookie can only store String objects.
Q. Which protocol will be used by browser and servlet to communicate ?
Ans. The browser communicates with a servlet by using the HTTP protocol.

Q.  What is HTTP Tunneling ?
Ans. HTTP Tunneling is a technique by which, communications performed using various network protocols are encapsulated using the HTTP or HTTPS protocols.

Q. What is URL Encoding and URL Decoding ?
Ans. The URL encoding procedure is responsible for replacing all the spaces and every other extra special character of a URL, into their corresponding Hex representation. In correspondence, URL decoding is the exact opposite procedure.

Q. What is the Collections API ?
Ans. The Collections API is a set of classes and interfaces that support operations on collections of objects.

Q.Which Java operator is right associative ?
Ans. The = operator is right associative.

Q. List primitive Java types ?
Ans. The eight primitive types are byte, char, short, int, long, float, double, and boolean.

Q. What class of exceptions are generated by the Java run-time system ?
Ans.The Java runtime system generates RuntimeException and Error exceptions.

Q. How can a dead thread be restarted ?
Ans. No,a dead thread cannot be restarted.

Q.Can try statements be nested ?
Ans. Yes, It can be nested.

Q. What are ClassLoaders ?
Ans. A class loader is an object that is responsible for loading classes. The class ClassLoader is an abstract class.

Q. Why do we need wrapper classes ?
Ans. We can pass them around as method parameters where a method expects an object. It also provides utility methods.

Q. Can constructor be inherited ?
Ans. No, constructor cannot be inherited.

Q. What is dot operator ?
Ans. The dot operator(.) is used to access the instance variables and methods of class objects.It is also used to access classes and sub-packages from a package.

Q. Describe life cycle of thread ?
Ans. A thread is a execution in a program. The life cycle of a thread include:
    Newborn state
    Runnable state
    Running state
    Blocked state
    Dead state
Q. What is the difference between the >> and >>> operators ?
Ans. The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

Q. Explain isAlive() method under Thread class ?
Ans. It is used to find out whether a thread is still running or not.

Q. What is currentThread() ?
Ans.  It is a public static method used to obtain a reference to the current thread.

Q. What is a JSP Page ?
Ans. A Java Server Page (JSP) is a text document that contains two types of text: static data and JSP elements. Static data can be expressed in any text-based format, such as HTML or XML.

Q. What are the advantages of JSP ?
Ans. Advantages of using the JSP are as follows:
 JSP pages are dynamically compiled into servlets and thus, the developers can easily make updates to presentation code.
JSP pages can be pre-compiled.
JSP pages can be easily combined to static templates, including HTML or XML fragments, with code that generates dynamic content.
 Developers can offer customized JSP tag libraries that page authors access using an XML-like syntax.
 Developers can make logic changes at the component level, without editing the individual pages that use the application’s logic.

Q. What are the different types of Directives available in JSP ?
Ans.  Directives are instructions that are processed by the JSP engine, when the page is compiled to a servlet. Directives are used to set page-level instructions, insert data from external files, and specify custom tag libraries. Directives are defined between < %@ and % >.The different types of directives are shown below:
   Include directive: it is used to include a file and merges the content of the file with the current page.
    Page directive: it is used to define specific attributes in the JSP page, like error page and buffer.
    Taglib: it is used to declare a custom tag library which is used in the page.

Q. What are JSP actions ?
Ans. JSP actions use constructs in XML syntax to control the behavior of the servlet engine. JSP actions are executed when a JSP page is requested. They can be dynamically inserted into a file, re-use JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.Some of the available actions are listed below:
    jsp:include – includes a file, when the JSP page is requested.
    jsp:useBean – finds or instantiates a JavaBean.
    jsp:setProperty – sets the property of a JavaBean.
    jsp:getProperty – gets the property of a JavaBean.
    jsp:forward – forwards the requester to a new page.
    jsp:plugin – generates browser-specific code.

Q.What are Scriptlets ?
Ans. Java Server Pages (JSP) technology, a scriptlet is a piece of Java-code embedded in a JSP page. The scriptlet is everything inside the tags. Between these tags, a user can add any valid scriplet.

Q. What are Decalarations ?
Ans.  Declarations are similar to variable declarations in Java. Declarations are used to declare variables for subsequent use in expressions or scriptlets. To add a declaration, you must use the sequences to enclose your declarations.

Q. What is meant by implicit objects and what are they ?
Ans. JSP implicit objects are those Java objects that the JSP Container makes available to developers in each page. A developer can call them directly, without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.

Q. What are Expressions ?
Ans.   A JSP expression is used to insert the value of a scripting language expression, converted into a string, into the data stream returned to the client, by the web server. Expressions are defined between <% = and %> tags.

Q.  Define canvas ?
Ans. It is a simple drawing surface which are used for painting images or to perform other graphical operations.

Q. Define Network Programming ?
Ans. It refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

Q. What is a Socket ?
Ans. Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.

Q: Advantages of Java Sockets?
Ans. Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. It cause low network traffic.

Q. Disadvantages of Java Sockets ?
Ans. Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

Q. What is daemon thread ?
Ans. Daemon thread is a low priority thread, which runs intermittently in the back ground doing the garbage collection operation for the java runtime system.

Q. What is an enumeration ?
Ans.  An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It allows sequential access to all the elements stored in the collection.

Q. What is difference between Path and Classpath ?
Ans. Path and Classpath are operating system level environment variales. Path is defines where the system can find the executables(.exe) files and classpath is used to specify the location of .class files.

Q. What restrictions are placed on method overriding ?
Ans. Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides.

Q. What is phantom memory ?
Ans. Phantom memory is false memory. Memory that does not exist in reality.

Q.  What is DGC ?
Ans. DGC stands for Distributed Garbage Collection. Remote Method Invocation (RMI) uses DGC for automatic garbage collection. Since RMI involves remote object references across JVM’s, garbage collection can be quite difficult. DGC uses a reference counting algorithm to provide automatic memory management for remote objects .

Q. Difference between Swing and Awt ?
Ans. AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

Q. What is an Iterator ?
Ans. Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

we have covered mostly all the frequently asked questions for the interview. students can prepare themselves well for the interview and if you have any questions or queries related to Java interview questions comment below.

No comments:

Post a Comment



Get latest updates


Proud to be an Indian

We are on Facebook