List of interview questions java. A guide for the future Java developer

Interview questions for the Java Junior position.

Preparing for interview for a Java Junior position is an integral part of the path of a beginning developer. Before you start making the rounds of potential employers, you need to thoroughly prepare for the meeting with them. It is very important to try to anticipate the questions that technical specialists will ask you. It often happens that a young applicant has read several books, taken a course, and even possibly written his own application to demonstrate the capabilities, but anxiety or the lack of a clear picture about the language or technology as a whole does not allow him to connect even a few words at the interview. He looks at the potential employer, understands everything, but does not know how to correctly express his thoughts.

I tried to collect the most complete list of interview questions for java junior position, most of which you will definitely hear when looking for your first job in the java developer industry.

1)
2)
3)
4)
5)
6)
7)

9)
10)
11)
12)
13)
14)
15)
16)
17)
18)
19)
20)
21)
22)
23)
24)
25)
26)
27)
28)
29)
30)
31)
32)
33)
34)
35)
36)
37)
38)
39)
40)
41)
42)
43)
44)
45)
46)
47)
48)
49)
50)
51)What is autoboxing?
52)Why is autoboxing used?
53) Alternatives to autoboxing?
54) Wrapper types for primitive types mutable or immutable?
55) How are primitive types reduced to non-primitive analogues?
56)How are non-primitive types reduced to primitive?
57)How do primitive and non-primitive types compare?
58)Is a new object always created during an autoboxing operation?
59)How does caching work during the autoboxing operation?
60)For what types and/or values ​​does caching work?
61)What are the thread priorities?
62) Is it possible to stop a thread by reducing its priority to 0?
63) Why do we need the ThreadGroup class?
64)Which group of threads does main-thread belong to?
65)What is the ThreadPool pattern
66) Why do we need the ThreadPoolExecutor class?
67) How many ways to create a thread do you know? (Thread, Runnable, Callable)
68)What is the Future class used for?
69)What are the advantages of Callable over Runnable?
70) Is it possible to cancel the execution of a task if we use the Future class?
71)What is a deadlock?
72)What strategies do you know to prevent deadlocks from occurring?
73) Can deadlocks occur when using wait-notify methods?
74)Which is more often used: notify or notifyAll?
75) Is it recommended to use the wait method with if or while constructs?
76)What happens after calling the notifyAll method?
77)What benefits does an object receive if it is immutable?
78)What is “thread-safe”?
79)What is “happens-before”?
80)What is JMM?
81)What exception will be thrown if you call wait not in a synchronized block?
82)How to use the Comparable interface?
83)How to use the Comparator interface?
84)What methods does the Collections class have?
85)What methods does the Arrays class have?
86)What is the name of the sort that is used when calling Collections.sort()?
87)What is kankarensi?
88)What classes from “kankarensi” do you know?
89) How does the ConcurrentHashMap class work?
90)What is the Lock class?
91)What is an iterator?
92)What is a mutex?
93)What is a monitor?

94) How in java can you separate the output of messages to the system console and errors to a file?
95)What is the difference between an interface and an abstract class?
96)When is it better to use a timed block instead of a timed method?
97) What is the purpose of the keyword transient?
98)How can I run the garbage collector?
99)What is the difference between constructors and other methods?
100) Explain the purpose of using packages in Java?
101)What is the difference between J2SDK 1.5 and J2SDK 5.0?
102) Does it matter in what order FileNotFoundException and IOException exceptions are caught, and why?
103)What happens if you replace && with & in the following code:

Java

String a=null; if (a!=null && a.length()>10) (...)

String a = null ; if (a != null && a . length () > 10 ) ( . . . )

104)What is the main difference between Vector and ArrayList?
105)What is the difference between a queue and a stack?
106)Name all the states of the Thread object?
107)What states can a thread go to when entering a synchronized block?
108)What state will the thread go to when calling the wait() method?
109)What state will the thread go to when calling the wait(500) method?
110)What state will the thread go to when calling the notify() method?
111)What state will the thread go to when calling the notifyAll() method?
112) Three threads in the synchronized block called wait() on the mutex object.
113)What state will these threads go to if the fourth thread calls notifyAll()?
114)What is the difference between join(500) and wait(500)?
115)What is the difference between wait(500) and sleep(500)?
116)What state will the thread go to when calling the yield() method?
117) Is it possible to declare internal classes private?
118) Is it possible to declare anonymous inner classes private?
119) How many internal classes can a class have maximum?
120) What is the meaning of the keyword super in Java?

Show hidden content

Variables and methods of a superclass can be overridden in the descendant class. When overridden, the subclass defines its variables and methods using the names of the superclass's variables and methods.
As a result of the override, the subclass will no longer be able to access the variables and methods of the superclass directly, because they are now hidden in the namespace of the subclass. Fortunately, Java provides a mechanism for accessing overridden methods and superclass variables - the keyword super. super can help when accessing variables, methods, and constructors of the superclass.
Important point: when calling a superclass constructor, super must be the first expression in the constructor.

121)What is the difference between overloading and overriding methods in Java?
122)What makes Java applications platform independent?
123) What is method overloading in Java?
124)What are the differences between C++ and Java?
125)What is JIT compilation?
126)What is bytecode?
127) What is a class?
128)What is an object in Java?
129)What is a method in Java?
130)What is the meaning of encapsulation?
131) Explain why the main() method has exactly this signature (public, void, static)?
132)What is a constructor in Java?
133)What is the difference between length and length()?
134)What is ASCII?
135)What is Unicode?
136)What are constants and how are they used in Java?
137)What is the difference between ">>" and ">>>" in Java?
138)What code formatting standards do you know?
139)What is "IS-A" relation in Java?
140)What is "HAS-A" relation in Java?
141)What is the difference between “HAS-A” and “IS-A” relationships?
142)Explain the purpose of the instanceof operator in java?
143)What is there null in Java?
144) Is it possible to have many classes in one file?
145)What access modifiers can be specified for the main (top) class?
146)Is it possible to specify more than one package in one file?
147) Is it possible to declare a package after declaring an import file?
148)What is a ThreadGroup and why is it needed?
149)What is ThreadPool and why is it needed?
150)What is ThreadPoolExecutor and why is it needed?
151)What is Concurrency?
152)What are “atomic types” in Java?
153)Why do we need the ThreadLocal class?
154)What is the volatile modifier?
155)What is Executor?
156)What is ExecutorService?
157) Why do you need ScheduledExecutorService?
158)Name all the states of the Thread object.
159)What states can a thread go to when entering a synchronized block?
160)What state will the thread go to when calling the wait() method?
161)What state will the thread go to when calling the wait(500) method?
162)What state will the thread go to when calling the notify() method?
163)What state will the thread go to when calling the notifyAll() method?
164) Three threads in the synchronized block called the wait() method on the mutex object. What state will these threads go to if the fourth thread calls notifyAll()?
165)What is the difference between join(500) and wait(500)?
166)What is the difference between wait(500) and sleep(500)?
167)What state will the thread go to when calling the yield() method?
168)What access modifiers can be used with classes?
169)
170)Tell about abstract classes in Java.
171) Is it possible to describe a constructor in an abstract class?
171)What is an abstract method?
172)What are exceptions in Java?
173)Name several options for using the exception mechanism.
174)What is catching exceptions in Java?
175) How many exception handling methods do you know?
176)Name 5 keywords related to the Java engine.
177)Is it possible to use a try block without a catch block?
178)What is the importance of the finally block?
179)Is it possible to write code between try...catch blocks?
180) Is it possible to catch more than one exception in one catch block?
181)What are checked exceptions?
182)Talk about unchecked exceptions.
183)What is the keyword used for? throw?
184) Is it possible to write code after throw?
185)What is a keyword for? throws?
186)Is it possible that the finally block will not be executed? If yes, then when?
187) Is it possible to catch a checked exception in a catch block?
188)How can you create your own exception?
189)Is it possible to throw an exception from a catch block?
190)Can try blocks be nested?
191) In what case can you get a ClassNotFoundException?
192)A flow and a process are the same thing? If not, what's the difference?
193)What is multithreading in Java?
194)What are the advantages of multi-threaded programming?
195) How many ways to create a thread do you know?
196) What is the best approach to create a thread?
197)What do you know about the task scheduler in the JVM?
198)Is it possible to start a dead thread in Java?
199)Is it possible to restart a thread after starting?
200)What synchronization methods do you know?
201)What is a timed method?
202)Can threads enter a synchronized method if there is already one thread in it?
203)What is a synchronized block in Java?
204)Can static methods be synchronized?
205)How is thread priority used in Java?
206)How can I set or change the priority of a thread?
207)If two threads have the same priority, which one will start executing first?
208) Will the yielded thread get a chance to re-execute?
209)Explain the importance of join() method
210)What is a daemon in Java?
211)Is an object or reference destroyed by the garbage collector?
212)When and who can call the finalize() method in Java?
213) Give an example of enumeration in Java.
214)Is there a difference between collection, Collection and Collections in Java?
215)Which classes implement the List interface?

Show hidden content

1) ArrayList
2)Vector
3) LinkedList


216)What is the difference between ArrayList and LinkedList?
217)What is the Iterator class for and what methods does it have?
218)What is the difference between Comparator and Comparable?
219)What are the alternatives to serialization in Java?
220)How to make an object serializable?
221)What is serialVersionUID and is it necessary to define it?
222)What 2 methods are needed for an object to be a key in a HashMap?

Show hidden content

Before using an object as a key in a HashMap, you need to make sure that it has ( Right) equals and hashcode methods.


223)What is a Java applet? What do you know about him?

Show hidden content

A Java applet is a program in the Java language that can be embedded in HTML markup and executed directly in the browser on the client side. Applets are used to create dynamic and interactive pages.


224)Tell us about the life cycle of a java applet.

Show hidden content

An applet can be in the following states:
Init: The applet is initialized every time it is launched.
Start: Execution of the applet begins.
Stop: Stops the applet from running.
Destroy: Finishing and cleaning up after yourself. Release of resources, cleaning.


225)What happens when an applet is loaded?
226)What is the difference between an applet and a Java application?
227)What are the limitations of java applets?
228)What is an “untrusted applet”?
229)What is the difference between an applet downloaded from the Internet and an applet downloaded from the file system?
230)What is a class loader for applets?
231)What is and what does the applet security manager provide?

SWING

232)What is the difference between Choice and List?
233) What is a layout manager for?
234)What is the difference between Scrollbar and JScrollPane?
235)What are the thread-safe methods in SWING?

Show hidden content

There are only 3 thread-safe methods: repaint, revalidate, and invalidate.


236)Name 3 Component subclasses that support drawing.

Show hidden content

Canvas, Frame, Panel


237)What is clipping?
238)What is the difference between MenuItem and CheckboxMenuItem?
239)By what principle are elements arranged in a BorderLayout?
240)By what principle are elements arranged in GridBagLayout?
241)What is the difference between the Window and Frame classes?
242)Can a GUI component handle its own events?
243)What design pattern is used for all Swing components?

JDBC

244)What is JDBC?
245)What is the JDBC driver used for?
246)What is the purpose of the Class.forName method?
247)What are the advantages of PreparedStatement over Statement?

Remote Method Invocation (RMI)

248)What is RMI?
249)What basic principles of RMI architecture do you know?
250)What layers make up the RMI architecture?
251)What is the role of the remote interface in RMI?
252)What is java.rmi.Naming Class used for?
253)How do you understand binding in RMI?
254)What is the difference between using bind() and rebind() methods?
255)What are the steps required to run an RMI program?
256)What is a “stub” in RMI?
257)What is DGC and how does it work?
258)What is the purpose of using RMISecurityManager in RMI?
259) Give examples of Marshalling and demarshalling.
260) Give examples of Serialization and Deserialization.

Servlets

261)What is a servlet?
262)Give an example of servlet architecture.
263)What is the difference between Applet and Servlet?
264)What is the difference between GenericServlet and HttpServlet?
265) Explain the life cycle of a servlet.
266)What is the difference between doGet() and doPost()?
267)What does "Web Application" mean?
268)What is Server Side Include (SSI)?
269)What is a servlet chain?
270) How do you know that the client machine has sent a request to your servlet?
271)What is the structure of an HTTP header?
272)What is a cookie?
273)What protocol does the browser and servlet use?
274)What do you know about HTTP Tunneling?
275)What is URL Encoding and URL Decoding?

JSP

276)What is a JSP page?
277)How is a JSP request processed?
278)What are the advantages of using JSP?
279)What are directives? What are the different types of directives available in JSP?
280)What are JSP actions?
281) What are scripts (scriptlets, Scriptlets)?

General

282)What is the difference between JDK and JRE?
283)What is JVM?
284)Why is Java called a “platform independent” language?
285)What are the data types in Java?
286)What is Autoboxing and unboxing?
287)What is the difference between String and StringBuffer?
288)What is the difference between byte and character streams?
289)What are FileInputStream and FileOutputStream?
290)What are FileReader and FileWriter?
291)How to work with the SimpleDateFormat class?
292) How to get the string “21 Aug 1992” from an object of type Date?
293)What is ClassLoader?
294)Write a program that checks whether a number is even/odd.
295) Give an example of a double check for blocking in Singleton.
296)How to create a thread-safe singleton?
297)When are volatile variables used?
298)When are transient variables used?
299)What is the difference between volatile and transient variables?
300)Is it possible to override a private method?
301)What is the difference between List and Set?
302)What is the difference between PATH and Classpath in Java?
303)Can an abstract class have a constructor?
304)How to make an Immutable class?
305)What types of data are used to represent money?
306)What was the last design pattern you used?
307)How many reserved keywords are there in java? How many of them are used?
308)What characters cannot be used in a variable name?
309)What groups are data types in Java divided into?
310)What values ​​are assigned to different types by default?
311)What are the cyclic constructs in java? When and which one to use?
312) How do you understand the word “class”? Describe the term in your own words.
313)What initialization blocks do you know?
314) How to correctly implement the hashcode of an object?
315) Does it make sense to add a final modifier to a private method?
316)What are Queue type collections?
317)Is it possible to make a collection read-only? If yes, then for what? If not, why not?
318)What are the main differences between a stack and a queue?
319)What does the term “concatenation” mean?
320)How can you split a string into substrings using built-in java tools?
321)What will the execution of the same piece of code by different threads lead to?
322)How can I get a link to the current stream?
323)What conditions must be met before calling the wait/notify methods?
324)What is a mutex in case of a synchronized method?
325)What do you know about aggregate functions? How do they work with null value?
326)Describe the structure used in a web project.
327)What do you know about ServletConfig?
328) Methods required to be defined when creating servlets.
329)What is WWW?
330)What methods of data transfer via HTTP do you know?
331)What do you know about ORM?
332)What principles of OOP do you know? How do you know them? Do you use it?
333)What is included in a method signature? What's not included?
334)What is the peculiarity of initializing final static variables?
335)What are the differences and similarities between inner and nested classes?
336)What is the purpose of the abstract and final modifiers in relation to methods and classes.
337)Can exceptions from different inheritance branches be caught in one catch block?
338)What is Error? What is it used for?
339)What are the features of Set type collections?
340)Is it possible to obtain a synchronized collection from an unsynchronized one?
341)Give an example of a ConcurrentModificationException being thrown.
342)Is it possible to inherit from a string type?
343)What method can you use to cut out a substring?
344)What are the main classes in the I/O mechanism in Java?
345)Which character is used as a separator when specifying the path to file system elements in Java?
346)When should you consider using multithreading in an application? Is multithreading always good?
347)What are daemon threads for? Are there angel streams?
348)Where is the join method used?
349)What are the implicit, internal JSP EL objects? How are they different from jsp objects?
350)What is the life cycle of a servlet? What methods are called during its stages?
351)What is the difference between encodeUrl() and encodeRedirectUrl()?
352)What are the differences between a web server and an application server?
353)What do you know about AJAX? What principles underlie this technology?
354)What are the primitive types and how much space do they take up in memory?
355)What are logical operations in Java?
356)What is a bit shift? What mathematical operation corresponds to it?
357)Which operator can be used to immediately terminate the execution of a loop?
358)Can the number of arguments passed to a method be changed?
359)How to correctly initialize static and non-static fields?
360)Can a method be abstract and static at the same time?
361)Can a class be static?
362)What modifiers do fields and interface methods have by default?
363)Which method returns a string description of an object?
364)What can you use to get to the private fields of a class? Is it possible?
365)Can a child extend the visibility of a private method of a parent class?
366)What do you know about MVC? What is the principle of its operation?
367)Is there any point in jvm error handling?
368)Are there situations where a finally block is not executed?
369)The method can throw IOException and FileNotFoundException. What order should catch blocks have?
370)What are List type collections?
371)What implementations of SortedSet do you know?
372)Which collections are synchronized?
373)What is the implementation of the foreach method?
374)What are fail-safe and fail-fast properties?
375)What do you know about sorting algorithms?
376)How to expand a line backwards?
377)What do you know about the string pool?
378)What is the easiest way to find the required character in a string?

Dear users! If you have any interesting java junior interview questions, send it to me by email [email protected] or

This section is devoted to questions that may be asked during an interview for the position of a Java programmer.

The goal is to collect not only questions (there are a lot of them on the Internet), but also answers to them in one place.

For attribution information, read the main page of the Interview section.

  1. How many keywords are reserved by the language, what are these words, which ones are not used?
  2. What characters can a variable name (correct identifier) ​​consist of?
  3. What does the word “initialization” mean?
  4. What main groups can data types be divided into?
  5. What primitive types do you know?
  6. What do you know about converting primitive data types, is there data loss, is it possible to convert a boolean type?
  7. What values ​​are default variables initialized to?
  8. How is the value of a variable passed (by reference/value)?
  9. What do you know about the main function, what are the prerequisites for its definition?
  10. What logical operations and operators do you know?
  11. What is the difference between the short and full notation of logical operators?
  12. What is a truth table?
  13. What is the ternary select operator?
  14. What unary and binary arithmetic operations do you know?
  15. What bitwise operations do you know?
  16. What is the role and rules for writing the switch operator?
  17. What cycles do you know, what are their differences?
  18. What is a “loop iteration”?
  19. What parameters does the for loop have, is it possible not to specify them?
  20. Which statement is used to stop the loop immediately?
  21. Which statement is used to move to the next iteration of the loop?
  22. What is an array?
  23. What types of arrays do you know?
  24. What do you know about wrapper classes?
  25. What is auto-packing (boxing/unboxing)?

  1. Name the principles of OOP and tell us about each.
  2. Define the concept of “class”.
  3. What is a class field/attribute?
  4. How to properly organize access to class fields?
  5. Define the concept of “constructor”.
  6. What is the difference between default, copy and parameter constructors?
  7. What access level modifications do you know, tell us about each of them.
  8. Tell us about the features of a class with a single private constructor.
  9. What do the keywords “this”, “super” mean, where and how can they be used?
  10. Define the concept of “method”.
  11. What is a method signature?
  12. What methods are called overloaded?
  13. Can non-static methods overload static ones?
  14. Tell us about method overriding.
  15. Can a method take a different number of parameters (variable length arguments)?
  16. Is it possible to narrow the access level/return type when overriding a method?
  17. How to access overridden methods of a parent class?
  18. What transformations are called downward and upward?
  19. What is the difference between overriding and overloading?
  20. Where can I initialize static/non-static fields?
  21. Why is the instanceof operator needed?
  22. Why are initialization blocks needed and what are they?
  23. What is the order of calling the constructors and initialization blocks of two classes: a child and its ancestor?
  24. Where and for what is the abstract modifier used?
  25. Is it possible to declare a method abstract and static at the same time?
  26. What does the static keyword mean?
  27. To which Java constructs does the static modifier apply?
  28. What happens if an exception occurs in a static block of code?
  29. Is it possible to overload a static method?
  30. What is a static class, what are the features of its use?
  31. What are the features of initializing final static variables?
  32. How does the static modifier affect a class/method/field?
  33. What does the final keyword mean?
  34. Define the concept of “interface”.
  35. What default modifiers do fields and interface methods have?
  36. Why can't you declare an interface method with the final or static modifier?
  37. What types of classes are there in java (nested... etc.)
  38. What are the features of creating nested classes: simple and static.
  39. What do you know about nested classes, why are they used? Classification, use cases, encapsulation violation.
  40. What is the difference between nested and inner classes?
  41. What classes are called anonymous?
  42. How can I access a field in an outer class from a nested class?
  43. How can you access a local variable of a method from an anonymous class declared in the body of this method? Are there any restrictions for such a variable?
  44. How is any user class related to the Object class?
  45. Explain each of the methods of the Object class.
  46. What is the equals() method? How is it different from the == operation.
  47. If you want to override equals(), what conditions must be satisfied for the overridden method?
  48. If equals() is overridden, are there any other methods that should be overridden?
  49. What is special about the hashCode and equals methods? How are the hashCode and equals methods implemented in the Object class? What rules and conventions exist to implement these methods? When are they used?
  50. Which method returns a string representation of an object?
  51. What happens if you override equals without overriding hashCode? What problems might arise?
  52. Are there any recommendations on what fields should be used when calculating hashCode?
  53. Do you think there will be any problems if the object that is used as the key in the hashMap changes the field that is involved in determining the hashCode?
  54. What is the difference between an abstract class and an interface, and in what cases will you use which?
  55. Is it possible to access private class variables and if so, how?
  56. What are volatile and transient? For what and in what cases could default be used?
  57. Expanding modifiers when inheriting, overriding, and hiding methods. If a parent class has a method declared private, can the descendant extend its visibility? What if protected? How about narrowing visibility?
  58. Does it make sense to declare a method private final?
  59. What are the features of initializing final variables?
  60. What happens if the only constructor of a class is declared final?
  61. What is finalize? Why is it needed? What can you tell us about the garbage collector and its algorithms?
  62. Why is the clone method declared protected? What is needed to implement cloning?
  63. Are you familiar with any design patterns?
  64. Write Singleton... And with lazy loading. What if it needs to be thread-safe? And in what cases is lazy loading worse?
  65. What can you say about MVC? Draw a diagram and explain how MVC works.
  66. Write a function to calculate factorial.
  67. A function for calculating Fibonacci numbers is given, it is known that it works. Find the logical fallacy. Estimate the complexity of the resulting algorithm.

  1. Define the concept of “exception”
  2. What is the hierarchy of exceptions.
  3. Is it possible/needed to handle jvm errors?
  4. What are the different ways to handle exceptions?
  5. What does the throws keyword mean?
  6. What is special about the finally block? Is it always fulfilled?
  7. Is it possible to not have a single catch block when catching exceptions?
  8. Could you think of a situation where the finally block will not be executed?
  9. Can one catch block catch multiple exceptions (from the same and different inheritance branches)?
  10. What do you know about checked/unchecked exceptions?
  11. What is special about RuntimeException?
  12. How to write your own (“custom”) exception? What motives will guide you when choosing the exception type: checked/unchecked?
  13. Which operator allows you to force an exception to be thrown?
  14. Are there additional conditions to a method that could potentially throw an exception?
  15. Can the main method throw an exception externally, and if so, where will this exception be handled?
  16. If a return statement is contained in both a catch block and a finally block, which one is more important?
  17. What do you know about OutOfMemoryError?
  18. What do you know about SQLException? Which checked or unchecked type does it belong to, and why?
  19. What is Error? When is Error used? Give an example of Error.
  20. Which construct is used in Java to handle exceptions?
  21. Let's say there is a try-finally block. An exception occurred in the try block and execution moved to the finally block. An exception also occurred in the finally block. Which of the two exceptions will “throw” from the try-finally block? What happens to the second exception?
  22. Suppose there is a method that can throw IOException and FileNotFoundException, in what order should the catch blocks go? How many catch blocks will be executed?

  1. Define the concept of “collection”.
  2. List the benefits of using collections.
  3. What data can collections store?
  4. What is the collection hierarchy?
  5. What do you know about List collections?
  6. What do you know about Set collections?
  7. What do you know about Queue type collections?
  8. What do you know about Map type collections, what are their fundamental differences?
  9. Name the main implementations of List, Set, Map.
  10. What SortedSet implementations do you know and what are their features?
  11. What are the differences/similarities between List and Set?
  12. What is different/common between the ArrayList and LinkedList classes, when is it better to use an ArrayList and when to use a LinkedList?
  13. When is it wise to use an array rather than an ArrayList?
  14. What is the difference between ArrayList and Vector?
  15. What do you know about the implementation of the HashSet and TreeSet classes?
  16. What is the difference between HashMap and TreeMap? How are they structured and work? What about the access time to objects, what are the dependencies?
  17. What is Hashtable, how is it different from HashMap? Today it is deprecated, how can you still use the required functionality?
  18. What happens if you put two values ​​with the same key in a Map?
  19. How is the order of objects in a collection determined, how can a collection be sorted?
  20. Define the term “iterator”.
  21. What functionality does the Collections class provide?
  22. How to get a non-modifiable collection?
  23. Which collections are synced?
  24. How to get a synchronized collection from an unsynced one?
  25. How to get a read-only collection?
  26. Why doesn't Map inherit from Collection?
  27. What is the difference between Iterator and Enumeration?
  28. How is the foreach loop implemented?
  29. Why is there no iterator.add() method to add elements to the collection?
  30. Why doesn't the iterator class have a method to get the next element without moving the cursor?
  31. What is the difference between Iterator and ListIterator?
  32. What are the ways to iterate over all elements of a List?
  33. What is the difference between fail-safe and fail-fast properties?
  34. What should I do to avoid a ConcurrentModificationException?
  35. What is a stack and a queue, tell us what their differences are?
  36. What is the difference between Comparable and Comparator interfaces?
  37. Why don't collections inherit the Cloneable and Serializable interfaces?

  1. What “string” classes do you know?
  2. What are the main properties of “string” classes (their features)?
  3. Is it possible to inherit a string type, why?
  4. Define the concept of string concatenation.
  5. How to convert a string to a number?
  6. How to compare the value of two strings?
  7. How to reverse a string?
  8. How does comparing two strings work?
  9. How to trim spaces at the end of a line?
  10. How to replace a character in a string?
  11. How to get part of a string?
  12. Define the concept of “string pool”.
  13. Which method allows you to select a substring in a string?
  14. How to split a string into substrings using a given delimiter?
  15. Which method is called to convert a variable to a string?
  16. How to find out the meaning of a specific character in a string, knowing its serial number in the string?
  17. How to find the required character in a string?
  18. Is it possible to synchronize row access?
  19. What does the intern() method do?
  20. What is the difference and what do the String, StringBuffer and StringBuilder classes have in common?
  21. How to correctly compare the string values ​​of two different objects of type String and StringBuffer?
  22. Why is string immutable and finalized in Java?
  23. Why is a character array preferable to a string for storing a password?
  24. Why is String a popular key in HashMap in Java?
  25. Write a method to remove a given character from a string.

  1. What types of I/O streams are there?
  2. Name the main ancestors of I/O streams.
  3. What do the following streams have in common and how do they differ: InputStream, OutputStream, Reader, Writer?
  4. What do you know about RandomAccessFile?
  5. What are the file access modes?
  6. What packages contain thread classes?
  7. What do you know about superclasses?
  8. Which add-on class allows you to read data from an input byte stream in the format of primitive data types?
  9. What add-on class allows you to speed up reading/writing by using a buffer?
  10. What classes allow you to convert byte streams to character streams and vice versa?
  11. Which class is designed to work with file system elements (EFS)?
  12. What character is the separator when specifying the path to the EFS?
  13. How to select all EFS of a certain directory by criterion (for example, with a certain extension)?
  14. What do you know about the FilenameFilter interface?
  15. What is serialization?
  16. What are the conditions for “successful” serialization of an object?
  17. What classes allow you to archive objects?

  1. Define the concept of “process”.
  2. Define the concept of “flow”.
  3. Define the concept of “thread synchronization”.
  4. How do programs, processes, and threads interact?
  5. When is it appropriate to create multiple threads?
  6. What can happen if two threads execute the same code in a program?
  7. What do you know about the main thread of a program?
  8. What are the ways to create and run threads?
  9. Which method starts a thread for execution?
  10. Which method describes the action of a thread during execution?
  11. When does the thread complete its execution?
  12. How to synchronize a method?
  13. How to forcefully stop a thread?
  14. Define the concept of “daemon thread”.
  15. How to create a daemon thread?
  16. How to get the current thread?
  17. Define the term “monitor”.
  18. How to pause a thread?
  19. What states can a flow be in?
  20. What is the monitor when calling a non-static and static method?
  21. What is the monitor when executing a section of method code?
  22. What methods allow you to synchronize the execution of threads?
  23. Which method puts a thread into standby mode?
  24. What is the functionality of the notify and notifyAll methods?
  25. What does the join method do?
  26. What are the conditions for calling the wait/notify method?
  27. Define the concept of “mutual blocking”.
  28. What is the difference between the interrupt, interrupted, and isInterrupted methods?
  29. In what case will an InterruptedException be thrown, what methods can throw it?
  30. Volatile modifiers and the yield() method.
  31. Package java.util.concurrent
  32. There is some method that performs the i++ operation. Variable i of type int. It is assumed that the code will be executed in a multi-threaded environment. Should the block be synchronized?
  33. What is used as a mutex if the method is declared static synchronized? Is it possible to create new instances of a class while a static synchronized method is running?
  34. Suppose a RuntimeException occurred in the run method and was not caught. What will happen to the flow? Is there a way to know that an Exception has occurred (without wrapping the entire body of run in a try-catch block)? Is there a way to restore the thread after this has happened?
  35. What standard Java tools would you use to implement a thread pool?
  36. What is ThreadGroup and why is it needed?
  37. What is ThreadPool and why is it needed?
  38. What is ThreadPoolExecutor and why is it needed?
  39. What are "atomic types" in Java?
  40. Why do we need the ThreadLocal class?
  41. What is Executor?
  42. What is ExecutorService?
  43. Why do you need ScheduledExecutorService?
This list of 300+ questions (unanswered) was found at http://becomejavasenior.com/. Other authors are also listed there.

58489 Total Views 15 Views Today

Views: 38,283

I moved to another city, I’m getting a job, I’m going for interviews. It seemed to me that the questions asked there, although well-known, nevertheless, put together, can help you prepare and feel more confident.

Questions to help you understand the principles of building a DBMS.
1. What is first normal form and the normalization process? What are the normal forms?
2. What is the meaning of a DBMS index, how are they structured, how are they stored? How would you implement the same functionality? The last question is asked if there is no clear understanding of the indices.
3. Draw a Many-to-Many relationship. For example: Authors and Books tables. One author can have several books, and a book can be written by several authors. Write an SQL query to select books by a specific author.

Basic questions about Java.
4. The base class in Java is known as Object. What methods can you name?
5. Tell us what equals and hashCode are? What rules and conventions exist to implement these methods? When are they used?
6. Explain the wait, notify, notifyAll methods. How are they used, when, why are they needed? What is synchronized?
7. What is finalize? Why is it needed? What can you tell us about the garbage collector and its algorithms?
8. Why is the clone method declared protected? What is needed to implement cloning?
9. What modifiers are there (access and others)? What are volatile and transient? For what and in what cases could default be used?

Java Collection Framework
10. What are the collection interfaces in Java? Explain how they differ.
11. What implementations of these interfaces do you know?
12. How do ArrayList and LinkedList differ from each other? How are they built? In what cases should they be used?
13. What is the difference between HashMap and TreeMap? How are they structured and work? What about the access time to objects, what are the dependencies?
14. What is a Hashtable, how is it different from a HashMap? Today it is deprecated, how can you still use the required functionality?

Exceptions
15. What is an exception? What types of exceptions do you know and how do they differ?
16. Maybe a problem with try-catch-finally blocks and the question of what will be returned or what exception will be ultimately passed up?

Algorithms
17. What sorting algorithms do you know? What kind of algorithms do you know?
Moreover, here various additional questions are possible about assessing the complexity of algorithms and their comparison with each other.

Design patterns.
18. Are you familiar with any design patterns?
19. Write a Singleton... And with lazy loading. What if it needs to be thread-safe? And in what cases is lazy loading worse?
20. What can you say about MVC? Draw a diagram and explain how MVC works.

A series of questions to help you understand the J2EE technology stack.
21. What is a servlet, jsp, their difference?
22. What is Ajax? How does this technology fundamentally work?
23. What is ORM, how to translate it and how should it work?

Simple problems for writing algorithms.
24. Write a function to calculate factorial.
25. A function for calculating Fibonacci numbers is given, it is known that it works. Find the logical fallacy. Estimate the complexity of the resulting algorithm.
26. Reverse the line.
27. Calculate the average of the array.

It is useful to remember that if you are not feeling very confident, there is no need to say unnecessary words. You say an extra word, and they cling to it, unwinding the chain. They are promoting something that they are not very sure about. This ability of people - to cling - must be used, but with benefit for yourself;-)

Knowledge and understanding... things are quite different, so
- different algorithms, for example sorting, are worth writing yourself, even from a textbook. See how different they are from each other, compare their complexity.
- it is useful to look at different utilities and libraries, the principles of grouping classes into packages and the style of writing code and commenting. It can be very helpful in understanding access modifiers and project organization.
- by understanding something specific, you can help those who know less. Go to any forum and try to answer questions on a topic that is interesting to you. You can take something for yourself from the discussion. You can write a short article. Of course, you need to have a good understanding of the topic.
Any work aimed at improving one’s own qualifications will be visible to a competent interviewer and will not go unnoticed. The only thing is that you need to talk about it honestly, you should not underestimate your capabilities and abilities.
To have any guideline for preparing or developing yourself as a specialist, you can look at something similar to this.

Actually, the questions listed above are the Junior Developer level, as I imagine it. Somewhere, maybe more deeply, somewhere less, but as a fact - Junior.

Every solution creates new problems

  • What is OOP?
  • What is an object?
  • What are the basic principles of OOP?
  • What is inheritance?
  • What is polymorphism? What manifestations of polymorphism in Java do you know?
  • What is encapsulation?
  • What is abstraction?
  • What are the advantages of object-oriented programming languages?
  • How does using an object-oriented approach improve software development?
  • There is an expression “is” and “has”. What do they mean in terms of OOP principles? What is the difference between composition and aggregation?
  • What do you mean by polymorphism, encapsulation and dynamic binding?

Java core.

  • What is the difference between JRE, JVM and JDK?
  • Describe access modifiers in Java.
  • What is package level access.
  • How is an abstract class different from an interface? In what cases would you use an abstract class and in what cases would you use an interface?
  • Can an object access a private class variable? If yes, then how?
  • Why are there static blocks in Java?
  • Is it possible to overload a static method?
  • Tell us about internal classes. When will you use them?
  • What is the difference between an instance variable and a static variable? Give an example.
  • Give an example when you can use a static method?
  • Tell us about loader classes and dynamic class loading.
  • What is the "assert" statement used in Java?
  • Why do some interfaces not define methods at all?
  • What is the main difference between String, StringBuffer, StringBuilder?
  • Explain about Java I/O streams.
  • What is Heap and Stack memory in Java?
  • What is the difference between Stack and Heap memory in Java?
  • Tell us about the memory model in Java?
  • How does the garbage collector work?
  • Tell us about type casting. What is type demotion and promotion? When do you get a ClassCastException?
  • What is a static class, what are the features of its use?
  • How to access a field of an outer class from a nested class.
  • What types of nested classes are there? What are they used for?
  • Is it possible to change when overriding a method:
  • Access modifier
  • Return type
  • Argument type or quantity
  • Argument name
  • Should I change the order, quantity, or remove the throws section altogether?
  • What is autoboxing?
  • What are Generics?
  • What is the real purpose of using generic types in Java?
  • How are variables passed to methods, by value or by reference?
  • What methods does the Object class have?
  • Rules for overriding the Object.equals() method.
  • If you want to override equals(), what conditions must be satisfied for the overridden method?
  • What is the relationship between hashCode and equals?
  • How are the hashCode and equals methods implemented in the Object class?
  • What happens if you override equals without overriding hashCode? What problems might arise?
  • Are there any recommendations on what fields should be used when calculating hashCode?
  • What is the hashCode() method for?
  • Rules for overriding the Object.hashCode() method.
  • Tell us about cloning objects. What is the difference between shallow and deep cloning?
  • Rules for overriding the Object.clone() method.
  • Where and how can you use a private constructor?
  • What is the default constructor?
  • Describe the Object.finalize() method.
  • What is the difference between final, finally and finalize?
  • Describe the hierarchy of exceptions.
  • What types of exceptions in Java do you know, how do they differ?
  • What is checked and unchecked Exception?
  • How to create your own unchecked Exception?
  • What are Unchecke exceptions?
  • What is Error?
  • Describe the operation of the try-catch-finally block.
  • Is it possible to use a try-finally block (without catch)?
  • Is the finally block always executed?
  • What are the features of the String class? what does the intern() method do?
  • Is it possible to inherit a string type, why?
  • Why is String a popular key in HashMap in Java?
  • Define the concept of string concatenation.
  • How to reverse a string?
  • How to compare the value of two strings?
  • How to trim spaces at the beginning and end of a line?
  • Define the concept of "string pool".
  • Is it possible to synchronize row access?
  • How to correctly compare the string values ​​of two different objects of type String and StringBuffer?
  • Why is string immutable and finalized in Java?
  • Write a method to remove a given character from a string.
  • What is reflection?
  • What happens to the garbage collector (GC) if an exception occurs during the finalize() method of some object?
  • What is internationalization, localization?
  • What are Annotations in Java?
  • What functions does Annotation perform?
  • What built-in annotations in Java do you know?
  • What do the @Retention, @Documented, @Target and @Inherited annotations do?
  • What do the @Override, @Deprecated, @SafeVarargs and @SuppressWarnings annotations do?
  • What annotation lifecycle can be specified using @Retention?
  • What elements can annotation be applied to, and how can I indicate this?
  • How to create your own Annotation?
  • What types of attributes are allowed in annotations?
  • What is JMX?
  • What benefits does JMX offer?
  • What else can JMX do besides remote control?
  • What is an MBean?
  • What types of MBeans are there?
  • What is MBean Server?
  • What mechanisms provide security in Java technology?
  • Name several types of checks that the Java bytecode verifier performs?
  • What do you know about the "security manager" in Java?
  • What is JAAS?
  • What is Refactoring?

Java Collections Framework.

  • What is a Collection?
  • Name the main interfaces of collections and their implementations.
  • How is ArrayList different from LinkedList? In what cases is it better to use the first one, and in what cases the second one?
  • How is HashMap different from Hashtable?
  • What is the difference between ArrayList and Vector?
  • How are collection elements compared?
  • Arrange the following interfaces in a hierarchy: List, Set, Map, SortedSet, SortedMap, Collection, Iterable, Iterator, NavigableSet, NavigableMap.
  • Why is Map not a Collection while List and Set are Collections?
  • Define the term "iterator".
  • What do you know about the Iterable interface?
  • How to convert a HashSet to an ArrayList in one line?
  • How to convert an ArrayList to a HashSet in one line?
  • How to iterate over all the keys of a Map, given that Map is not Iterable?
  • How to iterate over all Map values ​​given that Map is not Iterable?
  • How to iterate through all key-value pairs in a Map given that Map is not Iterable?
  • How is SortedMap “sorted”, other than the fact that toString() displays everything in order?
  • How to copy elements from any Collection into an array with one call?
  • Implement the symmetric difference of two collections using the Collection methods (addAll(), removeAll(), retainAll()).
  • Compare Enumeration and Iterator.
  • How are Iterable and Iterator related?
  • How are Iterable, Iterator and "for-each" introduced in Java 5 related to each other?
  • Compare Iterator and ListIterator.
  • What happens if I call Iterator.next() without "asking" Iterator.hasNext()?
  • What happens if I call Iterator.next() before calling Iterator.hasNext() 10 times? Am I missing 9 elements?
  • If I have a collection and a child iterator, will the collection change if I call iterator.remove()?
  • If I have a collection and a child iterator, will the iterator change if I call collection.remove(..)?
  • Why did they add ArrayList if there was already a Vector?
  • The implementation of the ArrayList class has the following fields: Object elementData, int size. Explain why store size separately if you can always take elementData.length?
  • Is LinkedList a singly linked list, a doubly linked list, or a four linked list?
  • What is the worst running time of the contain() method for an element that is in LinkedList (O(1), O(log(N)), O(N), O(N*log(N)), O(N*N) )?
  • What is the worst running time of the contain() method for an element that is in an ArrayList (O(1), O(log(N)), O(N), O(N*log(N)), O(N*N) )?
  • What is the worst running time for the add() method on LinkedList (O(1), O(log(N)), O(N), O(N*log(N)), O(N*N))?
  • What is the worst running time of the add() method for ArrayList (O(1), O(log(N)), O(N), O(N*log(N)), O(N*N))?
  • How many elements are allocated in memory when calling ArrayList.add()?
  • How many elements are allocated in memory when calling LinkedList.add()?
  • Estimate the amount of memory for storing one byte primitive in LinkedList?
  • Estimate the amount of memory for storing one byte primitive in an ArrayList?
  • I add an element to the middle of the List: list.add(list.size()/2, newElem). For whom is this operation slower - for ArrayList or for LinkedList?
  • How to iterate through LinkedList elements in reverse order without using slow get(index)?
  • How to get a List with all elements except the first and last 3 with one call from List?
  • Can different objects in memory (ref0 != ref1) have ref0.hashCode() == ref1.hashCode()?
  • Can different objects in memory (ref0 != ref1) have ref0.equals(ref1) == true?
  • Can different references to the same object in memory (ref0 == ref1) have ref0.equals(ref1) == false?
  • There is a class Point(int x, y;). Why is hash code 31 * x + y preferable to x + y?
  • If the class Point(int x, y;) has the "correct" implementation of the equals method (return ref0.x == ref1.x && ref0.y == ref1.y), but make the hash code in the form int hashCode() ( return x;), then will such points be correctly placed and retrieved from the HashSet?
  • equals() generates an equivalence relation. What properties does this relation have: commutativity, symmetry, reflexivity, distributivity, associativity, transitivity?
  • Is it possible to implement equals(Object that) (return this.hashCode() == that.hashCode()) like this?
  • equals requires checking that the argument (equals(Object that)) is the same type as the object itself. What is the difference between this.getClass() == that.getClass() and that instanceof MyClass?
  • Is it possible to implement the equals method of the MyClass class like this: class MyClass (public boolean equals(MyClass that) (return this == that;))?
  • Will HashMap work if all keys return int hashCode() (return 42;)?
  • Why did they add HashMap if there was already a Hashtable?
  • According to Knuth and Cormen, there are two main hash table implementations: open addressing based and chaining based. How is HashMap implemented? Why did they do this (in your opinion)? What are the pros and cons of each approach?
  • How many link clicks occur when you do HashMap.get(key) on a key that is in a table?
  • How many new objects are created when you add a new element to a HashMap?
  • How does a HashMap work when you try to store two elements into it by keys with the same hashCode, but for which equals == false?
  • A HashMap can degenerate into a list even for keys with different hashCodes. How is this possible?
  • What is the worst running time of the get(key) method for a key that is not in the table (O(1), O(log(N)), O(N), O(N*log(N)), O(N*N ))?
  • What is the worst running time of the get(key) method for a key that is in the table (O(1), O(log(N)), O(N), O(N*log(N)), O(N*N ))?
  • Explain the meaning of the parameters in the HashMap(int initialCapacity, float loadFactor) constructor.
  • What is the difference between HashMap and IdentityHashMap? What is IdentityHashMap for? How can it be useful for implementing serialization or cloning?
  • What is the difference between HashMap and WeakHashMap? What is WeakHashMap for?
  • WeakHashMap uses WeakReferences. Why not create a SoftHashMap on SoftReferences?
  • WeakHashMap uses WeakReferences. Why not create a PhantomHashMap on PhantomReferences?
  • Make a HashSet from a HashMap (only use a set of keys, not a set of values).
  • Make a HashMap from a HashSet (HashSet >).
  • Compare the java.util.Queue and java.util.Deque interfaces.
  • Who extends whom: Queue extends Deque, or Deque extends Queue?
  • Why does LinkedList implement both List and Deque?
  • What is the difference between the java.util.Arrays and java.lang.reflect.Array classes?
  • What is the difference between the java.util.Collection and java.util.Collections classes?
  • Write a MULTI-threaded program that causes a collection to throw a ConcurrentModificationException.
  • What is "fail-fast behavior"?
  • Is there a special class java.util.EnumSet for sets of enums? For what? Why weren't the authors satisfied with HashSet or TreeSet?
  • java.util.Stack - considered "obsolete". What is recommended to replace it with? Why?
  • Which collection implements the FIFO service discipline?
  • Which collection implements the FILO service discipline?
  • Give an example when any collection throws UnsupportedOperationException.
  • Why can't I write "ArrayList" numbers = new ArrayList ();" but you can "List numbers = new ArrayList ();"?
  • LinkedHashMap - what kind of “beast” is this? What is LinkedList and what is HashMap?
  • LinkedHashSet - what kind of “beast” is this? What is LinkedList and what is HashSet?
  • They say it’s easy to make a simple cache with an “invalidation policy” on LinkedHashMap, do you know how?
  • What does PriorityQueue allow you to do?
  • What are the differences between java.util.Comparator and java.lang.Comparable?

Java 8.

  • What is a symbolic link?
  • What's the difference between I/O and NIO?
  • What features of NIO do you know?
  • What types of I/O streams are there?
  • Name the main classes of I/O streams.
  • What is the difference and what do OutputStream, InputStream, Writer, Reader have in common?
  • What subclasses of the InputStream base class do you know and what do they do?
  • What do you know about RandomAccessFile?
  • What file access modes does RandomAccessFile have?
  • What subclasses of the OutputStream base class do you know and what do they do?
  • What is PushbackInputStream used for?
  • What is SequenceInputStream used for?
  • What subclasses of the base class Reader do you know and what are they for?
  • What subclasses of the Writer base class do you know and what do they do?
  • What is absolute path and relative path?
  • What packages contain thread classes?
  • What do you know about superclasses?
  • Which add-on class allows you to read data from an input byte stream in the format of primitive data types?
  • What add-on class allows you to speed up reading/writing by using a buffer?
  • What classes allow you to convert byte streams to character streams and vice versa?
  • What is the difference between the PrintWriter class and PrintStream?
  • Which class is designed to work with file system elements?
  • What character is the separator when specifying a path in a file system?
  • What methods of the File class do you know?
  • What do you know about the FileFilter interface?
  • What classes allow you to archive objects?

  • On what object does synchronization occur when calling a static synchronized method?
  • What is the keyword volatile, synchronized, transient, native used for?
  • What does thread priority mean?
  • What are daemon threads in Java?
  • What does it mean to put the flow to sleep?
  • What states can a thread exist in in Java? How does flow actually work?
  • What is the difference between the two interfaces for implementing Runnable and Callable tasks?
  • Differences between CyclicBarrier and CountDownLatch?
  • What is a race condition?
  • How to stop the thread?
  • What happens when a thread throws an exception?
  • What is a ThreadLocal variable?
  • What is FutureTask?
  • Difference between interrupted and isInterrupted?
  • Why are the wait and notify methods called in a synchronized block?
  • What is a thread pool?
  • Differences between livelock and deadlock?
  • How to check if a thread is holding a lock?
  • How to get a thread dump?
  • What JVM parameter is used to control the thread's stack size?
  • Differences between synchronized and ReentrantLock?
  • What is Semaphore?
  • What happens if the thread pool queue is already full and you submit a task?
  • Differences between submit() and execute() methods on a thread pool?
  • What is a blocking method?
  • What is ReadWriteLock?
  • What is Singleton's double checked locking?
  • What is the Fork/Join framework?
  • For those who hear the word Java Core for the first time, these are the fundamental foundations of the language. With this knowledge, you can safely go for an internship/internship. These questions will help you refresh your knowledge before the interview, or learn something new for yourself. To gain practical skills, study at.

      How to create an immutable object in Java? List all the benefits

      An immutable class is a class whose state cannot be changed after creation. Here, the state of an object is essentially considered to be the values ​​stored in an instance of a class, be it primitive types or reference types.

      In order to make a class immutable, the following conditions must be met:

      1. Do not provide setters or methods that modify fields or objects that refer to fields. Setters imply changing the state of an object, which is what we want to avoid here.
      2. Make all fields final and private. Fields marked private will not be accessible from outside the class, and designating them final ensures that you won't change them, even by accident.
      3. Don't allow subclasses to override methods. The easiest way to do this is to declare the class final. Finalized classes in Java cannot be overridden.
      4. Always remember that your variable instances can be either mutable or immutable. Define them and return new objects with copied content for all mutable objects (reference types). Immutable variables (primitive types) can be safely returned without any extra effort.

      Also, you need to remember the subsequent benefits of immutable classes. You may need them at an interview. Immutable classes:

      • easy to design, test and use
      • automatically thread safe and has no synchronization issues
      • do not require a copy constructor
      • allow you to lazily initialize a hashcode and cache the return value
      • do not require secure copying when used as a field
      • make good Map keys and Set elements (these objects should not change state when they are in the collection)
      • make your class permanent by creating it once, and it does not need to be checked again
      • always have “failure atomicity” (a term coined by Joshua Bloch): if an immutable object throws an exception, it will never remain in an unwanted or undefined state.

      Look at the example written in this post.

      The Java specification states that everything in Java is passed by value. There is no such thing as "pass by reference" in Java. These conditions are associated with calling methods and passing variables as method parameters. Okay, primitive types are always passed by value without any confusion. But, the concept should be clear in the context of a method parameter of complex types.


      In the example above, the address bits of the first instance are copied by another reference variable, causing both references to point to the same memory location where the object is stored. Remember that by assigning null to the second link, you will not assign null to the first link. But a change in the state of an object with one referencing variable will be reflected in another link.

      What is the use of a finally block? Does this block guarantee execution of its code? When is a finally block not called?

      The finally block is always called if the try block exists. This ensures that the finally block is called even if an unexpected exception occurs. But finally is more useful than just exception handling - this block allows you to clean up code that was accidentally bypassed through return , continue or break . Placing cleanup code in a finally block is always a good practice, even when no exceptions are expected.

      If the virtual machine exits while the try or catch block is executing, then the finally block will not be executed. Likewise, if a thread is executing a try or catch block and is interrupted or killed, the finally block will not be executed, even though the application continues to run.

      Why are there two Date classes, one in the java.util package and the other in java.sql?

      java.util.Date represents a date and time, while java.sql.Date represents only a date. Complementary to java.sql.Date is the java.sql.Time class, which represents only time.

      The java.sql.Date class is a subclass (extension) of the java.util.Date class. So what has changed in java.sql.Date:

      • toString() produces a different representation of the string: yyyy-mm-dd
      • static method valueOf(String) creates a date from a string with the above representation
      • getters and setters for hours, minutes and seconds are excluded

      The java.sql.Date class is used in JDBC and is designed to have no time component, meaning hours, minutes, seconds and milliseconds must be zero... but this is not required for the class.

      Explain marker interfaces.

      The interface-token pattern is a design pattern in computer science used by programming languages ​​that provide information about objects at run time. This provides a way to associate class metadata where the language does not have explicit support for such metadata. In Java, interfaces are used for this without specifying methods.

      A good example of a token interface in Java is the Serializable interface. A class implements this interface to indicate that its non-transient data can be written to a byte stream or to a file system.

      The main problem A marker interface is that the interface defines a convention for the classes that implement it, and that convention is inherited by all subclasses. This means that you will not be able to "de-implement" the token. In the example above, if you create a subclass that you don't want to serialize (perhaps because it is in a transient state), you must resort to explicitly throwing NotSerializableException.

      Why is the main() method declared as a public static void?

      Why public? The main method has a public access modifier, so it can be accessed everywhere and by any object that wants to use this method to run the application. Now I'm not saying that JDK/JRE have a similar reason, because java.exe or javaw.exe (for windows) use the Java Native Interface (JNI) call to run the method, so they can call it anyway, regardless of the access modifier .

      Why static? Let's assume that our main method is not static. Now, to call any method you need an instance of the class. Right? Java allows overloaded constructors, we all know that. Then which one should be used, and where will the parameters for the overloaded constructor come from?

      Why void? There is no use for the return value in the virtual machine that actually calls this method. The only thing the application will want to tell the calling process is whether it terminated normally or abnormally. This is already possible using System.exit(int) . A non-zero value implies abnormal completion, otherwise everything is ok.

      What is the difference between creating a string as new() and creating a literal (using double quotes)?

      When we create a string using new(), it is created in the heap and is also added to the string pool, while a string created using a literal is created only in the string pool.

      You will need to become more familiar with the concept of string pooling to answer this or similar questions. My advice is to really learn the String class and the string pool.

      How does the substring() method of the String class work?

      Like other programming languages, strings in Java are a sequence of characters. This class is more like a utility class for working with this sequence. The sequence of characters is provided by the following variable:

      /** The value is used for character storage. */ /** The value is used to store characters */ private final char value ; The following variables are used to access this array in various scenarios /** The offset is the first index of the storage that is used. */ /** Offset is the first index of the storage being used. */ private final int offset; /** The count is the number of characters in the String. */ /** Count is the number of characters in the line. */ private final int count;

      Each time we create a substring from an existing string instance, the substring() method only sets new values ​​for the offset and count variables. The internal character array does not change. This is a possible source of memory leak if the substring() method is used carelessly:

      The original value is not changed. So if you create a string that is 10000 characters long and create 100 substrings with 5-10 characters each, all 101 objects will contain the same 10000 character long character array. This is undoubtedly a waste of memory.

      This can be avoided by changing the code like this:

      replace original.substring(beginIndex) with new String(original.substring(beginIndex)) , where original is the original string.

      Explain the working of HashMap. How is the problem of duplicates solved?

      Most of you will probably agree that HashMap is the most favorite topic for discussion in interviews nowadays. If someone asks me to tell you “How does a HashMap work?”, I will simply answer: “Based on the principle of hashing.” As simple as it is.

      So, hashing is essentially a way to assign a unique code to any variable/object after applying any formula/algorithm to its properties.

      The definition of a Map is: “An object that associates keys with values.” Very simple, right? So, HashMap contains its own inner class Entry, which looks like:

      static class Entry implements Map . Entry( final K key; V value; Entry next; final int hash; …//More code goes here )

      When someone tries to put a key-value pair into a HashMap, the following happens:

      • First of all, the key object is checked for null . If the key is null, the value is stored in the table position. Because the hashcode for null is always 0.
      • Then, the next step is to calculate the hash value by calling the key variable's hashCode() method. This hash is used to calculate the index into the array to hold the Entry object. The JDK developers were well aware that the hashCode() method could be poorly written and could return a very large or very small value. To solve this problem, they introduced another hash() method, and pass the hashcode of the object to this method to cast that value to the array index size range.
      • Now the indexFor(hash, table.length) method is called to calculate the exact position to store the Entry object.
      • Now the main part. As we know two dissimilar objects can have the same hashcode value, how would two dissimilar objects be stored in the same location in an archive [called a recycle bin]?

      The answer is LinkedList. If you remember, the Entry class has a “next” property. This property always points to the next object in the chain. This behavior is very similar to LinkedList.

      So, in case of hashcode matches, the Entry objects are stored in the form of a LinkedList. When an Entry object needs to be placed at a specific index, HashMap checks to see if another Entry object exists at that location? If there is no entry there, our object will be saved in this location.

      If there is already another object at our index, its next field is checked. If it is null, our object becomes the next node in the LinkedList. If next is not null , this procedure is repeated until a next field that is null is found.

      What happens if we add another key value equal to the one we added earlier? It is logical that it should replace the old value. How does this happen? After determining the position index for the Entry object, iterating over the LinkedList located at our index, the HashMap calls the equals() method on the key value for each Entry object. All these Entry objects in the LinkedList have the same hashcode value, but the equals() method will check for real equality. If the key. equals(k) will be true, then both will be perceived as the same object. This will only cause the value object within the Entry object to be replaced.

      This way, HashMap ensures that the keys are unique.

      Differences between interfaces and abstract classes?

      This is a very common question if you are interviewing for a junior level programmer. The most significant differences are listed below:

      • In Java interfaces, variables are a priori final. Abstract classes can contain non-final variables.
      • An interface in Java absolutely cannot have an implementation. An abstract class can have method instances that implement basic behavior.
      • Interface components must be public. An abstract class can have access modifiers to suit any taste.
      • The interface must be implemented with the implements keyword. An abstract class must be extended with a keyword extends.
      • In Java, a class can implement many interfaces, but can only inherit from one abstract class.
      • An interface is completely abstract and cannot have instances. An abstract class also cannot have class instances, but can be called if a main() method exists.
      • An abstract class is slightly faster than an interface because the interface expects a lookup before calling any overridden method in Java. In most cases, this is a minor difference, but if you are writing a time-critical application, you need to take this fact into account.
    1. When do you override hashCode() and equals() methods?

      The hashCode() and equals() methods are defined in the Object class, which is the parent class of all Java objects. For this reason, all Java objects inherit the underlying implementation of these methods.

      The hashCode() method is used to obtain a unique integer value for a given object. This value is used to determine the location of the bucket when the object needs to be stored in a data structure like a HashTable. By default, the hashCode() method returns an integer representation of the memory address where the object is stored.

      The equals() method, as the name suggests, is used to perform simple object equivalence. The basic implementation of the method is to check the references of two objects to check if they are equivalent.

      Note that it is usually necessary to override the hashCode() method whenever the equals() method is overridden. This is necessary to support the general convention of the hashCode method, which states that equal objects must have equal hashcodes.

      The equals() method must determine equality between relations (it must be recurrent, symmetric, and transitive). In addition, it must be persistent (if the object has not changed, the method must return the same value). Also, o.equals(null) should always return false.

      hashCode() must also be persistent (if the object has not been modified by the conditions of the equals() method, it must continue to return the same value.

      The relationship between the two methods is: always if a.equals(b) then a.hashCode() must be the same as b.hashCode() .

    Good luck with your studies!! Author of the article Lokesh Gupta Original article Links to other parts: