0

I'm doing a FizzBuzz test, and I notice the variable set in one of if statement is not working in another if condition. In below method, the input int number = 1, also getPrev() = 1, thus the expected output should = 1Bingo, however the real output is 1. If I change condition if(output == getPrev()) to if("1" == getPrev()), then the output is correct. Why the variable set in previous if statement is not working in next if condition?

public String evaluate(int number) {
    String output = "";
    
    
    if (number % 15 == 0) {
        output = "FizzBuzz";
        //return output;
    }
    
    
    else if (number % 3 == 0) {
        output ="Fizz";
        //return output;
    }
    
    else if (number % 5 == 0) {
        output = "Buzz";
        //return output;
    }
    
    
    else if (number % 3 != 0 && number % 5 != 0) {
        output = String.valueOf(number);
        //return output;
    }
    
    
    if(output ==  getPrev()) {
        output += "Bingo";
    
    }
    return output;

}
knittl
  • 216,605
  • 51
  • 293
  • 340

1 Answers1

0

Don't use == to validate String values; Use equals() method instead. == is ideal for primitive datatypes like int,long,float etc;

//considering getPrev() method returns a String obj
if(output.equals(getPrev())) {
   output += "Bingo";   
}

Refer here for how == and equals differs; Statements from the same article

In Java Strings, the == operator is used to check the reference of both the string objects and the equals() method used to check the value equality of both strings.

  1. == – checks reference equality
  2. equals() – checks the value equality