Top 57 Core Java Programming Interview Questions And Answers
1. How do cookies work in Servlets?
Answer: Cookies are text data sent by the 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 get cookies() method is provided to get the array of Cookies from the request, since there is no point of adding Cookie to request, there are no methods to set or add a cookie to request.
Similarly, HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in the response header, there are no getter methods for a cookie.
2. What is JIT compiler?
Answer: Just-In-Time(JIT) compiler: It is used to improve 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?
Answer: JVM (Java Virtual Machine): It is an abstract machine. It is a specification that provides a 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 the 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)?
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?
Answer: Java is not 100% Object-oriented because it makes use of eight primitive data types such as boolean, byte, char, int, float, double, long, short which does not object.
6. What are the differences between Servlet Context vs Servlet Config?
Answer: The difference between ServletContext and ServletConfig in Servlets JSP is in below tabular format.
Servlet config object represent single servlet It represents 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 the 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 an 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 the 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?
Answer: the 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 a software-based platform.
8. How do you reverse a String in Java without using String Buffer?
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 the 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. The reverse is a recursive job, and for that reason, you can use recursion as well as a loop to reverse String in Java.
9. What is defined as false sharing in the context of multithreading?
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?
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 the 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 centered 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 centered on this model and uses a busy spin loop for EventProcessors waiting on the barrier.
11. Why we cannot override static method?
Answer: It is because the static method is the part of the class and it is bound with class whereas the instance method is bound with the object and static gets memory in the class area and instance gets memory in heap.
12. Difference between method Overloading and Overriding?
Method Overloading Method Overriding
1) Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its superclass.
2) method overloading occurs within the class. Method overriding occurs in two classes that have an IS-A relationship.
3) In this case, the parameter must be different. In this case, the parameter must be the same.
13. What is a static method?
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 an instance of the class.
14. What is the difference between import java.util.Date and java .util?
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 on run-time performance.
15. What is the difference between throw and throws in Java?
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 a throws clause in Java.
16. How do you take thread dump in Java?
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.
17. What are the access modifiers?
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?
Answer: This is a very confusing question, we know that object variables contain a 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 the difference between Heap and Stack Memory?
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 the stack is done in a 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 the final keyword?
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 the 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?
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 a method: Cloneable or Object?
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?
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.
24. Which one will take more memory: an int or Integer?
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? Answer: The string is immutable in Java since Java designer thought that String will be greatly used, making it immutable. It lets some optimization 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 a temporary String object by sharing them and in order to share, they must have to be from the 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?
Answer: Statement execute(String query) is used to execute an SQL query and it returns TRUE if the result is a 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 the 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 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 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.
27. What is Spring?
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?
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?
Answer: It is a feature using which a child class overrides the method of the 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?
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.
31. What is broken and continue statement?
Answer: We can use the break statement to terminate for, while, or do-while loop. We can use the break statement in the switch statement to exit the switch case. You can see the example of break statement at java break. We can use break with a 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 a label to skip the current iteration of the outermost loop.
32. How to run a JAR file through command prompt?
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 the java jar file.
33. What is the use of System class?
Answer: Java System Class is one of the core classes. One of the easiest ways to log information for debugging is System.out.print() method.
System class is final so that we can’t subclass and override its behavior through inheritance. System class doesn’t provide any public constructors, so we can’t instantiate this class and that’s why all of its methods are static.
Some of the utility methods of System class are for array copy, get the current time, reading environment variables. Read more at Java System Class.
34. Can we have multiple public classes in a java source file?
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?
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.The object is the fully classified name of the Object class that is part of java.lang package.
36. What are the differences between throw and throws?
Answer: throw keyword throws keyword
The throw is used to explicitly throw an exception. Throws is used to declare an exception.
Checked exceptions can not be propagated with throw only. A checked exception can be propagated with throws.
The throw is followed by an instance. Throws is followed by class.
The throw is used within the method. Throws are used with the method signature.
You cannot throw multiple exceptions You can declare multiple exceptions e.g. public void method()throws IOException, SQLException. (Interview Questions and Answers)
37. What is the exception hierarchy in java?
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 types of exceptions extend 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?
Answer: final – A final variable acts as a constant, a final class is immutable and a final method cannot be overridden in a child class.
finally – finally keyword is used with try-catch block for handling exceptions. The finally block is optional in a try-catch block. The final code block is always executed after try or catch block is completed. The final 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 final 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.
39. How many types of memory areas are allocated by JVM?
Program Counter Register
Native Method Stack
40. What is the final variable??
Answer: If you make any variable as final, you cannot change the value of the final variable(It will be constant).more details…
41. What is the covariant return type?
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 a covariant return type. more details…
42. Is it possible to write a regular expression to check if String is a number?
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?
Answer: Yes, this is possible from Java 7 onward. The 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?
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?
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.
Minimize the scope of your synchronization. Rather than making the whole method synchronized, be mindful that only the critical section should be synchronized.
Opt for volatile over synchronization 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 synchronized collection in Java as this will provide better scalability.
46. Explain some best practices you would apply while using Collection in Java?
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 synchronized 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 the collection.
Always use generics with the collection.
47. Explain a few methods of overloading best practices in Java?
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?
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 analyzing or configuring dates in Java.
49. Explain 5 IO best practices?
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 date in Java? i.e. in the DDMMYYY format?
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?
Answer: Anagrams are a mix-up of characters in String e.g. army and mary, stop and pots, etc. To identify if Strings are an 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?
Answer: RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in the 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:
53. What is Garbage Collection?
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, the 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. (Java Training Online)
54. What are Serialization and Deserialization?
Answer: We can convert a Java object to a 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?
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?
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 the exceptional case and no exception would be thrown in normal case.
In order to test any Java method for throwing an exception in Junit4, you need to make sure that argument provided to that method, from the test must result in an 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?
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 the 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 the input string passes this systematic expression pattern or not.
Note: Browse latest Java interview questions and Java tutorial. Here you can check Java Training details and Java Videos for self learning. Contact +91 988 502 2027 for more information.