+ 3
why is the result of the program is false
class Animal { String name; Animal(String n) { name = n; } } class MyClass { public static void main(String[ ] args) { Animal a1 = new Animal("Robby"); Animal a2 = new Animal("Robby"); System.out.println(a1 == a2); } }
8 ответов
+ 5
well said @sandesh
+ 4
a1 and a2 are different objects so it have different memory locations so the answer is false
If a1 and a2 are datatypes or string, the answer will be true
Example:
String a1,a2;
a1="Ruby";
a2="Ruby";
System.out.println(a1==a2);
+ 2
because a1 and a2 are different objects and their memory address will be different
+ 1
ok dude
+ 1
Because a1 n a2 are two different objects.
+ 1
See,there are two methods in java that are following:
1.==
2.equals()
In the above mentioned program you used '==' method that is used for reference comparison or address comparison while .equals() method is used for content comparison.
If you use equals() then your answer would be correct because the content of object a1 and a2 is same neither their adddress. Both the objects are referencing to different values.
0
Will it not compare the values stored in the variables ?
0
dude my answer was for the question asked and I was not generalising anything.