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 11

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

97. Are agreement redefinition conditions imposed when redefining Equals?

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

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

  • transitivity - for any values ​​of x , y and z , if x.equals(y) returns true and 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.

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

98. What happens if you don't override Equals and HashCode?

In this case, hashCode() will return a number generated based on the memory location in which the given object is stored. That is, two objects with exactly the same fields will receive different values ​​when calling a non-overridden hashCode() (after all, they are stored in different memory locations). The unoverridden equals() compares references to see whether they point to the same object or not. That is, the comparison is made through == , and in the case of objects with the same fields it will always return false . True will 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 spoil the logic of uniqueness. The main thing is to understand the nuances of overridden and non-overridden methods and use both approaches depending on the situation.

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

A bit of a 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 simple logic. Analysis of questions and answers from interviews for Java developer.  Part 11 - 2

100. What is 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 fact is that hashcode is mapped to the Integer type , which in turn has a range from -2147483648 to 2147483647, that is, approximately 4 billion different integers. This range is huge, however, it is not infinite. Therefore, situations are possible when two completely different objects have the same hash code. This is highly unlikely, but possible. A poorly implemented hash function can also increase the frequency of identical hash codes, which will, for example, return numbers in a small range, which will increase the chance of collisions. To combat a collision, you need to have a good implementation of the hashCode method so that the spread of values ​​is maximum and the chance of repeating values ​​is minimal.

101. What happens if an element participating in a HashCode contract changes its value?

If an element that is involved in calculating the hash code has been changed, then the hash code of the object itself will be changed (if the hash function is good). Therefore, in HashMap it is recommended to use immutable (unchangeable) 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 you use a mutable object as a key, then when you change the fields of this object, its hash code will change and, as a result, you can lose this pair in the HashMap . After all, it will be stored in the bucket for the original hash code, and after changing it, it will be searched in another bucket. Analysis of questions and answers from interviews for Java developer.  Part 11 - 3

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

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 links directly, because if the links are to the same object, what is the point of continuing the check? Everything will be true anyway .

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

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

  • Comparison of a primitive class field (after all, comparison via =! is enough for it ), 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 greater spread) and adding to it the hash code of a non-primitive string field (if it is not null).

  • Returning the result.

  • As a result of this hash code override, 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 look at what each approach does:
  • instanceof checks whether an object reference on the left side is an instance of a type on the right side or some subtype of it.

  • getClass() == ... checks for type identity.

That is, if getClass() checks 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 them in the right places.

104. Give a brief description of 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 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();
}
After all, 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 working with the fields of an object of reference type?

When cloning objects, only primitive values ​​and the value of object references are copied. This means that if an object has a link to another object in its internal field, then only this link will be cloned, but this other object itself will not be cloned. In fact, this is what they call 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 a marker interface - Cloneable . Then it will not be the references to objects that will be copied, 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 insufficient 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 as they are of an unchecked type. Analysis of questions and answers from interviews for Java developer.  Part 11 - 5Exceptions are problems that can occur at runtime and at compile time. Typically 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 depend on problems with the system itself in which our application runs.

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

As I said earlier, an exception is an error during program execution 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 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 into the methods above. Unchecked is a type of exception that does not need to be handled and is typically less predictable and less likely to occur. However, they can also be processed if desired. Throw is used when throwing an exception manually, for example:
throw new Exception();

108. What is the hierarchy of exceptions?

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

109. What is checked and unchecked exception?

As I said before:
  • Checked - exceptions that you must somehow handle, that is, either process them in a try - catch block , or “forward” them to 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 users of the method that the method can throw this exception (something like a warning) and transfers the responsibility to handle the exception to users of this method.

  • Unchecked - exceptions that do not need to be handled, since they are not checked at compile time and, as a rule, are 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 mandatory.

101. Write an example of intercepting 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, which 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’ll 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 the following output to the console:
Oops, something went wrong =(
Analysis of questions and answers from interviews for Java developer.  Part 11 - 7You can find out more about the exceptions here . Well, that's all for today! See you in the next part!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION