0

I am working on developing a timer application in eclipse using swing tables to store data. The main issue I'm running into is that this if statement keeps returning true, even when the values in those variables are identical (as shown by the output). What could be causing this?

Here is my snippet of code:

String currentPID = lblCurrentPID.getText();
for (int i = 0; i < tableActive.getRowCount(); i++) {
    String currentValue = (String) tableActive.getValueAt(i, 2);
    System.out.println(i + ": Current Value: " + currentValue + " - Current PID: "+ currentPID);
    if (currentPID != currentValue) {
        System.out.println("The value and PID are not the same for some reason!");
    }
    else {
        tableActive.setValueAt(ts1.getOverallTotalTime(), i, 3);
        System.out.println(i + ": Row Was Changed!");
    }
}

Here is the Output:

0: Current Value: Test3 - Current PID: Test3

The value and PID are not the same for some reason!

1: Current Value: 12345 - Current PID: Test3

The value and PID are not the same for some reason!

2: Current Value: 54321 - Current PID: Test3

The value and PID are not the same for some reason!

Frederic
  • 3,274
  • 1
  • 21
  • 37
Evidencex
  • 111
  • 1
  • 11

4 Answers4

4
 if (currentPID != currentValue){

should be

 if (!currentPID.equals(currentValue)){

Use equals() to check string equality. == operator only checks if two ref varibales refer to the same String object.

PermGenError
  • 45,977
  • 8
  • 87
  • 106
1

When you do String (or) Object comparison, it is better to use equals()

 if (!currentPID.equals(currentValue)){
kosa
  • 65,990
  • 13
  • 130
  • 167
  • I do not agree that it is always better to use equals for all objects, in all situations. Sometimes it matters if one is dealing with the same instance or different instances. That is why, for example, there is an IdentityHashMap. – Patricia Shanahan Mar 13 '13 at 15:00
  • @PatriciaShanahan: Agree with you. Updated answer, deleted always. – kosa Mar 13 '13 at 15:02
1

should be if (!currentPID.equals(currentValue))

gashu
  • 484
  • 6
  • 17
1

In order to compare Strings in java, use equals and not == (or !=) see Java String.equals versus == to get all the good reasons.

Community
  • 1
  • 1
benzonico
  • 10,635
  • 5
  • 42
  • 50