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

Level 30. Answers to interview questions on the level topic

Published in the Random EN group
Level 30. Answers to interview questions on the topic of level - 1
  1. What is NaN?

    NaN (English Not-a-Number) is one of the special states of a floating point number. Used in many mathematical libraries and mathematical coprocessors. This condition can occur in various cases, for example, when a previous mathematical operation completed with an uncertain result, or if a number that does not satisfy the conditions was entered into a memory cell.

    In accordance with IEEE 754, this state is specified by setting the exponent to the reserved value 11...11, and the mantissa to anything other than 0 (the reserved value for machine infinity). The sign and mantissa may carry some additional information: many libraries output “negative” NaN as -NaN.

    Operations that result in NaN as a response include:

    • all mathematical operations containing NaN as one of the operands;
    • dividing zero by zero;
    • dividing infinity by infinity;
    • multiplying zero by infinity;
    • addition of infinity with infinity of the opposite sign;
    • calculating the square root of a negative number[1];
    • taking the logarithm of a negative number.

    Some programming languages ​​have “silent” and “signal” NaN: the first, when involved in any operation, returns NaN, the second causes an emergency. Typically, "quiet" or "signal" is determined by the most significant bit of the mantissa.

    NaN is not equal to any other value (not even itself[2]); Accordingly, the simplest method of checking a result for NaN is to compare the resulting value with itself.

    The behavior of other comparison operators varies by language. Some languages ​​produce false[3] (so that a < b and b > a behave differently with NaN), others throw a crash even for “quiet” NaN.

    Any non-trivial operation that takes a silent NaN as an argument will always return NaN, regardless of the value of the other arguments. The only exceptions to this rule are the max and min functions, which return the value of the "second" argument (other than NaN). Trivial operations that are identities are treated specially: for example, 1NaN equals 1.

  2. How to get infinity in Java?

    In Java, type doublehas special meanings for plus infinity and minus infinity. A positive number divided by 0.0 gives "plus infinity", and a negative number - "minus infinity". These concepts correspond to special constants of type Double:

    Code Description
    public static final double POSITIVE_INFINITY = 1.0 / 0.0; plus infinity
    public static final double NEGATIVE_INFINITY = -1.0 / 0.0; minus infinity
    1. We convert the string into a number, and it contains letters. The answer is NaN
    2. Infinity minus infinity. The answer is NaN
    3. There are many other situations where they expect a number in the answer, but the result is unknown.

    Any operation that contains NaN results in NaN.

    Actions with infinity:
    Expression Result
    n ÷ ±Infinity 0
    ±Infinity × ±Infinity ±Infinity
    ±(not zero) ÷ ±Infinity
    Infinity + Infinity Infinity
    ±0 ÷ ±0 NaN
    Infinity - Infinity NaN
    ±Infinity ÷ ±Infinity NaN
    ±Infinity × 0 NaN
  3. How to check that the result of the calculation is infinity?

    There is an answer on StackOverFlow .

    It all comes down to the conclusionSystem.out.println()

  4. What is a bitmask?

    A bit mask is when many different Boolean values ​​(true/false) are stored as a single integer. In this case, each boolean value corresponds to a specific bit.

  5. Where are bit masks used?

    Mainly where you need to compactly store a lot of information about objects. When you store a lot of information about an object, there will always be a couple of dozen logical variables. It’s convenient to store them all in one number. Just store it. Because It's not that convenient to use at work.

  6. How to set a bit to one in a bitmask?

    Based on the lectures, you can answer with the following code:

    Here I used the method Integer.toBinaryString()to test myself, what if)

    public class BitMask {
    
        public static void main(String[] args) {
            int a = 9;
    
           a |= (1<<2); // установить в 1 бит 2
    
    
            System.out.println(Integer.toBinaryString(a) + " "+ a);
        }
    }

    The conclusion is:

    1101 13

  7. How to set a bit to zero in a bitmask?

    public class BitMask {
    
    public static void main(String[] args) {
    int a = 15;
    
    a &= ~(1<<2); // установить в 0 бит 2
    System.out.println(Integer.toBinaryString(a) + " "+ a);
    
        }
    }

    Conclusion:

    1011 11

    I took the number 15, since it more clearly shows where 0 is set.

  8. How to get the value of a specific bit in a bitmask?

    public class BitMask {
    
    public static void main(String[] args) {
         int a = 15;
    
         a &= ~(1<<2); // установить в 0 бит 2
    
         int c = a & (1<<2); // узнаем про 2 бит
         int d = a & (1<<3); // узнаем про 3 бит
        System.out.println(Integer.toBinaryString(a) + " "+ a + " " + c +" "+ d);
    
        }
    }

    Conclusion:

    1011 11 0 8

    C 0 everything is clear, in that place there really is 0. And the variable d returns the value of the requested bit (in the 10th system).

  9. What is lazy expression evaluation?

    Article: Lazy programming and lazy evaluation

    Это ленивые вычисления (lazy evaluation). В ленивых вычислениях ни один параметр не вычисляется, пока в нем нет необходимости. Программы фактически начинаются с конца и работают от конца к началу. Программа вычисляет, что должно быть возвращено, и продолжает движение назад, чтобы определить, Howое meaning для этого требуется. В сущности каждая функция вызывается с promise'ами для каждого параметра. Когда для вычисления необходимо meaning, тогда выполняется promise. Поскольку code выполняется только тогда, когда необходимо meaning, это называется вызов по необходимости (call-by-need). В традиционных языках программирования instead of promise'ов передаются значения, это называется вызов по значению(call-by-value).

    Технология программирования "вызов по необходимости" имеет ряд преимуществ. Потоки имплементируются автоматически. Ненужные значения никогда не вычисляются. Однако, поведение ленивых программ часто трудно предсказать. В программах типа "вызов по значению" порядок вычисления довольно предсказуем, поэтому любые time- or sequence-based вычисления относительно легко имплемнтировать. В ленивых языках, где специальные конструкции, например, monads, необходимы для описания явно упорядоченных событий, это намного труднее. Все это также делает связь с другими языками более трудной.

    Существуют языки программирования, например, Haskell и Clean, использующие ленивое программирование по умолчанию. Кроме того, для некоторых языков, таких How Scheme, ML и другие, существуют ленивые версии.

    Иногда, откладывая вычисления до тех пор, пока не понадобится их meaning, вы можете оптимизировать speed выполнения программы or реструктурировать программу в более понятную форму. Несмотря на свою ценность, методы ленивого программирования не слишком широко используются or даже не очень известны. Подумайте о том, чтобы добавить их в ваш арсенал.

  10. Чем отличается использование && и & для типа boolean?

    && — это логическое «и». (В этом случае имеют место ленивые вычисления: некоторые вычисления опускаются, когда результат и так ясен)

    & — это побитовое «и» (Если применить этот оператор к переменным типа Boolean, то ленивых вычислений происходить не будет)

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