Top 57 Core Java Programming Interview Questions And Answers

1. How does cookies work in Servlets ?_text]Answer:
Cookies are text data sent by server to the client and it gets saved at the client local machine.
Servlet API provides cookies support through javax.servlet.https.Cookie class that implements Serializable and Cloneable interfaces.
HttpServletRequest getCookies() method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there are no methods to set or add cookie to request.
Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in response header, there are no getter methods for cookie.

Top 57 Core Java Programming Interview Questions And Answers2. What is JIT compiler ?_text]Answer:
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.
Servlet is destroyed.3. Explain JVM, JRE and JDK ?_text]Answer:
JVM (Java Virtual Machine): It is an abstract machine. It is a specification that provides run-time environment in which java bytecode can be executed. It follows three notations:

Specification: It is a document that describes the implementation of the Java virtual machine. It is provided by Sun and other companies.
Implementation: It is a program that meets the requirements of JVM specification.
Runtime Instance: An instance of JVM is created whenever you write a java command on the command prompt and run the class.
JRE (Java Runtime Environment) : JRE refers to a runtime environment in which java bytecode can be executed. It implements the JVM (Java Virtual Machine) and provides all the class libraries and other support files that JVM uses at runtime. So JRE is a software package that contains what is required to run a Java program. Basically, it’s an implementation of the JVM which physically exists.

JDK(Java Development Kit) : It is the tool necessary to compile, document and package Java programs. The JDK completely includes JRE which contains tools for Java programmers. The Java Development Kit is provided free of charge. Along with JRE, it includes an interpreter/loader, a compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools needed in Java development. In short, it contains JRE + development tools.4. Explain public static void main(String args) ?_text]Answer:
public : Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class.
static : It is a keyword in java which identifies it is class based i.e it can be accessed without creating the instance of a Class.

void : It is the return type of the method. Void defines the method which will not return any value.

main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.5. Why java is not 100% Object-oriented ?_text]Answer:
Java is not 100% Object-oriented because it makes use of eight primitive datatypes such as boolean, byte, char, int, float, double, long, short which are not objects.6. What are the differences between Servlet Context vs Servlet Config ?_text]Answer:
The difference between ServletContext and ServletConfig in Servlets JSP is in below tabular format.

ServletConfig ServletContext
Servlet config object represent single servlet It represent whole web application running on particular JVM and common for all the servlet
Its like local parameter associated with particular servlet Its like global parameter associated with whole application
It’s a name value pair defined inside the servlet section of web.xml file so it has servlet wide scope ServletContext has application wide scope so define outside of servlet tag in web.xml file.
getServletConfig() method is used to get the config object getServletContext() method is used to get the context object.
for example shopping cart of a user is a specific to particular user so here we can use servlet config To get the MIME type of a file or application session related information is stored using servlet context object.7. What is platform ?_text]Answer:
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.8. How do you reverse a String in Java without using String Buffer ?_text]Answer:
To reverse a String in Java, you are able to use rich Java API to quickly reverse contents of any String object. The Java library provides String Buffer and StringBuilder class with reverse() method, which can be used to reverse String in Java.

Since changing between String and StringBuffer is very easy, this is the easiest way presented to reverse String in Java. Reverse is a recursive job, and for that reason you can use recursion as well as loop to reverse String in Java.

Top 57 Core Java Programming Interview Questions And Answers9. What is defined as false sharing in the context of multithreading ?_text]Answer:
False sharing is known to be one of the familiar performance issues on multi-core systems, whereby each process has a local cache.

False sharing can be hard to identify since the thread may be retrieving completely different global variables that occur to be fairly close together in memory.

Similar to many other concurrency issues, the main way to avoid false sharing is to carefully review your code and supporting your data structure with the size of a cache line.10. What is busy spin, and why should you use it ?_text]Answer:
Busy spin is known as one of the techniques to wait for events without freeing CPU. This is often done to avoid losing data in CPU cache, which could get lost if the thread is paused and resumed in some other core.

As a result, if you are working on a low latency system where your order processing thread isn’t in any particular order, rather than sleeping or calling wait(), you can just loop and then review the queue for new messages.

This is only valuable if you need to wait for a short amount of time, e.g. in microseconds or nanoseconds. LMAX Disruptor frameworks, a high-performance inter-thread messaging library has a BusySpinWait Strategy, which is centred on this model and uses a busy spin loop for EventProcessors waiting on the barrier.

LMAX Disruptor frameworks, a high-performance inter-thread messaging library has a BusySpinWait Strategy, which is centred on this model and uses a busy spin loop for EventProcessors waiting on the barrier.11. Why we cannot override static method ?_text]Answer:
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.12. Difference between method Overloading and Overriding ?_text]Answer:
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.13. What is a static method ?_text]Answer:
Static methods can be called directly without creating the instance (Object) of the class. A static method can access all the static variables of a class directly but it cannot access non-static variables without creating instance of class.14. What is the difference between import java.util.Date and java.util ?_text]Answer:
The star form (java.util.* ) includes all the classes of that package and that may increase the compilation time – especially if you import several packages. However it doesn’t have any effect run-time performance.15. What is the difference between throw and throws in Java ?_text]Answer:
The throw is used to actually throw an instance of java.lang.throwable class, meaning you can throw both Error and Exception using throw keyword.

However, throws is used as part of method declaration and indicate which kind of exceptions are thrown by this method, so that its caller can handle them.

It is compulsory to assert any unhandled checked exception in throws clause in Java.16. How do you take thread dump in Java ?_text]Answer:
By using kill -3 PID in Linux, where PID is the process id of Java process, you can take a thread dump of Java application. In Windows, you can press Ctrl + Break.

This will instruct JVM to print thread dump in standard out, and it may go to console or log file depending on your application configuration.

Top 57 Core Java Programming Interview Questions And Answers17. What are access modifiers ?_text]Answer:
Java provides access control through public, private and protected access modifier keywords. When none of these are used, it’s called default access modifier.
A java class can only have public or default access modifier. Read Java Access Modifiers to learn more about these in detail.18. Java is Pass by Value or Pass by Reference ?_text]Answer:
This is a very confusing question, we know that object variables contain reference to the Objects in heap space. When we invoke any method, a copy of these variables is passed and gets stored in the stack memory of the method. We can test any language whether it’s pass by reference or pass by value through a simple generic swap method, to learn more read Java is Pass by Value and Not Pass by Reference.19. What is difference between Heap and Stack Memory ?_text]Answer:
Major difference between Heap and Stack memory are as follows:
Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally.
For a detailed explanation with a sample program, read Java Heap vs Stack Memory.20. What is final keyword ?_text]Answer:
final keyword is used with Class to make sure no other class can extend it, for example String class is final and we can’t extend it.

We can use final keyword with methods to make sure child classes can’t override it.

final keyword can be used with variables to make sure that it can be assigned only once. However the state of the variable can be changed, for example we can assign a final variable to an object only once but the object variables can change later on.

Java interface variables are by default final and static.
Hashtable does not allow null keys but HashMap allows one null key.Q5).21. What is an immutable object ?_text]Answer:
Java classes whose objects cannot be modified once they are created are known as Immutable classes. Any modification of Immutable object results formation of the new object.22. Which class contains method: Cloneable or Object ?_text]Answer:
java.lang.Cloneable is marker interface and does not contain at all any method. Clone method is well-defined in the object class.

Remember that clone() is a native method, therefore it is applied in C or C++ or any other native programming language.23. Is ++ operator thread-safe in Java ?_text]Answer:
++ is not thread-safe in Java because it involves multiple commands such as reading a value, implicating it, and then storing it back into memory.

This can be overlapped between multiple threads.

Top 57 Core Java Programming Interview Questions And Answers24. Which one will take more memory: an int or Integer ?_text]Answer:
An integer object will take more memory as it stores metadata overhead about the object. An int is primitive, therefore it takes less space.25. Why is String immutable in Java ?_text]Answer:
String is immutable in Java since Java designer thought that String will be greatly used, making it immutable. It lets some optimisation easy sharing, and same String object between multiple clients.

A key step in that direction was the idea of putting away String literals in String pool. The aim was to moderate temporary String object by sharing them and in order to share, they must have to be from immutable class.

It is worth noting, that it isn’t possible to share a mutable project with two parties which are unfamiliar to each other.26. What is the difference between execute, execute Query, execute Update ?_text]Answer:
Statement execute(String query) is used to execute any SQL query and it returns TRUE if the result is an ResultSet such as running Select queries. The output is FALSE when there is no ResultSet object such as running Insert or Update queries. We can use getResultSet() to get the ResultSet and getUpdateCount() method to retrieve the update count.

Statement executeQuery(String query) is used to execute Select queries and returns the ResultSet. ResultSet returned is never null even if there are no records matching the query. When executing select queries we should use executeQuery method so that if someone tries to execute insert/update statement it will throw java.sql.SQLException with message “executeQuery method can not be used for update”.

Statement executeUpdate(String query) is used to execute Insert/Update/Delete (DML) statements or DDL statements that returns nothing. The output is int and equals to the row count for SQL Data Manipulation Language (DML) statements. For DDL statements, the output is 0.

You should use execute() method only when you are not sure about the type of statement else use executeQuery or executeUpdate method.

In case you are facing any challenges with these java interview questions, please comment your problems in the section below. Apart from this Java Interview Questions Blog, if you want to get trained from professionals on this technology.27. What is a Spring ?_text]Answer:
Wikipedia defines the Spring framework as “an application framework and inversion of control container for the Java platform. The framework’s core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform.” Spring is essentially a lightweight, integrated framework that can be used for developing enterprise applications.28. What is Polymorphism and what are the types of it ?_text]Answer:
Polymorphism is the ability of an object to take many forms. The most common use of polymorphism in OOPs is to have more than one method with the same name in a single class. There are two types of polymorphism: static polymorphism and dynamic polymorphism.29. What is the method overriding ?_text]Answer:
It is a feature using which a child class overrides the method of parent class. It is only applicable when the method in child class has the signature same as parent class.30. What is the size of int in 64-bit JVM ?_text]Answer:
The size of an int variable is constant in Java, it is always 32-bit regardless of platform. This means the size of primitive int is identical in both 32-bit and 64-bit Java Virtual Machine.

Top 57 Core Java Programming Interview Questions And Answers31. What is break and continue statement ?_text]Answer:
We can use break statement to terminate for, while, or do-while loop. We can use break statement in switch statement to exit the switch case. You can see the example of break statement at java break. We can use break with label to terminate the nested loops.

The continue statement skips the current iteration of a for, while or do-while loop. We can use continue statement with label to skip the current iteration of outermost loop.32. How to run a JAR file through command prompt ?_text]Answer:
We can run a jar file using java command but it requires Main-Class entry in jar manifest file. Main-Class is the entry point of the jar and used by java command to execute the class. Learn more at java jar file.33. What is the use of System class ?_text]Answer:
Java System Class is one of the core classes. One of the easiest way to log information for debugging is System.out.print() method.

System class is final so that we can’t subclass and override it’s behavior through inheritance. System class doesn’t provide any public constructors, so we can’t instantiate this class and that’s why all of it’s methods are static.

Some of the utility methods of System class are for array copy, get current time, reading environment variables. Read more at Java System Class.34. Can we have multiple public classes in a java source file ?_text]Answer:
We can’t have more than one public class in a single java source file. A single source file can have multiple classes that are not public.35. What is Java Package and which package is imported by default ?_text]Answer:
Java package is the mechanism to organize the java classes by grouping them. The grouping logic can be based on functionality or modules based. A java class fully classified name contains package and class name. For example, java.lang.Object is the fully classified name of Object class that is part of java.lang package.36. What are the differences between throw and throws ?_text]Answer:
throw keyword throws keyword
Throw is used to explicitly throw an exception. Throws is used to declare an exception.
Checked exceptions can not be propagated with throw only. Checked exception can be propagated with throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple exception You can declare multiple exception e.g. public void method()throws IOException,SQLException.37. What is exception hierarchy in java ?_text]Answer:
The hierarchy is as follows:

Throwable is a parent class of all Exception classes. There are two types of Exceptions: Checked exceptions and UncheckedExceptions or RunTimeExceptions. Both type of exceptions extends Exception class whereas errors are further classified into Virtual Machine error and Assertion error.38. What is the difference between final, finally and finalize() in Java ?_text]Answer:
final – A final variable acts as a constant, a final class is immutable and a final method cannot be overriden in a child class.

finally – finally keyword is used with try-catch block for handling exceptions. The finally block is optional in try-catch block. The finally code block is always executed after try or catch block is completed. The finally block is mainly executed to close the resources or clean up objects used in the try block. For e.g. Closing a FileStream, I/O stream objects, Database connections, HTTP connections are generally closed in a finally block.

finalize() – This is the method of Object class.It is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

Top 57 Core Java Programming Interview Questions And Answers39. How many types of memory areas are allocated by JVM ?_text]Answer:
Many types:

Class(Method) Area
Heap
Stack
Program Counter Register
Native Method Stack40. What is final variable ?_text]Answer:
If you make any variable as final, you cannot change the value of final variable(It will be constant).more details…41. What is covariant return type ?_text]Answer:
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. more details…42. Is it possible to write a regular expression to check if String is a number ?_text]Answer:
A numeric String is only able to contain digits i.e. 0-9 and +/- sign. By using this information, you can write following regular expression to check if given String is number or not.43. Is it possible to use String in the switch case ?_text]Answer:
Yes, this is possible from Java 7 onward. String can be used in switch case, but it is just syntactic sugar. Internal string hashcode is used for the switch.44. What is constructor chaining in Java ?_text]Answer:
Constructor chaining in Java is when you call one constructor from another. This generally occurs when you have multiple, overloaded constructor in the class.45. What best practices should you follow while writing multithreaded code in Java ?_text]Answer:
When writing concurrent code in Java, the following are some best practices to be mindful of:

Always name your thread as this help in debugging.
Minimise the scope of your of synchronisation. Rather than making the whole method synchronised, be mindful that only the critical section should be synchronised.
Opt for volatile over synchronisation if you have the option to.
Use a higher level of concurrency utilities instead of waiting() and notify for inter-thread communication, e.g. BlockingQueue, CountDownLatch and Semaphore.
Opt for concurrent collection over synchronised collection in Java as this will provide better scalability.

Top 57 Core Java Programming Interview Questions And Answers46. Explain some best practices you would apply while using Collection in Java ?_text]Answer:
When using Collection classes in Java, the following are some best practices to be mindful of:

Ensure you are using the right collection, e.g. if you need a non-synchronised list, then opt for ArrayList and not Vector.
Opt for concurrent collection over a synchronised collection because they are more scalable.
Ensure you are using interface to represent and access a collection e.g. use List to store ArrayList, Map to store HashMap.
Use iterator to loop over collection.
Always use generics with collection.47. Explain a few method overloading best practices in Java ?_text]Answer:
The following are examples of overloading a method in Java to avoid confusion with auto-boxing:

Don’t overload method where one accepts ints and the other accepts Integer.
Don’t overload method where a number of arguments are the same and only the order of argument is different.
Use varargs after the overload methods have had more than five arguments.48. Is SimpleDateFormat safe to use in the multithreaded program ?_text]Answer:
No, DataFormat and all its implementation including SimpleDateFormat is not thread-safe, hence should not be used in the multithreaded program until external thread-safety measures are applied e.g. confining SimpleDateFormat object into ThreadLocal variable.

If you do not do that, you will get wrong results while analysing or configuring dates in Java.49. Explain 5 IO best practices ?_text]Answer:
IO is important for overall performance for your Java application, and ideally you should avoid IO in a critical path of your application. The following are Java IO best practices you should be mindful of:

Use buffered IO classes instead of reading individual bytes and char.
Use classes from NIO and NIO2.
Always close streams in final block or use try-with-resource statements.
Use memory mapped file for faster IO.50. How would you format a data in Java? i.e. in the DDMMYYY format ?_text]Answer:
This can be done by using either SimpleDateFormat class or java-time library to format a date in Java. DateFormat class lets you format the date on many common formats.51. How do you check if two given String are anagrams ?_text]Answer:
Anagrams are a mix-up of characters in String e.g. army and mary, stop and pots etc. To identify if Strings are anagram, you will need to get their character array and identify if they are equal or not.

You are able to use indexOf(), substring() and StringBuffer or StringBuilder class to solve this question.52. What is Request Dispatcher ?_text]Answer:
RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response.

There are two methods defined in this interface:

1.void forward()

2.void include()53. What is Garbage Collection ?_text]Answer:
Garbage Collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. In Java, process of deallocating memory is handled automatically by the garbage collector.

We can run the garbage collector with code Runtime.getRuntime().gc() or use utility method System.gc(). For a detailed analysis of Heap Memory and Garbage Collection, please read Java Garbage Collection.54. What is Serialization and Deserialization ?_text]Answer:
We can convert a Java object to an Stream that is called Serialization. Once an object is converted to Stream, it can be saved to file or send over the network or used in socket connections.

The object should implement Serializable interface and we can use java.io.ObjectOutputStream to write object to file or to any OutputStream object. Read more at Java Serialization.

The process of converting stream data created through serialization to Object is called deserialization. Read more at Java Deserialization.55. What is the difference between state-based unit testing and interaction-based unit testing ?_text]Answer:
State-based unit testing tests that the resulting state of a piece of code under test is as expected. Interaction-based testing tests that the piece of code under tests followed a certain flow or invoked certain methods as expected.56. How do you test a method for an exception using JUnit ?_text]Answer:
One part of unit testing a Java method is checking exception thrown by that method. In a Java unit test, it should really prove correct exception thrown in exceptional case and no exception would be thrown in normal case.

In order to test any Java method for throwing exception in Junit4, you need to make sure that argument provided to that method, from the test must result in expected exception, otherwise JUnit test will fail.

A testing method called speed(), returns speed as distance/time, but before calculating speed it checks whether time and distance are positive or negative and if time is zero or negative it throws IllegalArgumentException.57. How do you check if a String contains only numeric digits ?_text]Answer:
java.lang.String class offers a couple of methods with an inherent support of systematic expression e.g.split method, replaceAll() and matches method. Although this can be used for this purpose, it can have a disadvantage.

They produce a new consistent expression pattern object, each time you call. Since most of the time the pattern can be reused, there is no need to spend time on producing and assembling pattern, which is costly in comparison to testing a String against the pattern.

In terms of reusable patterns, you can receive assistance of java.util.regex package, it offers two class Pattern and Matcher to create pattern and review String alongside that pattern.

To complete this, you need to create a regular expression pattern object. This can be done by passing regular expression String “(.)*(\\d)(.)*” to Pattern.compile() method.

This will then output a compiled version of regular expression String. From using this pattern you can acquire Matcher object to identify if input string passes this systematic expression pattern or not.[vc_wp_posts number=”5″]