0

The program I'm making needs to output true or false when using method backwards(), indicating if the string is backwards or not.. But it keeps displaying false when it's supposed to be true...

public class StringImproved
{
   private String word;

public StringImproved(String word)
{
  this.word = word; 
}
public String getWord()
{
  return(this.word); 
}
public void setWord(String word)
{
  this.word = word; 
}
public int size()
 {
  return(this.word.length()); 
 }
 public boolean backwards(String word)
{
   String backwards = "";
   for(int i = getWord().length() - 1; i >= 0; i--)
   {
     backwards += getWord().charAt(i);
    }
   if(backwards == word)
   {
   return true; 
   }
   else return false;
    }
}


public class test
{
   public static void main(String [] args)
 {
 StringImproved si=new StringImproved("lag");
 System.out.println(si.backwards("gal")); 

  }
  }
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
Edward Lavaire
  • 31
  • 2
  • 4
  • 9

1 Answers1

2

In this line:

if(backwards == word)

you need to use equals instead of ==:

if(backwards.equals(word))

This is because == just checks whether the backwards and word variables point to the same object, whereas equals checks whether the objects pointed to by the two variables have the same contents.

Sam Estep
  • 12,974
  • 2
  • 37
  • 75