Java IO and NIO interview questions
\
IO is a very important point in Java interviews. You should have a good knowledge of Java IO, NIO, NIO2, and the basics of operating system and disk IO. The following questions are frequently asked in Java IO.
\
66) In my Java program, I have three sockets, how many threads do I need to process?
\
67) How to create a ByteBuffer in Java?
\
68) How to read and write ByteBuffer in Java?
\
69) Is Java big-endian or small-endian?
\
70) What is the byte order in ByteBuffer?
\
71) What is the difference between direct buffer and indirect buffer in Java? (the answer)
\
72) What is a memory mapped cache in Java? (answer answer)
\
73) What is the socket option TCP NO DELAY?
\
What is the difference between TCP and UDP? (answer answer)
\
75) What is the difference between ByteBuffer and StringBuffer in Java? (the answer)
\
Java Best Practices interview questions
\
Contains best practices for various parts of Java, such as collections, strings, IO, multithreading, error and exception handling, design patterns, and more.
\
76) What best practices do you follow when writing multithreaded programs in Java? (the answer)
Here are some of the best practices I follow when writing concurrent Java programs:
A) Give the thread a name to help with debugging.
B) Minimize the scope of synchronization, instead of synchronizing the entire method, only the key parts.
C) If possible, use volatile rather than synchronized.
D) Use higher-level concurrency tools such as BlockingQueue, CountDownLatch, and Semeaphore instead of wait() and notify() for interthread communication.
E) Use concurrent collections in preference to synchronizing collections. Concurrent collections provide better scalability.
\
77) Name a few best practices for using Collections in Java (answer)
Here are some of my best practices in using the Collectionc class in Java:
A) Use the right collection class, for example, ArrayList instead of Vector if you don’t need to synchronize lists.
B) Use concurrent collections in preference to synchronizing collections. Concurrent collections provide better scalability.
C) Use interfaces to represent and access collections, such as using List to store ArrayList, using Map to store HashMap, and so on.
D) Use iterators to loop through collections.
E) Use generics when using collections.
\
78) Name at least five best practices for using threads in Java. (the answer)
This question is similar to the previous one and you can use the answer above. For threads, you should:
A) Name the thread
B) Separate threads from tasks and use thread pool actuators to perform Runnable or Callable.
C) Use thread pools
\
79) Name 5 IO best practices (answer)
IO is critical to the performance of Java applications. Ideally, you should not avoid IO operations on your application’s critical path. Here are some Java IO best practices you should follow:
A) Use buffered IO classes instead of reading bytes or characters individually.
B) Use NIO and NIO2
C) Close the stream ina finally block, or use a try-with-resource statement.
D) Use memory-mapped files to get faster IO.
\
80) List five JDBC best practices to follow (answers)
There are many best practices, and you can list them according to your preference. Here are some more general principles:
A) Use batch operations to insert and update data
B) Use preparedStatements to avoid SQL exceptions and improve performance.
C) Use a database connection pool
D) Obtain result sets by column names, not by column subscripts.
\
81) Name a few best practices for method overloading in Java? (the answer)
Here are a few best practices for method overloading that you can follow to avoid the chaos of automatic boxing.
A) Do not overload a method that takes an int and another method that takes an Integer.
B) Do not overload methods with the same number of arguments but different order of arguments.
C) If the number of overloaded method parameters is more than 5, variable parameters are used.
\
Date, Time and Calendar interview questions
\
82) Is SimpleDateFormat thread-safe in a multithreaded environment? (the answer)
No, unfortunately, all DateFormat implementations, including SimpleDateFormat, are not thread-safe, so you should not use them in multithreaded sequences unless they are used in an external thread-safe environment. For example, restrict SimpleDateFormat to ThreadLocal. If you don’t, you may get incorrect results when parsing or formatting dates. Therefore, I highly recommend the Joda-time library for all practices in date and time handling.
\
83) How to format a date in Java? For example, format to ddMMyyyy? (the answer)
In Java, you can use the SimpleDateFormat class or the Joda-time library to format dates. The DateFormat class allows you to format dates in a variety of popular formats. See the sample code in the answer that demonstrates formatting dates into different formats, such as DD-MM-YYYY or ddMMyyyy.
\
In Java, how to display the time zone in a formatted date? (the answer)
\
85) What is the difference between java.util.Date and java.sql.Date? (the answer)
\
86) In Java, how to calculate the difference between two dates? (program)
\
How to convert a string YYYYMMDD to a date in Java? (the answer)
\
Unit test JUnit interview questions
\
89) How do I test static methods? (the answer)
You can use the PowerMock library to test static methods.
\
90) How to use JUnit to test a method exception? (the answer)
\
91) Which unit test library have you used to test your Java programs? (the answer)
\
92) What is the difference between @before and @beforeclass? (the answer)
\
Programming and code related interview questions
\
93) How do I check if a string contains only numbers? (Solution)
\
94) How to write an LRU cache using generics in Java? (the answer <)
\
95) Write a Java program that converts byte to long? (the answer)
\
95) How do YOU invert a string without using a StringBuffer? (Solution)
\
In Java, how do I get the highest frequency of words in a file? (Solution)
\
98) How do I check that two given strings are in reverse order? (Solution)
\
99) How do I print all permutations of a string in Java? (Solution)
\
100) In Java, how do I print duplicate elements in an array? (Solution)
\
101) How to convert a string to an integer in Java? (Solution)
\
102) How can I exchange the values of two integer variables without using temporary variables? (Solution)
\
Interview questions about OOP and design patterns
\
This section covers SOLID design principles from the Java interview process, OOP fundamentals such as classes, objects, interfaces, inheritance, polymorphism, encapsulation, abstraction, and more advanced concepts such as composition, aggregation, and association. GOF design pattern issues are also covered.
\
103) What is an interface? Why use interfaces instead of directly using concrete classes?
Interfaces are used to define apis. It defines the rules that classes must follow. At the same time, it provides an abstraction because the client only uses interfaces, which can have multiple implementations, such as the List interface, where you can use arrayLists that are randomly accessible, or linkedLists that are easy to insert and delete. No code is allowed in interfaces to ensure abstraction, but in Java 8 you can declare static default methods in interfaces that are concrete.
\
104) What is the difference between abstract classes and interfaces in Java? (the answer)
There are many differences between abstract classes and interfaces in Java, but one of the most important is that Java limits a class to inheriting only one class, but can implement multiple interfaces. Abstract classes can define the default behavior of a family of classes, while interfaces can define the types better, which helps to implement the polymorphism mechanism later. See the answer for a discussion of this question.
\
105) Besides singletons, what other design patterns have you used in production?
This is based on your experience. In general, you can say dependency injection, factory mode, decorator mode, or observer mode, whichever you’ve used before. But be prepared to answer subsequent questions based on the model you choose.
\
Can you explain Richter’s substitution principle? (the answer)
\
107) Under what circumstances is Demeter’s Law violated? Why is this a problem? (the answer)
Demeter’s Rule advises “only talk to friends, not strangers” to reduce coupling between classes.
\
108) What is the adapter mode? When to use it?
The adapter pattern provides transformations to interfaces. If your client uses some interfaces, but you have other interfaces, you can write an adaptation to connect to those interfaces.
\
109) What are “dependency injection” and “inversion of control”? Why do people use it? (the answer)
\
110) What is an abstract class? How is it different from an interface? Why have you ever used abstract classes? (the answer)
\
Which is better, constructor injection or setter dependency injection? (the answer)
Each approach has its disadvantages and advantages. Constructor injection ensures that all injections are initialized, but setter injection provides greater flexibility to set optional dependencies. If XML is used to describe dependencies, Setter injection is more readable and writable. The rule of thumb is to force dependencies to use constructor injection and optional dependencies to use setter injection.
\
112) What is the difference between dependency injection and engineering patterns? (the answer)
Although both patterns separate object creation from application logic, dependency injection is cleaner than engineering. With dependency injection, your class is a POJO, and it only knows about dependencies and doesn’t care how they get them. With the factory pattern, your classes need to get dependencies through the factory. Therefore, using DI is easier to test than using factory mode. See answers for a more detailed discussion of this topic.
\
113) What is the difference between adapter mode and decorator mode? (the answer)
Although the structure of the adapter pattern and the decorator pattern are similar, each pattern appears for a different purpose. The adapter pattern is used to bridge two interfaces, while the decorator pattern is intended to add new functionality to a class without modifying it.
\
What was the difference between the adapter pattern and the proxy pattern? (the answer)
This problem is similar to the previous one, the adapter pattern and the proxy pattern differ in their intent. The structure is the same because both the adapter pattern and the proxy pattern encapsulate classes that actually perform actions, but the adapter pattern is used for transformations between interfaces, while the proxy pattern adds an additional middle layer to support allocation, control, or intelligent access.
\
115) What is the template method pattern? (the answer)
The template approach provides a framework for algorithms that you can configure or define yourself. For example, you can think of a sorting algorithm as a template. It defines the steps for sorting, but you can use Comparable or something similar in its language for specific comparisons, and the specific policies are up to you to configure. The method of outlining an algorithm is known as the template method.
\
116) When to use the visitor pattern? (the answer)
The visitor pattern addresses, but is not directly associated with, adding operations at the inheritance level of a class. This mode adopts the form of double distribution to increase the middle layer.
\
117) When to use composite mode? (the answer)
The composite pattern uses a tree structure to show the inheritance relationship between parts and the whole. It allows clients to treat individual objects and object containers in a uniform manner. Use composition mode when you want to show the inheritance of parts to the whole of an object.
\
118) What is the difference between inheritance and composition? (the answer)
Although both allow code reuse, composition is more flexible than inheritance because composition allows you to choose different implementations at run time. Code implemented by composition is also simpler to test than inheritance.
\
119) Describe overloading and overwriting in Java? (the answer)
Overloading and overwriting both allow you to implement different functions with the same name, but overloading is a compile-time activity, while overwriting is a run-time activity. You can override methods in the same class, but only in subclasses. Rewriting must have inheritance.
\
120) What is the difference between nested public static classes and top-level classes in Java? (the answer)
Classes can have multiple nested public static classes inside them, but a Java source file can have only one top-level public class, and the top-level public class name must be the same as the source file name.
\
121) What is the difference between composition, aggregation, and association in OOP? (the answer)
If two objects are related to each other, they are said to be related. Composition and aggregation are two forms of association in object orientation. A combination is a stronger association than an aggregation. In composition, one object is the owner of another, while aggregation is the use of one object by another. If object A is composed of object B, then B does not exist if A does not exist, but if object A aggregates an object B, then B can exist alone even if A does not exist.
\
122) Give me an example of a design pattern that conforms to the open close principle? (the answer)
The open closed principle requires that your code be open for extension and closed for modification. This means that if you want to add a new feature, you can easily add new code without changing the already tested code. There are several design patterns that are based on the open closed principle, such as the policy pattern. If you need a new policy, you just implement the interface, add configuration, and don’t change the core logic. One working example is the collections.sort () method, which is policy-based and follows the open and close principle. You don’t need to modify sort() for new objects. All you need to do is implement your own Comparator interface.
\
123) What is the difference between abstract factory pattern and prototype pattern? (the answer)
\
124) When to use the premium mode? (the answer)
The meta pattern avoids creating too many objects by sharing objects. In order to use the share mode, you need to make sure that your objects are immutable so that you can safely share them. The String pool, the Integer pool, and the Long pool in the JDK are all good examples of using the meta schema.
\
A variety of other Java interview questions
\
This section contains Java interview questions on XML, JDBC interview questions, regular expression interview questions, Java errors and exceptions, and serialization interview questions
\
125) What is the difference between nested static classes and top-level classes? (the answer)
A common top-level class has the same source file name as the class name, whereas nested static classes do not have this requirement. A nested class is inside a top-level class, and the name of the top-level class needs to be used to refer to the nested static class, such as HashMap.Entry, which is a nested static class, HashMap, which is a top-level class, and Entry, which is a nested static class.
\
126) Can you write a regular expression to determine if a string is a number? (Solution)
A numeric string can contain only digits, such as 0 through 9 and the beginning of + and -. With this information, you can use the following regular expression to determine whether a given string is a number.
\
127) What is the difference between checked and unchecked exceptions in Java? (the answer)
The checked exception compiler checks during compilation. For such exceptions, methods enforce handling or declare them via throws clause. One of these cases is a subclass of Exception but not RuntimeException. Unchecked is a subclass of RuntimeException that is not checked by the compiler at compile time.
\
Throws throws 128) What is the difference between throws and throws? (the answer)
\
Throw is used to throw an instantiated object of the java.lang.Throwable class. This means that you can throw an Error or an Exception using the keyword throw, as in:
Throw new IllegalArgumentException(” Size must be multiple of 2 “)
\
Throws exceptions as part of a method declaration and signature that the caller can handle. In Java, any unchecked checked exception is forced to be declared in the THROWS clause.
\
129) How is Serializable different from Externalizable in Java? (the answer)
Serializable interface Serializable interface is an interface that serializes Java classes so that they can be transferred over the network or their state can be stored on disk. It is the default serialization method embedded in the JVM and is expensive, fragile, and insecure. Externalizable allows you to control the entire serialization process, specify specific binary formats, and add security mechanisms.
\
130) What is the difference between DOM and SAX parsers in Java? (the answer)
The DOM parser loads the entire XML document into memory to create a DOM model tree, which makes it faster to find nodes and modify the XML structure, whereas the SAX parser is an event-based parser that does not load the entire XML document into memory. For this reason, DOM is faster and requires more memory than SAX, and is not suited for parsing large XML files.
\
131) Name three new features in JDK 1.7? (the answer)
While JDK 1.7 isn’t as big as JDK 5 and 8, there are a number of new features, such as try-with-resource statements, that allow you to use streams or resources without having to manually close them. Fork-join pooling implements the Java version of Map-Reduce to some extent. Allow String variables and text in Switch. The diamond operator (<>) is used for type inference and eliminates the need to declare generics on the right side of variable declarations, resulting in stronger, cleaner code that can be read and written. Another feature worth mentioning is improved exception handling, such as allowing multiple exceptions to be caught in the same catch block.
\
132) Name five new features introduced in JDK 1.8? (the answer)
Java 8 is a groundbreaking release in Java history. Here are five key features in JDK 8:
Lambda expressions, which allow anonymous functions to be passed like objects
The Stream API, which takes full advantage of modern multicore cpus, can write very concise code
The Date and Time API, finally, has a stable, simple library of dates and times at your disposal
Extended methods, now you can have static, default methods in the interface.
Repeat annotations. Now you can use the same annotation multiple times on the same type.
\
133) What is the difference between Maven and ANT in Java? (the answer)
While both are build tools for creating Java applications, Maven does more, providing a standard Java project structure based on the concept of convention over configuration while automatically managing dependencies (JAR files that the application depends on). See the answers for more differences between Maven and ANT tools.
\
That’s all the interview questions, right? I can guarantee that if you can answer all the questions on this list, you can easily handle any core Java or advanced Java interview. Although servlets, JSP, JSF, JPA, JMS, EJB and other Java EE technologies are not covered here, and mainstream frameworks such as Spring MVC, Struts 2.0, Hibernate are not included. SOAP and RESTful Web Services are not included either, but this list is also useful for Java developers who are preparing for Java Web development positions, because all of the Java interviews, The initial questions are all about Java basics and JDK apis. If you think I have any popular Java issues that should be on this list and I’ve left them out, feel free to give me suggestions. My goal is to create an up-to-date list of the best Java interview questions from recent interviews.
\
Java EE related interview questions
\
For the sake of Java EE friends, here is a list of web development-specific questions that you can use to prepare for the JEE portion of your interview:
\
10 Spring Framework Interview Questions and Answers (see also)
10 Great XML Interview Questions (Java Programmers) (see)
20 Great Design Pattern Interview Questions (see also)
10 Most Popular Struts Interview Questions (Java Developers) (see)
20 Tibco Rendezvous and EMS Interview Questions (more)
The 10 most Frequently asked Servlet Interview Questions and answers (see also)
20 jQuery Interview Questions (Java Web Developer)
10 Great Oracle Interview Questions (Java Developers) (see also)
Top 10 JSP Questions from J2EE Interviews (More)
12 Great RESTful Web Services Interview Questions (see also)
Top 10 EJB Interview Questions and Answers (see also)
10 JMS and MQ Interview Questions and Answers (List)
10 Great Hibernate Interview Questions (Java EE Developers) (see)
10 Very Good JDBC Interview Questions for Java Developers (see)
15 Java NIO and Web Interview Questions and Answers (see also)
Top 10 XSLT Interview Questions and Answers (more)
15 Data Structure and Algorithm Questions from Java Interviews (see also)
Top 10 Java Interview Puzzles and Answers (see also)
40 Core Java Mobile Development Interview Questions and Answers (List)
\
Recommended books for Java candidates
\
If you’re looking for good preparation for a Java interview, you can check out the following books, which cover theoretical and coding questions
- Markham’s Java Programming Interview Debunked (see also)
- Crack the Code Interview: 150 Programming Questions and Answers (see also)
- Procedural interview Revealed: The secret to finding your next job (see also)
- \