0

I have the following piece of code:

String week = this.getIntent().getStringExtra("weekNumber");
String correctWeek = Integer.toString(Calendar.WEEK_OF_YEAR);

if (week == correctWeek) {
    correct();
}

else incorrect();

They are both "3", but the comparation result is false and I don't know why:

enter image description here

Where is the error?

Lechucico
  • 1,914
  • 7
  • 27
  • 60

3 Answers3

2

Use equals() to compare strings for content, not ==.

== will check if the objects are the same.

String foo = "foo";

if (foo == foo) {
    // same object, so true
}
String foo1 = "foo";
String foo2 = "foo";

if (foo1 == foo2) {
    // both are string literals set at compile time, so true
}
String foo1 = loadFoo1(); // imagine this returns "foo"
String foo2 = loadFoo2(); // imagine this also returns "foo"

if (foo1 == foo2) {
    // not the same object, and not string literals, so false
}

if (foo1.equals(foo2)) {
    // both strings hold "foo", so true
}
Ben P.
  • 52,661
  • 6
  • 95
  • 123
0

The two strings are separate objects, and "==" tests if its two operands are the same exact object.

To compare strings, try week.equals(correctWeek)

0

The "==" operator is used for reference comparison. It checks if both objects point to the same memory location, which returns false in your case as you are comparing two different string objects.

For your purpose you should use .equals(), which evaluates to the comparison of values in the objects.

Example:

String week =  new String("3"); 
String correctWeek =  new String("3"); 
System.out.println(week == correctWeek); 
System.out.println(week.equals(correctWeek));

will output:

false
true
Alex
  • 11
  • 2