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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.