Nine Core Java Questions
My previous post with Eight Core Java Questions was popular so I created nine more.
Please join the discussion of the answers for these questions on Twitter
1.
Comment on this question
How many elements does this set have?
Set set = new HashSet(Arrays.asList( -0, +0, -0L, +0L, -0F, 0F, -0D, 0D, 0xF, 0xD, 0x0.DP+0)); System.out.println(set.size());
- 12
- 1
- 6
- 9
2.
Comment on this question
This compiles in Java 17 due to
static int[] a(int[]... a)[] { return a; } static final int one = a(new int[0]).length; // 1
- It confuses the compiler
- It’s a static method
- Backward Compatibility
- JEP 747
3.
Comment on this question
The code below prints "23 & 52" the following due to
System.out.println( new BigDecimal(2.008f).toString().length() + " & " + new BigDecimal(2.008).toString().length());
- A bug in Java 23
- The randomness of floating-point
- Length of the mantissa
- Magic numbers
4.
Comment on this question
This code prints "hello world" due to
public static void main(String[] args) { System.out.println(r(604568751) + " " + r(401174283)); } public static String r(int num) { return Integer.toUnsignedString(new Random(num).nextInt(), 33); }
- Secret code in Java
- Using Magic numbers
- A bug in Java 13
- (char) 33 is '!'
5.
Comment on this question
This is class is
public class StackTrace extends Throwable { }
- An unchecked exception
- A checked exception
- Neither
- A compilation error
6.
Comment on this questionThis code prints the following in Java 17
public static void main(String[] args) { test(new IdentityHashMap<>()); test(new WeakHashMap<>()); test(new ConcurrentSkipListMap<>()); } static void test(Map<String, Integer> map) { map.computeIfAbsent("key", (String k) -> { map.putIfAbsent(k, 2); return 1; }); System.out.println(map.getClass().getSimpleName() + " " + map); } IdentityHashMap {key=1} WeakHashMap {key=1} ConcurrentSkipListMap {key=2}
- It depends on whether the map is concurrent or not
- It’s a memory leak
- It's a thread safety issue
- The behaviour is undefined.
7.
Comment on this question
In Java 17, the stack trace StackTraceElement[] of a Throwable is created when
- It is thrown
- It is used for the first time
- Never really exists
- The Throwable is created
8.
Comment on this question
If -Dfalse=true is set on the command line, which of these is true
- (Boolean) false
- Boolean.parseBoolean("false")
- Boolean.getBoolean("false")
- "true" == "false"
9.
Comment on this question
This expression is true for powers of 2 and one other value.
n & ( n - 1 ) == 0
- Integer.MAX_VALUE
- Character.MIN_VALUE
- Double.MIN_VALUE
- Float.NaN
Hint
In the questions above, there are a total of three answers for each for B, C,and D
Comments
Post a Comment