0

I find it difficult to understand the result of following code.

File x = new File("myFile.txt");
File y = new File("myFile.txt");
System.out.println(x==y); //outputs false

I dont understand why this outputs false. Please help

eccentricCoder
  • 846
  • 1
  • 14
  • 35
  • Not sure if your question is about the meaning of object references or the usage of `==` and `equals`. – Luiggi Mendoza Jan 24 '16 at 15:27
  • What do you think should happen and why do you think so? – Pshemo Jan 24 '16 at 15:28
  • I know that two references are equal if they point to same object. but x and y appears to point to same object? – eccentricCoder Jan 24 '16 at 15:29
  • 3
    No they don't. They point to two different File objects. These objects might reference the same physical files, but they are unique objects. – Hovercraft Full Of Eels Jan 24 '16 at 15:30
  • 2
    Each time you call `new ...` you are creating new (separate) instance. Two separate instances can have same state (like two people can have same name) but it doesn't mean they are the same (same != equal). So `==` checks if two references are pointing to *same* object, if you want to check if two objects are equal use `obj1.equals(obj2)`. – Pshemo Jan 24 '16 at 15:31

0 Answers0