I am trying to run a getBook() method in a Bookstore program which can allow me to find a book stored in the AL books not only if title and author are correct but also if one of them is null. So, I wrote this code:
public Book getBook(String author, String title){
boolean condOk = false;
Book book = null;
if(books!=null){
for(int i=0; i<books.size(); i++){
if((author==null && title.equals(books.get(i).getTitle())) ||
(author.equals(books.get(i).getAuthor()) && title==null)){
condOk = true;
book = books.get(i);
break;
} else if(title.equals(books.get(i).getTitle()) &&
author.equals(books.get(i).getAuthor())){
condOk = true;
book = books.get(i);
break;
}
}
}
if(condOk==false) return null;
else return book;
}
The J-Unit test (not created by me) of this part, puts in books 4 objects (with constructor: String title, String author, ...) and then it tests the method getBook() three times: with author and title, with title expressed and author null, and a last time with the opposite situation.
I have already tried something and I noticed that if I substitute all the equals() calls with the logical op == everything works fine. In the Book class everything is correct, all the getters and setters are in the right place.
So, why do I get such a behavior, when several times I read that comparing Strings with equals() is better than doing it with ==?