JavaRush /Java Blog /Random EN /Level 21. Answers to interview questions on the level top...
zor07
Level 31
Санкт-Петербург

Level 21. Answers to interview questions on the level topic

Published in the Random EN group
Level 21. Answers to interview questions on the topic of level - 1
  1. List class methodsObject

    • equals()
    • hashCode()
    • toString()
    • getClass()
    • notify()
    • notifyAll()
    • wait()
    • wait(long timeOut)
    • wait(long timeOut, int nanos)
  2. equalsWhy are & methods needed hashCode?

    Used to compare objects.

    The purpose of the method equalsis to determine whether objects are internally identical by comparing the internal contents of the objects. This equalsworks slowly, first the hash codes of the objects are compared, and if the hash codes are equal, a check is made againstequals

  3. What happens if you override equals but not override hashCode?

    Initially hashCode, a random number.

    equalsCollections in Java always look for/compare them using the method before comparing objects using hashCode(). And if identical objects have different hashCode, then the objects will be considered different - it simply won’t be possible to compare using them equals.

  4. Why are the methods wait, notify, notifyAll?

    Sometimes a program may have a situation where a thread has entered a block of code synchronized, blocked the monitor, and cannot work further, because some data is still missing: for example, the file that it should process has not yet been loaded or something like that. A method was invented to solve this problem wait(). Calling this method causes the thread to release the monitor and "pause".

    To unpause, methods are used notify. notifyAllThe method notify“unfreezes” one random thread, the method notifyAll– all “frozen” threads of a given monitor.

  5. How to clone an object correctly?

    Two types of cloning.

    To clone a default object:

    • Add an interface Cloneableto your class
    • Override the method cloneand call the base implementation in it:
    class Point implements Cloneable
    {
     int x;
     int y;
    
     public Object clone()
     {
      return super.clone();
     }
    }

    Or you can write the implementation of the method cloneyourself:

    class Point
    {
     int x;
     int y;
    
     public Object clone()
     {
      Point point = new Point();
      point.x = this.x;
      point.y = this.y;
      return point;
     }
    }
  6. Why is the method needed finalize()and how does it work?

    If you remember, this finalize()is a special method that is called on an object before the garbage collector destroys it.

    The main purpose of this method is to release used external non-Java resources: close files, I/O streams, etc.

    finalize()works unstable.

    This method does not live up to the expectations placed on it. The Java machine can delay the destruction of an object, as well as the call of a method, finalizefor as long as it likes. Moreover, it does not guarantee that this method will be called at all. In a lot of situations, for the sake of “optimization” it is not called.

  7. What is the difference final, finally, finalize?

    • final- modifier
    • Fields cannot be changed, methods are overridden
    • Classes cannot be inherited
    • This modifier only applies to classes, methods and variables (also local variables)
    • Method arguments marked as are finalread-only; attempting to change them will result in a compilation error.
    • Переменные final не инициализируются по умолчанию, им необходимо явно присвоить meaning при объявлении or в конструкторе, иначе – ошибка компиляции
    • Если final переменная содержит ссылку на an object, an object может быть изменен, но переменная всегда будет ссылаться на тот же самый an object
    • Также это справедливо и для массивов, потому что массивы являются an objectми, – массив может быть изменен, а переменная всегда будет ссылаться на тот же самый массив
    • Если класс объявлен final и abstract (взаимоисключающие понятия), произойдет ошибка компиляции
    • Так How final класс не может наследоваться, его методы никогда не могут быть переопределены

    finally — блок в связке try-catch-finally, code в котором выполнится независимо от того вылетело ли исключение в блоке try or нет. Используется для освобождения ресурсов.

    finalize — метод в классе Object см 6.

  8. What такое try-with-resources?

    Это специальная конструкция try, называемая try-with-resources, в которой Обрати внимание – после try следуют круглые скобки, где объявляются переменные и создаются an objectы. Эти an objectы можно использовать внутри блока try, обозначенного скобками {}. Когда выполнение команд блока try закончится, независимо от того – нормально оно закончилось or было исключение, для an object, созданного внутри круглых скобок (), будет вызван метод close();

  9. Чем отличаются методы wait(1000) и sleep(1000)?

    sleep() приостанавливает поток на указанное. состояние меняется на TIMED_WAITING, по истечению — RUNNABLE

    wait() меняет состояние потока на WAITING

    может быть вызвано только у an object владеющего блокировкой, в противном случае выкинется исключение IllegalMonitorStateException. при срабатывании метода блокировка отпускается, что позволяет продолжить работу другим потокам ожидающим захватить ту же самую блокировку . в случае wait(int) с аргументом состояние будет TIMED_WAITING

  10. В чем отличие i++ и ++i?

    • ++i, i сначала увеличивается на 1, затем участвует в выражении.
    • i++, i сначала участвует в выражении, затем увеличивается на 1.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION