-1

Possible Duplicate:
If statement using == gives unexpected result

I am working on a java code that is suppose to do something if the time is equal you set in the code and the real time in the system.And if the time doesn't match it completely ignores it. Now I can got the time correctly but for some reason the if statement is saying its not equal even when it is. Is there something I am missing or doing wrong?

Calendar now = new GregorianCalendar();
String am_pm;     
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
if (now.get(Calendar.AM_PM) == 0){
    am_pm = "AM";  
}
else{
    am_pm = "PM";
}
String time = hour + ":" + minute + " " + am_pm;        
String Scan_hour = "2:45 PM";       
System.out.println(time + "--" + Scan_hour);    
if (time == Scan_hour){
    System.out.println("Time matchs");
}
else{
    System.out.println("Time Doesn't Match");
}
Community
  • 1
  • 1
M1M N7
  • 69
  • 2
  • 7

1 Answers1

1
if (time == Scan_hour){

should be

if (time.equals(Scan_hour)){

String comparison should use equals() instead of == (except the case of String literals).

== checks for reference equality (both references points to same object or not). equals() checks for content equality.

kosa
  • 65,990
  • 13
  • 130
  • 167
  • Thank you. that got it working fine. Can't believe I miss something so small yet important. Thank you very much. – M1M N7 Nov 15 '12 at 20:08