Ideas.  Interesting.  Public catering.  Production.  Management.  Agriculture

Java interview questions. A guide for the future Java developer. Interview and career. Differences between interfaces and abstract classes

  • 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?

  • 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 inner 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?

  • 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 over 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 the 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?

  • 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?
  • 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, as you know, is 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

    We have collected 10 tricky examples of programs that display any information. You should look at the code and tell what the program will output. It is possible that the program will not even compile. In this case, you need to specify what the compiler will output.

    People like to ask questions like these during interviews, so it’s a good idea to brush up on your knowledge of the Java programming language. The answers will be hidden in the spoilers - what the program or compiler will output. Try to think for yourself before looking at the correct answer.

    Package com.instanceofjava; public class B ( B b = new B(); public int show())( return (true ? null: 0); ) public static void main(String args) ( B b = new B(); b.show() ; ) )

    • Every time we create an object of any class, the constructor is called first and memory is allocated for all non-static variables.
    • Here B b = new B(); an object of class B is assigned a new object of the same class.
    • Write B b = new B(); leads to recursive execution of the constructor, which creates infinite objects. This is why a java.lang.StackOverFlowError exception will be raised on the "main" thread when this code runs.
    • A common cause of these kinds of exceptions is bad recursion. This usually occurs due to an invalid termination condition.

    What will the following program output?

    package com.instanceofjava; public class A( public static void show())( System.out.println("Static method called"); ) public static void main(String args) ( A obj = null; obj.show(); ) )
    • We can call static methods using a variable referencing null . The point is that static methods are at the class level. This is why we can call static functions both using the class itself and using a variable equal to null .

    What will the following program output?

    package com.instanceofjava; public class A( static int a = 1111; static ( a = a-- - --a; ) ( a = a++ + ++a; ) public static void main(String args) ( System.out.println(a) ; ) )

    What will the following program output?

    package com.instanceofjava; public class A( int GetValue() ( return (true ? null: 0); ) public static void main(String args) ( A obj = new A(); obj.GetValue(); ) )

    What will the following program output?

    package com.instanceofjava; public class A( public static void main(String args) ( Integer i1 = 128; Integer i2 = 128; System.out.println(i1 == i2); Integer i3 = 127; Integer i4 = 127; System.out.println (i3 == i4); ) )

    What will the following program output?

    package com.instanceofjava; class A ( void method(int i) ( ) ) class B extends A ( @Override void method(Integer i) ( ) )
    • Which line of the program will cause a compile time error?
    package com.instanceofjava; class A ( public static void main(String args) ( Integer i = new Integer(null); String s = new String(null); ) )

    What will the following program output?

    package com.instanceofjava; class A ( public static void main(String args) ( String s = "ONE"+3+2+"TWO"+"THREE"+5+4+"FOUR"+"FIVE"+5; System.out.println (s); ) )

    What will the following program output?

    package com.instanceofjava; class A ( static int method1(int i) ( return method2(i *= 11); ) static int method2(int i) ( return method3(i /= 11); ) static int method3(int i) ( return method4( i -= 11); ) static int method4(int i) ( return i += 11; ) public static void main(String args) ( System.out.println(method1(11)); ) )

    What will the following program output?

    package com.instanceofjava; class A ( public static void main(String args) ( System.out.println(null); ) )

    What happens when you write System.out.println(null); ?

    Of course, a compilation error occurs. The println method has several variations. It can accept String, Object or char. When passing a null argument to this function, the compiler cannot decide which of the three methods to call.

    Overloaded methods:

    • public void prinltln(String str) (
    • public void prinltln(char ch) (
    • public void prinltln(Object ch) (

    For the compiler, calling System.out.println(null) is ambiguous, since two methods can be more or less suitable for outputting null ‘a: println(String) and println(char) . But the compiler does not know which specific method to call. For compilation to succeed, you should write:

    • System.out.println((String)null);
    • System.out.println((char)null);
    • System.out.println((Object)null);

    But here you need to be careful. Call System.out.println((char)null); will result in a runtime exception.

    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 the other 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 runtime. 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. The 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 particular 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:

    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 JavaRush.

      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 the other 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 runtime. 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. The 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 particular 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:
    Loading...