-1

Why the comparision of Local Date object print true at line no. 8 while false at line no. 9 and line no.10?

import java.time.LocalTime;
public class Main{
    public static void main(String arg[]){
        LocalTime t1,t2,t3;
        t1=LocalTime.parse("10:10");
        t2=LocalTime.of(10,10);
        t3=LocalTime.parse("10:10");
        System.out.println(t1==t1); 
        System.out.println(t1==t3);
        System.out.println(t2==t3); 
    }
}
Shahbaz
  • 1
  • 1
  • 1
    Because `==` compares references. `t1` has the same reference as `t1`, so the first line prints `true` while the others print `false`. – BackSlash Feb 08 '17 at 09:25

2 Answers2

1

I suggest you to read on difference between equals and ==

public class Main {
    public static void main(String arg[]) {
        LocalTime t1, t2, t3;
        t1 = LocalTime.parse("10:10");
        t2 = LocalTime.of(10, 10);
        t3 = LocalTime.parse("10:10");
        System.out.println(t1 == t1);//true because it matches same memory location  
        System.out.println(t1 == t3);
        System.out.println(t2 == t3);

        //you have to use equals method to compare t1,t2,t3 objects
        System.out.println(t1.equals(t1));//true
        System.out.println(t1.equals(t3));//true
        System.out.println(t2.equals(t3));//true

    }
}

This shows the difference

KishanCS
  • 1,357
  • 1
  • 19
  • 38
  • http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/ – KishanCS Feb 08 '17 at 09:28
0

Using the == operator you check if the objects itself are the same.

You have to use equals to compare objects by content.

René Scheibe
  • 1,970
  • 2
  • 14
  • 20