0

My problem is hidden in next code:

public class saturo { 
     public String primer, d;
     public void start() {
         primer = "545640";
         //d = "0";
         d = String.valueOf(primer.charAt(((primer.length())-1)));

         if(d == "0"){
             System.out.println("This is equal: d == " + d);
         }else{
             System.out.println("This is not equal: d == " + d);
         }
         }
        public static void main(String args[]) {
            new saturo().start();
        } 
    }

So as you see, the problem is that if i declare String d as "0" than the program will execute it as d is equal to "0" and return true;

But if i get character "0" from a String, convert it to String, and check if this equals to "0" then i have got a false.

I have checked if there is something wrong with character encode, but not, its right in any case. No type mismatches.

Where in this the logic?

Kovács Gergely
  • 73
  • 1
  • 10

2 Answers2

0

use .equals not == you are comparing by reference not value

Ashley Frieze
  • 4,993
  • 2
  • 29
  • 23
0

If you want to compare the value of 2 strings, you need to use .equals()

So you would do:

if(d.equals("0"){
 // your code here
}

Using == compares the strings by reference (same spot in memory) where .equals() compares the value of the strings.

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156