4.10. Answers to sample exam questions

Q4-1.

What is the output of the following code?

class EJavaGuruArray {
    public static void main(String args[]) {
        int[] arr = new int[5];
        byte b = 4; char c = 'c'; long longVar = 10;
        arr[0] = b;
        arr[1] = c;
        arr[3] = longVar;
        System.out.println(arr[0] + arr[1] + arr[2] + arr[3]);
    }
}
  1. 4c010
  2. 4c10
  3. 113
  4. 103
  5. Compilation error

Answer: e

Explanation: The code in this question won’t compile due to

arr[3] = longVar;

The preceding line of code tries to assign a value of type long to a variable of type int. Because Java doesn’t support implicit narrowing conversions (for example, long to int in this case), the assignment fails. Also, this code tries to trick you regarding your understanding of the following:

Get OCA Java SE 8 Programmer I Certification Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.