Top 43 Advanced Core Java Interview Questions And Answers
1. Is Swing thread-safe?
Answer: No, Swing is not thread-safe. You aren’t able to update Swing components, e.g. JTable, JList or Jpanel from any thread. In fact, they must be updated from a GUI or AWT thread. This is why Swing’s provide
In fact, they must be updated from a GUI or AWT thread. This is why Swing’s provide invokeAndWait() and invokeLater() method to request GUI update from alternative threads.
These methods put update requests in AWT threads queue and wait for the update or return straight away for an asynchronous update.
2. What are Packages?
Answer: A Package can be defined as a grouping of related types (classes, interfaces, enumerations, and annotations )
3. What are the differences between Heap and Stack Memory? Answer:
The major difference between Heap and Stack memory are:
Features Stack Heap
Memory Stack memory is used only by one thread of execution. Heap memory is used by all the parts of the application.
Access Stack memory can’t be accessed by other threads. Objects stored in the heap are globally accessible.
Memory Management Follows LIFO manner to free memory. Memory management is based on the generation associated with each object.
Lifetime Exists until the end of execution of the thread. Heap memory lives from the start till the end of application execution.
Usage Stack memory only contains local primitive and reference variables to objects in heap space. Whenever an object is created, it’s always stored in the Heap space.
In case you are facing any challenges with these java interview questions, please comment on your problems in the section below. Apart from this Java Interview Questions Blog, if you want to get trained from professionals on this technology.
4. What is runtime polymorphism or dynamic method dispatch?
Answer: In Java, 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 superclass. Let’s take a look at the example below to understand it better.
5. What is an Object class?
Answer: This is a special class defined by java; all other classes are subclasses of the object class. Object class is a superclass of all other classes. Object class has the following methods
objection () – to creates a new object that is same as the object being cloned.
boolean equals(Object obj) – determines whether one object is equal to another.
finalize() – Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform another cleanup.
toString () – Returns a string representation of the object.
6. What are constructors in Java?
Answer: In Java, constructor refers to a block of code which is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created.
There are two types of constructors:
7. What is singleton class and how can we make a class singleton?
Answer: Singleton class is a class whose only one instance can be created at any given time, in one JVM. A class can be made singleton by making its constructor private.
8. Why Java is not a pure Object Oriented language?
Answer: Java is not said to be pure object-oriented because it supports primitive types such as int, byte, short, long, etc. I believe it brings simplicity to the language while writing our code. Obviously java could have wrapper objects for the primitive types but just for the representation, they would not have provided any benefit.
As we know, for all the primitive types we have wrapper classes such as Integer, Long etc that provides some additional methods.
9. What is the difference between Array list and vector?
Array List Vector
Array List is not synchronized. Vector is synchronized.
Array List is as fast as it’s non-synchronized. Vector is slow as it is thread-safe.
If an element is inserted into the Array List, it increases its Array size by 50%. Vector defaults to doubling size of its array.
Array List does not define the increment size. Vector defines the increment size.
Array List can only use Iterator for traversing an Array List. Except for Hashtable, Vector is the only other class which uses both Enumeration and Iterator.
10. What are the differences between constructor injection and setter injection?
No. Constructor Injection Setter Injection
1) No Partial Injection Partial Injection
2) Doesn’t override the setter property Overrides the constructor property if both are defined.
3) Creates a new instance if any modification occurs Doesn’t create a new instance if you change the property value
4) Better for too many properties Better for a few properties.
11. What is the difference between the Hash table and Hash Map?
There are several differences between the two classes, including:
Hashtable is a legacy class and current from JDK 1, HashMap was introduced and added later.
Hashtable is synchronized and slower whereas HashMap is not synchronized and faster.
12. Can you override a private or static method in Java?
Answer: You cannot override a private or static method in Java. If you create a similar method with the same return type and same method arguments in child class then it will hide the superclass method; this is known as method hiding. Similarly, you cannot override a private method in subclass because it’s not accessible there. What you can do is create another private method with the same name in the child class. Let’s take a look at the example below to understand it better.
13. What is Interface in java?
Answer: An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Read more about the interface here.
14. What are multiple inheritances? Is it supported by Java?
Answer: Multiple Inheritance – Java Interview Questions – SVR. If a child class inherits the property from multiple classes is known as multiple inheritances. Java does not allow to extend multiple classes.
The problem with multiple inheritances is that if multiple parent classes have the same method name, then at runtime it becomes difficult for the compiler to decide which method to execute from the child class.
Therefore, Java doesn’t support multiple inheritances. The problem is commonly referred to as Diamond Problem.
15. What is JDBC Driver?
Answer: JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers:
JDBC-ODBC bridge driver
Native-API driver (partially java driver)
Network Protocol driver (fully java driver)
Thin driver (fully java driver)
16. What are the steps to connect to a database in java?
- Registering the driver class
- Creating a connection
- Creating a statement
- Executing queries
- Closing connection
17. What are the JDBC API components?
The java.sql package contains interfaces and classes for JDBC API.
- CallableStatement etc.
- SQLException etc.
18. What is the role of the JDBC DriverManager class?
Answer: The DriverManager class manages the registered drivers. It can be used to register and unregister drivers. It provides a factory method that returns the instance of Connection.
19. What is JDBC Connection interface?
Answer: The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that return the instance of Statement, PreparedStatement, CallableStatement, and DatabaseMetaData.
20. Can the Garbage Collection be forced by any means?
Answer: No, it’s not possible. you cannot force a garbage collection. you can call system.gc() methods for garbage collection but it does not guarantee that garbage collection would be done.
21. What is the purpose of the JDBC ResultSet interface?
Answer: The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the information from the database.
22. What do you mean by batch processing in JDBC?
Answer: Batch processing helps you to group related SQL statements into a batch and execute them instead of executing a single query. By using a batch processing technique in JDBC, you can execute multiple queries which makes the performance faster.
23. What is static and dynamic binding?
Answer: Binding refers to the linking of the method call to its body. A binding that happens at compile time is known as static binding while binding at runtime is known as dynamic binding.
24. How does HashSet work internally in Java?
Answer: HashSet is internally implemented using a HashMap. Since a Map needs a key and value, a default value is used for all keys. Like HashMap, HashSet does not allow identical keys and only one null key – you are only able to store one null object in HashSet.
25. What is the byte order of Byte Buffer?
Answer: The byte order is used when reading or writing multibyte values, and when creating buffers that are views of this byte buffer. The order of a new byte buffer is always BIG_ENDIAN.
26. What is the difference between the direct buffer and non-direct buffer in Java?
Answer: Byte buffer is one of the important class of the Java NIO API. This was initially introduced in java. nio package on JDK 1.4. It lets you function on-heap byte arrays as well as with direct memory, which occurs outside the JVM.
It lets you function on-heap byte arrays as well as with direct memory, which occurs outside the JVM.
The main difference between direct and non-direct byte buffers are their memory location, non-direct byte buffers are just a wrapper around byte array and they reside in Java Heap memory.
Meanwhile, direct byte buffer is outside of JVM and memory is not assigned from the heap.
A byte buffer is either direct or non-direct. Given a direct byte buffer, the Java Virtual Machine will make a best effort to complete native I/O operations directly upon it.
It will try to evade copying the buffer’s content to (or from) an intermediate buffer before (or after) each invocation of one of the underlying operating system’s native I/O operations.
27. What is autowiring in Spring? What are the autowiring modes?
Answer: Autowiring enables the programmer to inject the bean automatically. We don’t need to write explicit injection logic. Let’s see the code to inject bean using dependency injection.
The autowiring modes are given below:
No. Mode Description
1) no this is the default mode, it means autowiring is not enabled.
2) byName Injects the bean based on the property name. It uses the setter method.
3) byType Injects the bean based on the property type. It uses the setter method.
4) constructor It injects the bean using constructor
28. How to handle exceptions in Spring MVC Framework?
Spring MVC Framework provides the following ways to help us achieving robust exception handling.
We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
Global Exception Handler:
Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
For generic exceptions, most of the times we serve static pages. Spring Framework provides a HandlerExceptionResolver interface that we can implement to create a global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.
29. What are some of the important Spring annotations which you have used?
Some of the Spring annotations that I have used in my project are:
@Controller – for controller classes in Spring MVC project.
@RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation, so you should go through Spring MVC RequestMapping Annotation Examples
@ResponseBody – for sending Object as a response, usually for sending XML or JSON data as a response.
@PathVariable – for mapping dynamic values from the URI to handler method arguments.
@Autowired – for autowiring dependencies in spring beans.
@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type are present.
@Service – for service classes.
@Scope – for configuring the scope of the spring bean.
@Configuration, @ComponentScan and @Bean – for java based configurations.
AspectJ annotations for configuring aspects and advice, @Aspect, @Before, @After, @Around, @Pointcut, etc.
30. How to integrate Spring and Hibernate Frameworks?
Answer: We can use Spring ORM module to integrate Spring and Hibernate frameworks if you are using Hibernate 3+ where SessionFactory provides current session, then you should avoid using HibernateTemplate or HibernateDaoSupport classes and better to use DAO pattern with dependency injection for the integration.
Also, Spring ORM provides support for using Spring declarative transaction management, so you should utilize that rather than going for hibernating boiler-plate code for transaction management.
In case you are facing any challenges with these java interview questions, please comment on your problems in the section below. Apart from this Java Interview Questions Blog, if you want to get trained from professionals on this technology, you can opt for structured training.
31. Can we overload main method?
Answer: Yes, we can have multiple methods with the name “main” in a single class. However, if we run the class, java runtime environment will look for main method with syntax as public static void main(String args).
32. What is the difference between Error and Exception?
Answer: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors you can not repair them at runtime. Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.
While exceptions are conditions that occur because of bad input or human error etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving the user feedback for entering proper values etc.
33. What are the differences between Checked Exception and Unchecked Exception?
The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions.
Checked exceptions are checked at compile-time.
Example: IOException, SQLException, etc.
The classes that extend RuntimeException are known as unchecked exceptions.
Unchecked exceptions are not checked at compile-time.
Example: ArithmeticException, NullPointerException etc.
34. String class is defined under which package in Java?
The answer to this Java question is java.lang package, and this will test the very basics of core Java knowledge.
David Owens, who is a freelancing Java developer also provides interview questions about the core fundamentals of Java knowledge.
35. What are instance variables?
Answer: Instance variables are those which are defined at the class level. Instance variables need not be initialized before using them as they are automatically initialized to their default values.
36. What occurs when an object is constructed?
Answer: Several things happen in a specific order to guarantee the object is constructed properly:
Memory is distributed from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implementation-specific data consist of point to class and method data.
The instance variables of the objects are initialized to their default values.
The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its uppercase. This process continues until the constructor is for java.lang.The object is called, as java.lang.Object is the base class for all objects in Java.
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. This, the constructor for the base class completes first and constructor for the most derived class completes last.
A question like this will indicate a good understanding of processes with the core Java language.
37. For addition and deletion. Which one is most preferred: Array List or Linked List?
LinkedList. Because deleting or adding a node in LinkedList is faster than ArrayList.
38. 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. More details.
39. How is JSP better than Servlet technology?
Answer: JSP is a technology on the server’s side to make content generation simple. They are document-centric, whereas servlets are programs. A Java server page can contain fragments of Java program, which execute and instantiate Java classes. However, they occur inside an HTML template file. It provides the framework for the development of a Web Application.
40. 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.
41. How can you handle Java exceptions?
There are five keywords used to handle exceptions in java:
42. Why Java is platform-independent?
Answer: Platform independent practically means “write once run anywhere”. Java is called so because of its byte codes which can run on any system irrespective of its underlying operating system.
43. What are the important methods of Java Exception Class?
Answer: Methods are defined in the base class Throwable. Some of the important methods of Java exception class are stated below.
String getMessage() – This method returns the message String about the exception. The message can be provided through its constructor.
public StackTraceElement getStackTrace() – This method returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack whereas the last element in the array represents the method at the bottom of the call stack.
Synchronized Throwable getCause() – This method returns the cause of the exception or null id as represented by a Throwable object.
String toString() – This method returns the information in String format. The returned string contains the name of Throwable class and localized message.
void printStackTrace() – This method prints the stack trace information to the standard error stream.