Join Regular Classroom : Visit ClassroomTech

Java Interview Questions

Q1. What is Encapsulation?

Answer 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.
You can refer to our tutorial here for more details and examples on encapsulation.

Q2. What is Polymorphism?

Answer 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.

Q3. What is Inheritance?

Answer Inheritance provides an object with the ability to acquire the fields and methods of another class, called base class. Inheritance provides re-usability of code and can be used to add additional features to an existing class, without modifying it.

Q4. What is Abstraction?

Answer 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. The abstraction technique aims to separate the implementation details of a class from its behavior.

Q5. Differences between Abstraction and Encapsulation
Answer 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.

Q6. Can there be an abstract class with no abstract methods in it?
Answer Yes

 

 

Q7. Can an Interface be final?
Answer No

 

 

Q8. Can an Interface have an inner class?
Answer Yes.

Example: 

public interface abc {
static int i=0;
void dd();
class a1 {
a1() {
int j;
System.out.println("in interfia");
};
public static void main(String a1[])
{
System.out.println("in interfia");
}
}
}

Q9. Can there be an abstract class with no abstract methods in it?
Answer Yes

Q10. Can an Interface be final?
Answer No

Q11. Can we define private and protected modifiers for variables in interfaces?
Answer No

Q12. What is the query used to display all tables names in SQL Server (Query analyzer)?
Answer select * from information_schema.tables

Q13. What is Externalizable?
Answer Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

Q14. What modifiers are allowed for methods in an Interface?
Answer Only public and abstract modifiers are allowed for methods in interfaces.

Q15. What is a local, member and a class variable?
Answer Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables). Variables declared within the class i.e not within any methods and are defined as “static” are class variables

Q16. How many types of JDBC Drivers are present and what are they?
Answer There are 4 types of JDBC Drivers
Type 1: JDBC-ODBC Bridge Driver
Type 2: Native API Partly Java Driver
Type 3: Network protocol Driver
Type 4: JDBC Net pure Java Driver

 

 

Q17. Can we implement an interface in a JSP?
Answer No

 

 

Q18. What is the difference between ServletContext and PageContext?
Answer
ServletContext: Gives the information about the container
PageContext: Gives the information about the Request

 

 

Q19. What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
Answer request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.

 

 

Q20. How to pass information from JSP to included JSP?
Answer Using <%jsp:param> tag.


Q21. What is the difference between directive include and jsp include?

Answer <%@ include> : Used to include static resources during translation time.
: Used to include dynamic content or static content during runtime.

 

 

Q22. What is the difference between RequestDispatcher and sendRedirect?
Answer RequestDispatcher: server-side redirect with request and response objects.
sendRedirect : Client-side redirect with new request and response objects.

 

 

Q23. How does JSP handle runtime exceptions?
Answer Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.

 

 

Q24. How do you delete a Cookie within a JSP?
Answer: 

Cookie mycook = new Cookie("name","value");
response.addCookie(mycook);
Cookie killmycook = new Cookie("mycook","value");
killmycook.setMaxAge(0);
killmycook.setPath("/");
killmycook.addCookie(killmycook);


Q25. What is Function Overriding and Overloading in Java ?

Answer Method overloading in Java occurs when two or more methods in the same class have the exact same name, but different parameters. On the other hand, method overriding is defined as the case when a child class redefines the same method as a parent class. 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.

Q26. What is a Constructor, Constructor Overloading in Java and Copy-Constructor
Answer A constructor gets invoked when a new object is created. Every class has a constructor. In case the programmer does not provide a constructor for a class, the Java compiler (Javac) creates a default constructor for that class. The constructor overloading is similar to method overloading in Java. Different constructors can be created for a single class. Each constructor must have its own unique parameter list. Finally, Java does support copy constructors like C++, but the difference lies in the fact that Java doesn’t create a default copy constructor if you don’t write your own.

Q27. Does Java support multiple inheritance ?
Answer No, Java does not support multiple inheritance. Each class is able to extend only on one class, but is able to implement more than one interfaces. That means Multiple inheritance can be achieved using interface.


Q28. What is the difference between an Interface and an Abstract class ?

Answer Java provides and supports the creation both of abstract classes and interfaces. Both implementations share some common
characteristics, but they differ in the following features:
• All methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and nonabstract methods.
• A class may implement a number of Interfaces, but can extend only one abstract class.
• In order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the sub-class must also be declared as abstract.
• Abstract classes can implement interfaces without even providing the implementation of interface methods.
• Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
• Members of a Java interface are public by default. A member of an abstract class can either be private, protected or public.
• An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be invoked if it contains a main method.

Q29. What are pass by reference and pass by value ?

Answer When an object is passed by value, this means that a copy of the object is passed. Thus, even if changes are made to that object, it doesn’t affect the original value. When an object is passed by reference, this means that the actual object is not passed, rather a reference of the object is passed. Thus, any changes made by the external method, are also reflected in all places.

Exception handling Interview Questions


Q) What is an exception?

Exceptions are abnormal conditions that arise during execution of the program. It may occur due to wrong user input or wrong logic written by programmer.

Q) Exceptions are defined in which java package? OR which package has definitions for all the exception classes?

Java.lang.Exception
This package contains definitions for Exceptions.

Q) What are the types of exceptions?

There are two types of exceptions: checked and unchecked exceptions.
Checked exceptions: These exceptions must be handled by programmer otherwise the program would throw a compilation error.
Unchecked exceptions: It is up to the programmer to write the code in such a way to avoid unchecked exceptions. You would not get a compilation error if you do not handle these exceptions. These exceptions occur at runtime.

Q) What is the difference between Error and Exception?

Error: Mostly a system issue. It always occur at run time and must be resolved in order to proceed further.
Exception: Mostly an input data issue or wrong logic in code. Can occur at compile time or run time.

Q) What is throw keyword in exception handling?

The throw keyword is used for throwing user defined or pre-defined exception.

Q) What is throws keyword?

If a method does not handle a checked exception, the method must declare it using the throwskeyword. The throws keyword appears at the end of a method’s signature.

Q) Can static block throw exception?

Yes, A static block can throw exceptions. It has its own limitations: It can throw only Runtime exception (Unchecked exceptions), In order to throw checked exceptions you can use a try-catch block inside it.

Q) What is finally block?

Finally block is a block of code that always executes, whether an exception occurs or not. Finally block follows try block or try-catch block.

Q) ClassNotFoundException vs NoClassDefFoundError?
1) ClassNotFoundException occurs when loader could not find the required class in class path.
2) NoClassDefFoundError occurs when class is loaded in classpath, but one or more of the class which are required by other class, are removed or failed to load by compiler.

Q) Can we have a try block without catch or finally block?

No, we cannot have a try block without catch or finally block. We must have either one of them or both.

Q) Can we have multiple catch blocks following a single try block?

Yes we can have multiple catch blocks in order to handle more than one exception.

Q) Is it possible to have finally block without catch block?

Yes, we can have try block followed by finally block without even using catch blocks in between.

When a finally block does not get executed?

The only time finally won’t be called is if you call System.exit() or if the JVM crashes first.

Q) Can we handle more than one exception in a single catch block?

Yes we can do that using if-else statement but it is not considered as a good practice. We should have one catch block for one exception.

Q) What is a Java Bean?

A JavaBean is a Java class that follows some simple conventions including conventions on the names of certain methods to get and set state called Introspection. Because it follows conventions, it can easily be processed by a software tool that connects Beans together at runtime. JavaBeans are reusable software components.

Java Multithreading Interview Questions

Q) What is Multithreading?

It is a process of executing two or more part of a program simultaneously. Each of these parts is known as threads. In short the process of executing multiple threads simultaneously is known as multithreading.

Q) What is the main purpose of having multithread environment?

Maximizing CPU usage and reducing CPU idle time

Q) What are the main differences between Process and thread? Explain in brief.

1)  One process can have multiple threads. A thread is a smaller part of a process.
2)  Every process has its own memory space, executable code and a unique process identifier (PID) while every thread has its own stack in Java but it uses process main memory and shares it with other threads.
3) Threads of same process can communicate with each other using keyword like wait and notify etc. This process is known as inter process communication.

Q) How can we create a thread in java?

There are following two ways of creating a thread:
1)  By Implementing Runnable interface.
2)  By Extending Thread class.

Q) Explain yield and sleep?

yield() – It causes the currently executing thread object to temporarily pause and allow other threads to execute.

sleep() – It causes the current thread to suspend execution for a specified period. When a thread goes into sleep state it doesn’t release the lock.

Q) What is the difference between sleep() and wait()?

sleep() – It causes the current thread to suspend execution for a specified period. When a thread goes into sleep state it doesn’t release the lock

wait() – It causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

Q) What is a daemon thread?

A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.

Q) What does join( ) method do?

if you use join() ,it makes sure that as soon as a thread calls join,the current thread(yes,currently running thread) will not execute unless the thread you have called join is finished.

Q) Preemptive scheduling vs. time slicing?

1) The preemptive scheduling is prioritized. The highest priority process should always be the process that is currently utilized.
2) Time slicing means task executes for a defined slice/ period of time and then enter in the pool of ready state. The scheduler then determines which task execute next based on priority or other factor.

Q) Can we call run() method of a Thread class?

Yes, we can call run() method of a Thread class but then it will behave like a normal method. To actually execute it in a Thread, you should call Thread.start() method to start it.

Q) What is Starvation?

Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by “greedy” threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.

Q) What is deadlock?

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.

Serialization interview Questions

Q: What is Serialization and de-serialization?

Serialization is a process of converting an object and its attributes to the stream of bytes. De-serialization is recreating the object from stream of bytes; it is just a reverse process of serialization. To know more about serialization with example program.

Q) Do we need to implement any method of Serializable interface to make an object serializable?

No. In order to make an object serializable we just need to implement the interface Serializable. We don’t need to implement any methods.

Q) What is a transient variable?

1) transient variables are not included in the process of serialization.
2) They are not the part of the object’s serialized state.
3) Variables which we don’t want to include in serialization are declared as transient.

String interview questions

Q) A string class is immutable or mutable?

String class is immutable that’s the reason once its object gets created, it cannot be changed further.

Q) Difference between StringBuffer and StringBuilder class?

1) StringBuffer is thread-safe but StringBuilder is not thread safe.
2) StringBuilder is faster than StringBuffer.
3) StringBuffer is synchronized whereas StringBuilder is not synchronized.

Q) What is toString() method in Java?

The toString() method returns the string representation of any object.

Java collections interview questions

Q) What is List?

Elements can be inserted or accessed by their position in the list, using a zero-based index.
A list may contain duplicate elements.

Q) What is Map?

Map interface maps unique keys to values. A key is an object that we use to retrieve a value later. A map cannot contain duplicate keys: Each key can map to at most one value.

Q) What is Set?

A Set is a Collection that cannot contain duplicate elements.

Q) Why ArrayList is better than Arrays?

Array can hold fixed number of elements. ArrayList can grow dynamically.

Q) What is the difference between ArrayList and LinkedList?

1) LinkedList store elements within a doubly-linked list data structure. ArrayList store elements within a dynamically resizing array.
2) LinkedList is preferred for add and update operations while ArrayList is a good choice for search operations.

Q) For addition and deletion. Which one is most preferred: ArrayList or LinkedList?

LinkedList. Because deleting or adding a node in LinkedList is faster than ArrayList.

Q) For searches. Which one is most preferred: ArrayList or LinkedList?

ArrayList. Searching an element is faster in ArrayList compared to LinkedList.

Q) What is the difference between ArrayList and Vector?

1) Vector is synchronized while ArrayList is not synchronized.
2) By default, Vector doubles the size of its array when it is re-sized internally. ArrayList increases by half of its size when it is re-sized.

Q) What is the difference between Iterator and ListIterator?

Following are the major differences between them:
1) Iterator can be used for traversing Set, List and Map. ListIterator can only be used for traversing a List.
2) We can traverse only in forward direction using Iterator. ListIterator can be used for traversing in both the directions(forward and backward). 

Q) Difference between TreeSet and SortedSet?

TreeSet implements SortedSet interface.

Q) What is the difference between HashMap and Hashtable?

1) Hashtable is synchronized. HashMap is not synchronized.
2) Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. 

Q) What is the difference between Iterator and Enumeration?

1) Iterator allows to remove elements from the underlying collection during the iteration using its remove() method. We cannot add/remove elements from a collection when using enumerator.
2) Iterator has improved method names.
Enumeration.hasMoreElement() -> Iterator.hasNext()
Enumeration.nextElement() -> Iterator.next().

Applet Interview Questions

Q) How do you do file I/O from an applet?

Unsigned applets are simply not allowed to read or write files on the local file system .

Unsigned applets can, however, read (but not write) non-class files bundled with your applet on the server, called resource files

Q) What is container ?

A component capable of holding another component is called as container.
Container
Panel
Applet
Window
Frame
Dialog

Q) On Windows, generally frames are invisible, how to make it visible?

Frame f = new Frame(); f.setSize(300,200); //height and width f.setVisible(true) ; // Frames appears

Q) Listeners and corresponding Methods?

ActionListerner – actionPerformed();
ItemListerner – itemStateChanged();
TextListener – textValueChanged();
FocusListener – focusLost(); & FocusGained();
WindowListener – windowActified(); windowDEactified(); windowIconified(); windowDeiconified(); windowClosed(); windowClosing(); windowOpened();
MouseMotionListener – mouseDragged(); & mouseMoved();
MouseListener – mousePressed(); mouseReleased(); mouseEntered(); mouseExited(); mouseClicked();

Q) Applet Life cycle?

Following stage of any applets life cycle, starts with init(), start(), paint(), stop() and destroy().

Q) Use of showStatus() method in Java

To display the message at the bottom of the browser when applet is started.

Q) What is Event handling in Java?

Is irrespective of any component, if any action performed/done on Frame, Panel or on window, handling those actions are called Event Handling.

Q) What is Adapter class?

Adapter class is an abstract class.
Advantage of adapter: To perform any window listener, we need to include all the methods used by the window listener whether we use those methods are not in our class like Interfaces whereas with adapter class, its sufficient to include only the methods required to override. Straight opposite to Interface.

Categories
Pages
Recent Posts