0

I'm grabbing the current win7 username which is rsmith but my if statement below displays: 0000 rsmith 2222 rsmith

Why doesn't my if == line work as expected? The userName IS rsmith

        String userName = System.getProperty("user.name");
        System.out.println("0000 " + userName + "\n");
        if (userName == "rsmith"){
            System.out.println("1111 " + userName + "\n");
        }
        else {
            System.out.println("2222 " + userName + "\n");
        }
RalphF
  • 373
  • 3
  • 10
  • 21

4 Answers4

2

You should not compare Strings with ==. You should use the equals() method.

 if (userName.equals("rsmith"){
   ..
 }

See this excellent answer for a more detailed explanation.

Community
  • 1
  • 1
micha
  • 47,774
  • 16
  • 73
  • 80
1

The == operator compares whether two object references reference the same object in memory (referential equality), not whether they are equal. The String class' implementation of equals() compares whether two String objects have the same characters (value equality).

Hence, it would be:

if (userName.equals("rsmith") {
    ....
}
blackpanther
  • 10,998
  • 11
  • 48
  • 78
0

== tests for reference equality.

.equals() tests for value equality.

Consequently, if you actually want to test whether two strings have the same value you should use .equals().

== is for testing whether two strings are the same object.

        String userName = System.getProperty("user.name");
        System.out.println("0000 " + userName + "\n");
        if (userName.equals("rsmith")){
            System.out.println("1111 " + userName + "\n");
        }
        else {
            System.out.println("2222 " + userName + "\n");
        }
Kick
  • 4,823
  • 3
  • 22
  • 29
0

==

compares 2 objects to check if they refer the same place in the memory

.equals()

compares the values of the object.

In your case, you need to use .equals to compare

Orhan Obut
  • 8,756
  • 5
  • 32
  • 42