Andrew
Andrew

Reputation: 175

equals() not working as expected

I'm trying to compare two post data fields to see if they're the same. If they're different I'm going to save the info. However I can't seem to get equals() to work correctly. Here's a sample:

String oldDesc1 = request.getParameter("desc1_old");
String oldDesc2 = request.getParameter("desc2_old");
String desc1 = request.getParameter("desc1");
String desc2 = request.getParameter("desc2");

if (!oldDesc1.equals(desc1) || !oldDesc2.equals(desc2)) {
    out.println("made it!!");
    part.setDescription(new String[] {desc1, desc2});
}
//added for testing
out.println("Old Desc 1: "+oldDesc1);
out.println("New Desc 1: "+desc1);
out.println("Old Desc 2: "+oldDesc2);
out.println("New Desc 2: "+desc2);

Now my Servlets output looks like this:

Old Desc1: foo1
New Desc1: bar1
Old Desc2: foo2
New Desc2: bar2

Notice how it's missing the "made it!!"

===EDIT====

My goal is to check and if either desc1 changes, desc2 changes, or both change to write the new info. Given the answers I'm seeing, you're statements are saying if desc1 and desc2 changes then save the info. I'm sorry if I didn't explain myself clearly enough before!

Upvotes: 0

Views: 81

Answers (2)

atish shimpi
atish shimpi

Reputation: 5023

if (!oldDesc1.equals(desc1) || !oldDesc2.equals(desc2)) {
    out.println("made it!!");
    part.setDescription(new String[] {desc1, desc2});
}

you are using || (OR) instead of && (AND) operator.

Modified code:

if (!oldDesc1.equals(desc1) && !oldDesc2.equals(desc2)) {
    out.println("made it!!");
    part.setDescription(new String[] {desc1, desc2});
}

Upvotes: 2

Maroun
Maroun

Reputation: 95948

You should refer to De morgan's laws:

(not a) OR (not b)  ⟷  not (a AND b)

Applying this rule to your condition, it'll be equivalent to:

if (!(oldDesc1.equals(desc1) && oldDesc2.equals(desc2)))

which is not what you want, use && instead of ||.

Upvotes: 5

Related Questions