JavaRush /Java Blog /Random EN /Level 29. Answers to interview questions on the level top...
DefNeo
Level 36

Level 29. Answers to interview questions on the level topic

Published in the Random EN group
Level 29. Answers to interview questions on the topic of level - 1
  1. What's happened autoboxing?

    Autoboxing is a mechanism for implicitly initializing objects of wrapper classes (Byte, Short, Character, Integer, Long, Float, Double) with the values ​​of their corresponding original primitive types (respectively, , , , , , , byte, short) char, intwithout longexplicit floatuse doubleof the class constructor.

    Autoboxing occurs when a primitive is directly assigned to a wrapper class (using the " =" operator), or when a primitive is passed into the parameters of a method (such as a "wrapper class"). Both variables of primitive types and compile-time constants (literals and final-primitives) can be autopacked into “wrapper classes”. In this case, literals must be syntactically correct to initialize a variable of the original primitive type.

    Autoboxing of variables of primitive types requires an exact match of the type of the original primitive - the type of the “wrapper class”. For example, attempting to autobox a type variable byteinto Short, without first making an explicit cast, byte->shortwill cause a compilation error.

    Autoboxing of primitive type constants allows for wider matching boundaries. In this case, the compiler is able to perform implicit extension/narrowing of primitive types in advance. The transformation occurs in two stages:

    1. implicit expansion (narrowing) of the original primitive type to the primitive type corresponding to the wrapper class (for conversion int->Byte, first the compiler implicitly narrows intto byte)

    2. autopacking of a primitive into the appropriate “wrapper class” (the compiler autopacks byte->Byte). however, in this case there are two additional restrictions:

      • assignment of a primitive to a “wrapper” can only be done using the “ =” operator (you cannot pass such a primitive to method parameters without explicit type casting)

      • the type of the left operand must not be older than Character, the type of the right operand must not be older than int, (extension/constriction is allowed byte <-> short, byte <-> char, short <-> char
        and only narrowing byte <- int, short <- int, char <- int, all other options require explicit type casting)

    An additional feature of integer "wrapper classes" created by autoboxing constants in the range -128 +127 is that they are cached by the JVM. Therefore, such wrappers with the same values ​​will be references to one object.

  2. Why is it used autoboxing?

    I will quote the lecture:

    As you remember, Java has both types inherited from the class Objectand primitive types. But, as it turned out, such a convenient thing as collections and generics can only work with types inherited from Object.

  3. Alternatives autoboxing?

    Не нашел ответа, но запостил на StackOverFlow.

    Исходя из этой дискуссии, получается, что альтернатива autoboxing`у это использование примитивных типов, так How использовние autoboxing`a снижает производительность. Вывод: использовать autoboxing только там где это необходимо.

    Написана статья про Autoboxing: Autoboxing: Traps and Advantages

  4. Типы-обертки для примитивных типов mutable or immutable?

    Immutable, так How примитивные an objectы тоже immutable. Whatбы работать How с Mutable типом есть класс MutableInteger, и.т.д.

  5. Как примитивные типы приводятся к непримитивным аналогам?

    На этот и последующий вопросы хорошо отвечает вот эта статья: Автоупаковка и распаковка в Java

    Это заключение из нее: автоупаковка является механизмом для скрытого преобразования примитивных типов данных в соответствующие классы-оболочки (an objectы). Компилятор использует метод valueOf() чтобы преобразовать примитивные типы в an objectы, а методы IntValue(), doubleValue() и т.д., чтобы получить примитивные типы из an object (то есть обратное преобразование). Автоупаковка преобразует логический тип boolean в Boolean, byte в Byte, char в Character, float в Float, int в Integer, long в Long, short в Short. Распаковка происходит в обратном направлении.

  6. Как непримитивные типы приводятся к примитивным?

    Выше ответил.

  7. Как сравниваются примитивные и непримитивные типы?

    В лекции это подробно рассматривается, но я нашел так скажем тоже самое, но другими словами.

    В Java есть два способа сравнивать an objectы на equalsство, == и метод equals().

    == используется для примитивных типов. Для an objectов «==» это исключительно сравнение ссылок. Для остальных случаев нужно использовать метод equals(). Кроме того метод hashCode() служит (в теории) для той же цели. Хорошим тоном считается, если вы переопределor equals() и hashCode(). После инициализации неких an objectов a и b должно выполняться правило:

    Если выражение a.equals(b) вернет true, то a.hashCode() должен быть equals b.hashCode().

  8. Всегда ли создается новый an object при операции autoboxing?

    Это в лекциях есть:

    Когда мы присваиваем переменной типа Integer meaning типа int, при этом вызывается метод Integer.valueOf: функция valueOf не всегда создает новый an object типа Integer. Она кэширует значения от -128 до 127.

    Если передаваемое meaning выходит за эти пределы, то новый an object создается, а если нет, то нет.

    Если мы пишем new Integer(), то гарантированно создается новый an object. Если мы вызываем Integer.valueOf(), явно or при autoboxing, то этот метод может вернуть для нас How новый an object, так и отдать an object из кэша, если переданное число лежит в диапазоне от -128 до 127.

  9. Как работает кэширование при операции autoboxing?

    Ответил в вопросе выше, на всякий случай создал вопрос на StackOverFlow, но там отвечают тоже самое

  10. Для Howих типов и/or значений работает кэширование?

    В восьмом вопросе. Если у кого – то есть соображения на тему трех последних вопросов, то напишите в комментариях.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION