Knowee
Questions
Features
Study Tools

What is the output of the following Java code?public class ArrayComparison { public static void main(String[] args) { int[] arr1 = {1, 2, 3}; int[] arr2 = {1, 2, 3}; int[] arr3 = arr1; System.out.println(arr1 == arr2); System.out.println(arr2 == arr3); }}a)Compilation errorb)falsefalse c)NullPointerExceptiond)truetrue

Question

What is the output of the following Java code?public class ArrayComparison { public static void main(String[] args) { int[] arr1 = {1, 2, 3}; int[] arr2 = {1, 2, 3}; int[] arr3 = arr1; System.out.println(arr1 == arr2); System.out.println(arr2 == arr3); }}a)Compilation errorb)falsefalse c)NullPointerExceptiond)truetrue

🧐 Not the exact question you are looking for?Go ask a question

Solution

The output of the given Java code will be:

false true

Explanation:

In Java, when we compare two arrays using the '==' operator, it doesn't compare the contents of the arrays, instead, it checks whether both arrays are pointing to the same memory location or not.

In the given code, arr1 and arr2 are two different arrays having the same elements. But they are located in different memory locations. So, arr1 == arr2 will return false.

On the other hand, arr3 is not a new array, it's just a reference to arr1. So, both arr3 and arr1 are pointing to the same memory location. Hence, arr2 == arr3 will return true.

So, the correct answer is d) true true.

This problem has been solved

Similar Questions

What is the output of the following Java code?public class array{public static void main(String args[]){int []arr = {1,2,3,4,5};System.out.println(arr[5]);}}a.5b.4c.ArrayIndexOutOfBoundsExceptiond.InavlidInputException

Select the correct answerWhat will be the output of the following Java code?class multidimention_array {  public static void main(String args[])  {    int arr[][] = new int[3][];    arr[0] = new int[1];    arr[1] = new int[2];    arr[2] = new int[3];         int sum = 0; for (int ct1 = 0; ct1 < 3; ++ct1)    for (int ct2 = 0; ct2 < ct1 + 1; ++ct2)        arr[ct1][ct2] = ct2 + 1; for (int ct1 = 0; ct1 < 3; ++ct1)    for (int ct2 = 0; ct2 < ct1 + 1; ++ct2)        sum += arr[ct1][ct2]; System.out.print(sum);   } }Options13101114

What is the output of the below Java code snippet? int[] balls = {}; System.out.print(balls.length);

e correct answerWhat is the output of the following Java program?class Main { public static void main(String args[]) { final int i; i = 20; i = 30; System.out.println(i); }}

What does the following piece of code do?for (int i = 0; i < arr.length-1; i++){ for (int j = i+1; j < arr.length; j++) { if( (arr[i].equals(arr[j])) && (i != j) ) { System.out.println(arr[i]); } }}

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.