Computing the Hamming distance between two strings in Java?

Odd. I was looking this morning for some Java code to compute the Hamming distance between any two strings in Java, and could not find it. There are plenty of code samples for the Hamming distance between integers, but I am really looking for something that can process String objects.

Anyone knows where I could find this?

Update. Yes, I know it is not difficult. I am really looking for a Java two-liner.

Published by

Daniel Lemire

A computer science professor at the University of Quebec (TELUQ).

4 thoughts on “Computing the Hamming distance between two strings in Java?”

  1. It’s very easy to compute — it’s just the number of differences, right?

    def hamming(s1 ,s2)
    dist = 0,s1.length-1).each {|i| dist += 1 unless s1[i] == s2[i] }

  2. Right.

    I got as far as this:

    int hamming (String s1, String s2) {
    if(s1.size() != s2.size()) return -1;// not sure whether there is someting better to do
    int counter = 0;
    for (int k = 0; k < s1.size();++k) if( != ++counter; return counter; }

    But that's a tad ugly.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see