-3

Possible Duplicate:
How do I compare strings in Java?
java == vs equals() confusion

So, I am trying to develop an application that opens a JDialog at a time I enter. It only needs t be accurate to a second.

public void run() {

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    timeset = "16:37";

    while(true){

    System.out.println("thread sleep");
    try{Thread.currentThread().sleep(1000);}catch(InterruptedException ie){}

    Calendar cal = Calendar.getInstance();
    cal.getTime();
    temptime = sdf.format(cal.getTime());       
    System.out.println("realtime = " + realtime);
    System.out.println("timeset = " + timeset);

    if(realtime == timeset){

        System.out.println("if statement activated");
        Alert.man();
        break;

    }

So, my problem is when I run the programme the if statement doesn't run when timeset and realtime are equal and I just can't figure it out. What's the deal?

Community
  • 1
  • 1
  • Note that the comparison of pointers vs values is a very basic concept (in most languages) that you need to "get", if you want to become a programmer. It doesn't just apply to strings. – Hot Licks Jan 02 '13 at 16:50
  • I'm beginning to "get" it now. I've only just begun writing code, so I'm learning new things all the time and this is just one of them. – james kingsbury Jan 02 '13 at 17:00

1 Answers1

6

Use equals() method to check if two dates are equal. == operator just checks if two references point to the same instance.

if(realtime == timeset){

should be

if(realtime.equals(timeset)){
PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • 1
    The compare should take into account that you might not compare exactly on that second. The sleep is for one second, and one could have enough variation from one cycle to the next to miss a second. – Hot Licks Jan 02 '13 at 16:43
  • Thanks very much, that fixed it. Sorry about the vague question, I was finding it hard to articulate my thoughts into a title. – james kingsbury Jan 02 '13 at 16:46
  • @HotLicks true that, i completely agree with your statement .. – PermGenError Jan 02 '13 at 16:48