123k views
3 votes
What is the output of the following code snippet? public static void main(String[] args) { String[] arr = { "aaa", "bbb", "ccc" }; mystery(arr); System.out.println(arr[0] + " " + arr.length); } public static void mystery(String[] arr) { arr = new String[5]; arr[0] = "ddd"; }

User Nick Wyman
by
6.1k points

1 Answer

6 votes

Answer:

The output is:

aaa 3

Step-by-step explanation:

Lets examine the code snippet

  1. public static void main(String[] args) {
  2. String[] arr = { "aaa", "bbb", "ccc" };
  3. mystery(arr);
  4. System.out.println(arr[0] + " " + arr.length);
  5. }
  6. public static void mystery(String[] arr) {
  7. arr = new String[5];
  8. arr[0] = "ddd";
  9. }
  10. }

Line 2 Creates an array with three string values

line 3 calls method mystery() The method definition on lines 6-9 indicates that it does not output any value, neither does it return any value

Line 4 determines the output of this code. In the output statement The first element of the array (indexed 0) is printed concatenated with the length of the array which is 3. Hence the output aaa 3

User Samvel Aleqsanyan
by
6.5k points