JavaRush /Java Blog /Random EN /Analysis of questions and answers from interviews for Jav...

Analysis of questions and answers from interviews for Java developer. Part 2

Published in the Random EN group
Hello again everyone! We continue to look for answers to 250+ questions for Junior, Middle and Senior developers. The questions are quite interesting, and I myself like to analyze them: at such moments you can discover gaps in theoretical knowledge, and in the most unexpected places. Analysis of interview questions and answers.  Part 2 - 1The previous part can be found in this article . But before we begin, I want to remind you that:
  1. I will skip questions that intersect with this series of articles so as not to duplicate information once again. I recommend reading these materials, as they contain the most common (popular) Java Core interview questions.
  2. Questions on DOU are presented in Ukrainian, but I will have everything here in Russian.
  3. The answers could be described in more detail, but I won’t, since then the answer to each question could take a whole article. And they won’t ask you in such detail at any interview.
If necessary, I will leave links for deeper study. Let's fly!

11. Name all the methods of the Object class

The Object class has 11 methods:
  • Class<?> getClass() — getting the class of the current object;
  • int hashCode() — getting the hash code of the current object;
  • boolean equals​(Object obj) - comparison of the current object with another;
  • Object clone() - creating and returning a copy of the current object;
  • String toString() — getting a string representation of an object;
  • void notify() - awakening one thread waiting on the monitor of this object (thread selection is random);
  • void notifyAll() - awakens all threads waiting on the monitor of this object;
  • void wait() - switches the current thread to wait mode (freezes it) on the current monitor, works only in a synchronized block until some notify or notifyAll wakes up the thread;
  • void wait(long timeout) - also freezes the current thread on the current monitor (on the current synchronized one), but with a timer to exit this state (or again: until notify or notifyAll wakes up);
  • void wait(long timeout, int nanos) - a method similar to the one described above, but with more precise timers for exiting freezing;
  • void finalize() - before deleting this object, the garbage collector calls this method (finally). It is used to clean up occupied resources.
To correctly use the hashCode , equals​ , clone , toString , and finalize methods, they must be redefined, taking into account the current task and circumstances.

12. What is the difference between try-with-resources and try-catch-finally when dealing with resources?

Typically, when using try-catch-finally, the final block was used to close resources. Java 7 introduced a new type of operator try-with-resources , an analogue of try-catch-finally for freeing resources, but more compact and readable. Let's remember what try-catch-finally looks like :
String text = "some text......";
BufferedWriter bufferedWriter = null;
try {
   bufferedWriter = new BufferedWriter(new FileWriter("someFileName"));
   bufferedWriter.write(text);
} catch (IOException e) {
   e.printStackTrace();
} finally {
   try {
       bufferedWriter.close();
   } catch (IOException e) {
       e.printStackTrace();
   }
}
Now let's rewrite this code, but using try-with-resources :
String text = "some text......";
try(BufferedWriter bufferedWriter =new BufferedWriter(new FileWriter("someFileName"))) {
   bufferedWriter.write(text);
} catch (IOException e) {
   e.printStackTrace();
}
It’s somehow become easier, don’t you think? In addition to simplification, there are a couple of points:
  1. In try-with-resources , resources declared in parentheses (which will be closed) must implement the AutoCloseable interface and its only method, close() .

    The close method is executed in an implicit finally block , otherwise how will the program understand exactly how to close a given resource?

    But, most likely, you will rarely write your own implementations of resources and their closing method.

  2. Sequence of block execution:

    1. try block .
    2. Implicit finally .
    3. A catch block that catches exceptions in previous steps.
    4. Explicit finally .

    As a rule, exceptions that appear lower in the list interrupt those that appear higher.

Imagine a situation where when using try-catch-finally an exception occurs in your try . Accordingly, a specific catch block immediately starts executing , in which you write another exception (for example, with a message that describes the error in more detail), and you want the method to throw this exception further. Next comes the execution of the finally block , and an exception is also thrown in it. But this is different. Which of these two exceptions will this method ultimately throw? Exception thrown by the finally block ! But there is also one point with try-with-resources . Now let's look at the behavior of try-with-resources in the same situation. We get an exception in the try block when we try to close resources in the close() method , that is, in the implicit finally . Which of these exceptions will catch ? The one that was thrown by the try block ! An exception from an implicit finally (from the close() method ) will be ignored. This ignoring is also called exception suppression.

13. What are bitwise operations?

Bitwise operations are operations on bit strings that include logical operations and bitwise shifts. Logical operations:
  • bitwise AND - compares bit values, and in the process, any bit set to 0 (false) sets the corresponding bit in the result as 0. That is, if in both values ​​being compared the bit was 1 (true), the result will also be 1.

    Denoted as - AND , &

    Example: 10111101 & 01100111 = 00100101

  • bitwise OR is the inverse operation of the previous one. Any bit set to 1 sets a similar bit in the result as 1. And accordingly, if the bit was 0 in both compared values, the resulting bit will also be 0.

    Denoted as - OR , |

    Example: 10100101 | 01100011 = 11100111

  • bitwise NOT - applied to one value, flips (inverts) the bits. That is, those bits that were 1 will become 0; and those that were 0 will become 1.

    Denoted as - NOT , ~

    Example: ~10100101 = 01011010

  • bitwise exclusive OR - compares bit values, and if in both values ​​the bit is equal to 1, then the result will be 0, and if in both values ​​the bit is 0, the result will be 0. That is, for the result to be equal to 1, only one of the bits must was equal to 1, and the second was equal to 0.

    Denoted as - XOR , ^

    Example: 10100101 ^ 01100011 = 11000110

Bitwise shifts - >> or << shift the bits of a value in the specified direction, by the specified number. Free positions are filled with zeros. For example:
  1. 01100011 >> 4 = 00000110
  2. 01100011 << 3 = 00011000
There is also an exception when right shifting a negative number. As you remember, the first bit is responsible for the sign, and if this bit is equal to 1, then the number is negative. If you move a negative number, the vacated positions will no longer be filled with zeros, but with ones, since it is necessary to maintain the sign bit. For example: 10100010 >> 2 = 11101000 At the same time, in Java there is an additional unsigned right shift operator >>> This operator is an analogue of >>, when shifting, the vacated positions are filled with 0, regardless of whether the number is negative or positive. For example: 10100010 >>> 2 = 00101000 Read more about bitwise operations here . Analysis of interview questions and answers.  Part 2 - 2As examples of the use of bitwise shifts in Java, you can cite the hash() method of a HashMap, which is used to determine a special internal hash code for a key: Analysis of interview questions and answers.  Part 2 - 3This method allows you to evenly distribute data in a HashMap to minimize the number of collisions.

14. What standard immutable classes are objects in Java?

Immutable is an object that does not allow its original parameters to be changed. It may have methods that return new objects of a given type, with parameters that you wanted to change. Some standard immutable objects:
  • By far the most famous immutable object in Java is String;
  • instances of wrapper classes that wrap standard types: Boolean, Character, Byte, Short, Integer, Long, Double, Float;
  • objects that are usually used for especially LARGE numbers - BigInteger and BigDecimal;
  • an object that is a unit in stacktraces (for example, in an exception stacktrace) StackTraceElement;
  • an object of the File class - can change files, but at the same time it itself is immutable;
  • UUID - which is often used as a unique id for elements;
  • all class objects of the java.time package;
  • Locale - used to define a geographic, political, or cultural region.

15. What are the advantages of an immutable object over regular objects?

  1. Such objects are safe when used in a multi-threaded environment . By using them, you don't have to worry about losing data due to thread race conditions. Unlike working with ordinary objects: in this case, you will have to think very carefully and work out the mechanisms for using the object in a parallel environment.
  2. Immutable objects are good keys in a map, because if you use a mutable object and then the object changes its state, it can become confusing when using a HashMap: the object will still be present, and if you use containsKey() it may not be found.
  3. Immutable objects are great for storing immutable (constant) data that should never be changed while the program is running.
  4. “Atomicity to failure” - if an immutable object throws an exception, it will still not remain in an unwanted (broken) state.
  5. These classes are easy to test.
  6. Additional mechanisms such as a copy constructor and clone implementation are not needed.

Questions about OOP

Analysis of interview questions and answers.  Part 2 - 4

16. What are the advantages of OOP in general and compared to procedural programming?

So, the advantages of OOP:
  1. Complex applications are easier to write than procedural programming, since everything is broken down into small modules - objects that interact with each other - and as a result, programming comes down to relationships between objects.
  2. Applications written using OOP are much easier to modify (as long as the design concepts are followed).
  3. Since the data and operations on it form a single entity, they are not smeared throughout the application (which often happens with procedural programming).
  4. Information encapsulation protects the most critical data from the user.
  5. It is possible to reuse the same code with different data, because classes allow you to create many objects, each of which has its own attribute values.
  6. Inheritance and polymorphism also allow you to reuse and extend existing code (instead of duplicating similar functionality).
  7. Easier application extensibility than with a procedural approach.
  8. The OOP approach makes it possible to abstract from implementation details.

17. Tell us what shortcomings there are in OOP

Unfortunately, they are also present:
  1. OOP requires a lot of theoretical knowledge that needs to be mastered before you can write anything.Analysis of interview questions and answers.  Part 2 - 5
  2. The ideas of OOP are not so easy to understand and apply in practice (you need to be a bit of a philosopher at heart).
  3. When using OOP, the performance of the software is slightly reduced due to the more complex organization of the system.
  4. The OOP approach requires more memory, since everything consists of classes, interfaces, methods, which take up much more memory than ordinary variables.
  5. The time required for the initial analysis is greater than for the procedural one.

18. What is static and dynamic polymorphism

Polymorphism allows objects to behave differently for the same class or interface. There are two types of polymorphism, also known as early- and late-binding . Static polymorphism, or earlier binding:
  • occurs at compile time (early in the program's life cycle);
  • decides which method to execute at compile time;
  • Method overloading is an example of static polymorphism;
  • early binding includes private, static, and terminal methods;
  • inheritance is not involved in early binding;
  • Static polymorphism does not involve specific objects, but information about the class, the type of which is represented to the left of the variable name.
Dynamic polymorphism, or late binding:
  • occurs at runtime (while the program is running);
  • dynamic polymorphism decides what specific implementation a method will have at runtime;
  • method overriding is an example of dynamic polymorphism;
  • late binding is the assignment of a specific object, a reference of its type, or its superclass;
  • inheritance is associated with dynamic polymorphism.
You can read more about the differences between early and late binding in this article .

19. Define the principle of abstraction in OOP

Abstraction in OOP is a way to highlight a set of significant characteristics of an object, excluding unimportant details. That is, when designing a program with an OOP approach, you focus on models in general, without delving into the details of their implementation. In Java, interfaces are responsible for abstraction . For example, you have a machine, and this will be the interface. And various interactions with it - for example, starting the engine, using the gearbox - these are functions that we use without going into implementation details. After all, at the moment when you are driving a car, you do not think about how exactly the gearbox fulfills its purpose, or how the key starts the engine, or exactly how the steering wheel turns the wheels. And even if the implementation of one of this functionality is replaced (for example, the engine), you may not notice it. This doesn't matter to you: you don't go into details of the implementation. It is important for you that the action is carried out. Actually, this is abstraction from implementation details. This is where we will stop today: to be continued!Analysis of interview questions and answers.  Part 2 - 6
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION