+ 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); } }

2nd Jul 2017, 10:49 AM
priya
8 ответов
+ 5
well said @sandesh
2nd Jul 2017, 11:04 AM
Pravin Pandey
Pravin Pandey - avatar
+ 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);
2nd Jul 2017, 2:56 PM
Thirumurugan C
Thirumurugan C - avatar
+ 2
because a1 and a2 are different objects and their memory address will be different
2nd Jul 2017, 10:59 AM
Sandesh
Sandesh - avatar
+ 1
ok dude
2nd Jul 2017, 3:01 PM
Thirumurugan C
Thirumurugan C - avatar
+ 1
Because a1 n a2 are two different objects.
2nd Jul 2017, 4:34 PM
Jatin Agarwal
Jatin Agarwal - avatar
+ 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.
28th Jul 2017, 10:20 AM
Shubhi Jain
0
Will it not compare the values stored in the variables ?
2nd Jul 2017, 2:09 PM
priya
0
dude my answer was for the question asked and I was not generalising anything.
2nd Jul 2017, 2:59 PM
Sandesh
Sandesh - avatar