2

so i ran this code

        String line = worldRead.readLine();

        String[] aLine = line.split("");

        for (int i = 0; i < aLine.length; i++){

            System.out.println(aLine[i]);

            if(aLine[i] == "0"){

                System.out.println("Its an 0");

            }

        }

and it prints the first line of the file as it should one character by one, but the if statement isn't working, I looked at the de bugger and it says the the value of aLine[i] at that time was "0". I don't understand this strange behavior. Why is this ?

Kacper Lubisz
  • 780
  • 2
  • 10
  • 17

5 Answers5

3

use if(aLine[i].equals("0"))

== checks the obeject while equals compare the values

stinepike
  • 54,068
  • 14
  • 92
  • 112
3
 if(aLine[i] == "0"){

     System.out.println("Its an 0");
 }

never compare strings with ==. use the equals method.

 if(aLine[i].equals("0"){
     System.out.println("Its an 0");
 }

Why?

Well, using the == operator will actually check if these two objects are the same object. What you're testing is the values inside those objects.

christopher
  • 26,815
  • 5
  • 55
  • 89
0

Use equals method for string comparision.

== will not compare string object's string value it just checks for reference equality.

In this respect if you compare two string objects with same value they are not equal by == operator.

String line = worldRead.readLine();

        String[] aLine = line.split("");

        for (int i = 0; i < aLine.length; i++){

            System.out.println(aLine[i]);

            if(aLine[i].equals("0")){

                System.out.println("Its an 0");

            }

        }

It should work now.

pinkpanther
  • 4,770
  • 2
  • 38
  • 62
0

As others have said, string comparisons in Java should be done using .equals() rather than ==. The latter only checks for object identity and two String objects in Java can have the same value without being the same object. In this case, since your strings are guaranteed to be one character long, you can compare characters using ==. You can also simplify your code a bit using an enhanced for loop:

String line = worldRead.readLine();
for (String s : line.split("")){
    System.out.println(s);
    if (s.charAt(0) == '0') {  // or s.equals("0")
        System.out.println("Its an 0");
    }
}
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

as StinePike said above, use equals() instaed of ==.

Two string objects are not the same, but equal!

Peggy
  • 394
  • 6
  • 22