0

Why does this code print false? I've tried the code below as well as using the somea.equals(somea2); method and still i get false. how are these two arrays different?

int[] somea = {2};
int[] somea2 = {2};
System.out.println(somea==somea2);

false

what could possibly be going wrong?

Mahmoud Hendi
  • 139
  • 11
Bdyce
  • 332
  • 2
  • 11

4 Answers4

2

You are comparing the 2 address. Maybe you can use the java.util.Arrays.equals(int[] a, int[] a2) method that returns "true" if the two specified arrays of ints are equal to one another. Two arrays are equal if they contain the same elements in the same order.Two array references are considered equal if both are null.

Example :

int[] somea = {2};
int[] somea2 = {2};
System.out.println(Arrays.equals(somea , somea2 ));

You can read more from here: https://www.tutorialspoint.com/java/util/arrays_equals_int.htm

Mahmoud Hendi
  • 139
  • 11
0

This is because soma and soma2 is not primitive type. They are reference type. Reference type variables have references for memory.

Rurou2
  • 167
  • 1
  • 1
  • 7
0

the arrays live in different cities of the memory and you are asking the machine if the cities where they live is are the same. however, both cities have a street named grand avenue. you want to be asking the machine if both cities have a street named grand avenue

Timetrax
  • 1,373
  • 13
  • 15
-1

Cause you are comparing the address of these two arrays,

Richard
  • 1
  • 1