Question

i recently started to do some encryption with Apache DigestUtils. I simply want to use md5 hashes for authorization, but i'm an absolute beginner in this topic and in general not really experienced in Java. The API of this library provided me the methods md5, md5hex. If i'm not mistaken the result of these just differs in the output as a hexString (i'm not even sure whats this means) and regular bytes.

String b1 = DigestUtils.md5hex("Some String");
String b2 = DigestUtils.md5hex("Some String");

The result is 83beb8c4fa4596c8f7b565d390f494e2 & 83beb8c4fa4596c8f7b565d390f494e2 But a comparison with == results in false

    if (b1 == b2){
      System.out.println("Matching")

}

I'm pretty confused and i can't find a source for an introduction around this topic(for java!)

Was it helpful?

Solution

Because == is not how Strings are compared in Java, use .equals

For example...

if (b1.equals(b2)) {...

OTHER TIPS

"==" means to compare with the values.

  1. If you compare two object-type objects(such as String, Date), the compared value is their unique reference address in the jvm. That means you want to know if they are the same object

  2. If you compare two primitive types(such as int, float, double...), the compared value is their real values.

So if we want to compare two objects, we usually use equals() function instead of "==", because we just want to know if they they have the same attribute values.

Further more, If you define you own class, you should override the equals() function to compare objects of the class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top