The interview questions

Without further ado, let’s get straight to the point:

Q: what is the result of test1 when a=1 and b=2? Think about it for a minute.

The answer:

parsing

When using the ternary operator, ensure that the two return values have the same type; otherwise, type conversion will be triggered. The conversion rules are as follows:

  1. If the return value X and Y are of the same type, then the return type is unambiguously of this type.

  2. If two return values X and Y are of different types, the return value type is their nearest parent. For example:

    // Both String and Boolean implement Serializable interface
    Serializable serializable = a == b ? "true" : Boolean.FALSE;
    // All classes inherit from Object
    Object o = a == b ? new ArrayList<>() : new TernaryOperatorDemo();
    Copy the code
  3. For basic data types, if one of the return values X is of type byte, short, or char, and the other Y is of type int, then the return type is X if it can be determined at compile time that Y is in the range of X, and Y if it is not. If the return value X is of any of the above types, a hidden type conversion is triggered.

  4. When a primitive data type and an object data type meet, the ternary operator returns the primitive data type by default.

With these rules in mind, let’s look at the Test1 method.

private static void test1(int a, int b) {
  Int 9 is converted to 9.0d
  System.out.println(a == b ? 9.9 : 9);
  // change 98 from char to b
  System.out.println(a == b ? 'a' : 98);
  Char (int); char (int)
  System.out.println(a == b ? 'a' : Integer.MAX_VALUE);
  // When compiling, the value of b cannot be determined
  System.out.println(a == b ? 'a': b); System.out.println(a ! = b ?'a' : b);

  Map<String, Long> map = new HashMap<>();
  map.put("b".1L);
  // When the basic data type meets the object data type, it defaults to the basic data class.
  // map.get("a") returns null, indicating null pointer exception when converted to basic data type
  System.out.println(map == null ? -1L : map.get("a"));

}
Copy the code

homework

Provide at least one solution to how to modify the test1 method so that the code runs without nulling pointer exceptions.


This article was first published in personal wechat public number: Coder Xiaohei, welcome everyone to scan the code to pay attention to oh.