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

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

Published in the Random EN group
Hello! Even the fastest ship without a course will simply drift through the waves. If you are reading my article now, you definitely have a goal. The main thing is not to go astray, but to bend your line to the end - to become a Java developer. Today I want to continue my 250+ questions for Java developers that will help you cover some gaps in theory. Analysis of questions and answers from interviews for a Java developer.  Part 11 - 1

97. Are conditions for redefining the convention put forward when redefining Equals?

The overridden equals() method must comply with the following conditions (rules):
  • reflexivity - for any value of x, an expression like x.equals(x) should always return true (when x != null ).

  • symmetry - for any values ​​of x and y, an expression like x.equals(y) must return true only if y.equals(x) returns true .

  • transitivity - for any values ​​of x , y and z , if the expression x.equals(y) returns true , while y.equals(z) also returns true , then x.equals(z) must return true .

  • consistency - for any values ​​of x and y, a repeated call to x.equals(y) will always return the value of the previous call to this method, provided that the fields used to compare the two objects have not changed between calls.

  • null comparison - for any value of x, calling x.equals(null) will return false .

98. What happens if Equals and HashCode are not redefined?

In this case, hashCode() will return a number generated based on the memory location where the given object is stored. That is, two objects with exactly the same fields when calling an unredefined hashCode () will receive different values ​​​​(after all, they are stored in different memory cells). The unoverridden equals() compares references whether they point to the same object or not. That is, the comparison goes through == , and in the case of objects with the same fields, it will always return false . Truewill only be when comparing references to the same object. Sometimes there is logic in not overriding these methods. For example, you want all objects of a certain class to be unique, and overriding these methods will only mess up the uniqueness logic. The key is to understand the nuances of overridden and non-overridden method data and use both approaches as appropriate.

99. Why is symmetry only performed if x.equals(y) returns true?

A little strange question. If object A is equal to object B, then object B is equal to object A. If B is not equal to object A, then how is the opposite possible? This is normal logic. Analysis of questions and answers from interviews for a Java developer.  Part 11 - 2

100. What is a collision in HashCode? How to deal with it?

A hashCode collision is a situation in which two different objects have the same hashCode value . How is this possible? The point is that hashcode is mapped to type Integer , which, in turn, has a range from -2147483648 to 2147483647, that is, approximately 4 billion different integers. This range is huge, however, not infinite. Therefore, situations are possible when two completely different objects have the same hash code. This is highly unlikely, but possible. Another poorly implemented hash function can increase the frequency of identical hash codes, which, for example, will return numbers in a small range, which will increase the chance of collisions. To deal with collision, you need to have a good implementation of the methodhashCode so that the spread of values ​​is maximized and the chance of repeating values ​​is minimized.

101. What happens if the element participating in the contract with the HashCode changes its value?

If the element that participates in the hash code calculation has been changed, then the hash code of the object itself will be changed (with a good hash function). Therefore, in HashMap, it is recommended to use immutable (immutable) objects as a key, because their internal state (fields) cannot be changed after creation. Accordingly, their hash code is also not converted after creation. If, however, a mutable object is used as a key, then when the fields of this object change, its hash code will change and, as a result, this pair can be lost in the HashMap . After all, it will be stored in the bucket for the original hash code, and after the change, it will be searched in another bucket. Analysis of questions and answers from interviews for a Java developer.  Part 11 - 3

102. Write the Equals and HashCode methods for the Student class, which consists of the fields String name and int age

public class Student {
int age;
String name;

 @Override
 public boolean equals(final Object o) {
   if (this == o) {
     return true;
   }
   if (o == null || this.getClass() != o.getClass()) {
     return false;
   }

   final Student student = (Student) o;

   if (this.age != student.age) {
     return false;
   }
   return this.name != null ? this.name.equals(student.name) : student.name == null;
 }

 @Override
 public int hashCode() {
   int result = this.age;
   result = 31 * result + (this.name != null ? this.name.hashCode() : 0);
   return result;
 }
}
Equals:
  • First, we compare the references directly, because if the references to the same object, what's the point of continuing to check? Everything will be true anyway .

  • Checking for null and for matching class types, because if the object is an argument of null or another type, then this means that the objects are not equal - false .

  • Casting the argument object to one type (suddenly it was an object of the parent type).

  • Comparison of a primitive field of a class (after all, it suffices to compare using =! ), if the field is not equal - false .

  • Checking a non-primitive field for null and equals (in String the method is overridden and will compare correctly), if both fields are null or equals , then the check ends and the method returns true .

hashcode:
  • Setting the initial hash code value to the object's age primitive .

  • Multiplying the current hash code by 31 (for more scatter) and adding the hash code of a non-primitive string field to it (if it's not null).

  • Returning a result.

  • As a result of this redefinition of the hash code, objects with the same name and int values ​​will always return the same value.

103. What is the difference between using if (obj instanceof Student) and if (getClass() == obj.getClass())?

Let's see what each approach does:
  • instanceof checks whether the object reference on the left side is an instance of the type on the right side or some subtype of it.

  • getClass() == ... checks if the types are identical.

That is, if getClass() tests for the complete identity of a class, then instanceof will return true even if the object is just a subtype, which can give us more flexibility when actively using polymorphism. Actually, both approaches are good if you understand the features of their work and apply in the right places.

104. Briefly describe the clone() method.

Clone() is a method of the Object class , the purpose of which is to create and return a clone of the current object (a copy of the current object). Analysis of questions and answers from interviews for a Java developer.  Part 11 - 4To use it, you need to implement the Cloneable marker interface :
Student implements Cloneable
And override the clone() method itself :
@Override
protected Object clone() throws CloneNotSupportedException {
 return super.clone();
}
Indeed, in the Object class it is protected, that is, it will be visible only in the Student class itself , but not visible to classes from the outside.

105. What is the peculiarity of the clone () method with the fields of an object of the link type?

When cloning objects, only primitive values ​​and the value of object references are copied. This means that if an object has a reference to another object in its internal field, then only this reference will be cloned, while this other object itself will not be cloned. Actually, this is called - surface cloning. Well, what if you need full-fledged cloning with cloning of all nested objects? How to make sure that these are not copies of links, but full-fledged clones of objects with other occupied memory cells in the heap? In fact, everything is quite simple - for this you need to also override the clone () method in each class of these internal objects and add an interface marker - Cloneable. Then there will be copied not references to objects, but the objects themselves, because now they also have the ability to copy themselves.

Exceptions

106. What is the difference between error and exception?

Both exceptions and errors are subclasses of the Throwable class . However, they have their differences. The error indicates a problem that mainly occurs due to a lack of system resources. And our application should not detect these types of problems. Some of the examples of errors are system crash and out of memory error. Errors mostly occur at runtime because they are of an unchecked type. Analysis of questions and answers from interviews for a Java developer.  Part 11 - 5Exceptions are problems that can occur at run time and at compile time. As a rule, this happens in code written by developers. That is, exceptions are more predictable and more dependent on us as developers. At the same time, errors are more random and more independent of us, but rather dependent on the failure of the system itself on which our application is running.

107. What is the difference between checked and unchecked, exception, throw, throws.

As I said earlier, an exception is an error during the execution of the program and during compilation that occurred in the code written by the developer (due to some abnormal situation). Checked is a type of exception that must always be handled by using the try-catch mechanism or thrown into the methods above. Throws is used in the method header to indicate possible exceptions thrown by the method. That is, this is the mechanism for “throwing” exceptions to the methods above. Unchecked is a kind of exception that doesn't need to be handled and is generally less predictable and less likely to occur. However, they can also be processed if desired. Throwused when manually throwing an exception, for example:
throw new Exception();

108. What is the hierarchy of exceptions?

The hierarchy of exceptions is very large and extensive, even too much to tell everything about it here. Therefore, we will consider only its key links: Analysis of questions and answers from interviews for a Java developer.  Part 11 - 6Here at the very top of the hierarchy we see a class - Throwable - a general class, an ancestor of the exception hierarchy, which in turn is divided into:
  • Error - critical, unchecked errors.
  • Exception - checked exceptions.
Exception is divided into various unchecked runtime exceptions and various checked exceptions.

109. What are checked and unchecked exceptions?

As I said before:
  • Checked - exceptions that you must handle somehow, that is, either process them in a try - catch block , or “throw them” into the method above. To do this, in the method signature, after listing the method arguments, you need to use the trows <exception type> keyword , which indicates to the users of the method that the method can throw this exception (something like a warning) and transfer the responsibility to handle the exception already for the users of this method.

  • Unchecked - Exceptions that do not need to be handled as they are not checked at compile time and tend to be more unpredictable. That is, the main difference with checked is that for them these try - catch or throwing mechanisms work the same, but they are not required.

101. Write an example of catching and handling an exception in a try-catch block of a method

try{                                                 // начало блока перехвата
 throw new Exception();                             // ручной бросок исключения
} catch (Exception e) {                              // данное исключение и его потомки будут перехватываться
 System.out.println("Упс, что-то пошло не так =("); // вывод некоторого исключения в консоль
}

102. Write an example of catching and handling an exception using your own exceptions

First, let's write our own exception class that inherits from Exception and override its constructor with an error message:
public class CustomException extends Exception {

 public CustomException(final String message) {
   super(message);
 }
}
Well, then we will throw it manually and intercept it as in the previous question:
try{
 throw new CustomException("Упс, что-то пошло не так =(");
} catch (CustomException e) {
 System.out.println(e.getMessage());
}
And again, when you run it, you will get output to the console:
Oops, something went wrong =(
Analysis of questions and answers from interviews for a Java developer.  Part 11 - 7More information about exceptions can be found here . Well, that's all for today! See you in the next part! Analysis of questions and answers from interviews for a Java developer.  Part 11 - 8
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION