Comparing values obtained from combo box to another string fails even though both appear to be the same

I am trying to obtain a date from 3 separate combo boxes that I then convert to ints and make a Date object. However, when I compare this date string to an already existing string, it doesnt match even though in the debugger it appears to be the same. I have setup a simple if statement to check what the problem is however I am not sure why it does not match.

int apptDay, apptMonth, apptYear;
apptDay = Integer.parseInt(consultationDay.getSelectedItem().toString());
apptMonth = Integer.parseInt(consultationMonth.getSelectedItem().toString());
apptYear = Integer.parseInt(consultationYear.getSelectedItem().toString());
consultationDate = new Date(apptDay, apptMonth, apptYear);

if (appointmentList.get(0).getDate() == consultationDate) {

I am quite sure that there is some issue with my code related to combo boxes as that is the only place where I face problems. The if statement is never satisfied so "Working" is never printed.

Any help would be appreciated.

>Solution :

You should use .equlas() instead of the == operator.

int apptDay = 5, apptMonth = 12, apptYear = 2000;
Date testDate = new Date(apptDay, apptMonth, apptYear);
Date consultationDate = new Date(apptDay, apptMonth, apptYear);

if (testDate == consultationDate) {
    System.out.println("Success for ==");
} else if (testDate.equals(consultationDate)) {
    System.out.println("Success for equals");

Leave a Reply