Java Credit Card Validation - Luhn Algorithm in Java With Examples

Recently I came to know that Credit Card numbers are not random and passes Luhn Algorithm test.

Java Credit Card Validation

Any credit card number should pass following test:

  1. From the rightmost digit, we should double every second digit. If the double is greater than 9, then add the both digits so that final number is of single digit.
  2. Now sum all the digits in the number, the unchanged numbers and the doubled numbers.
  3. The final sum should be multiple of 10 or mod 10 of the number should be 0. If it’s not then its not a valid credit card number.

Let’s check it with an example credit card number 12345678903555.

Digits are : 1,2,3,4,5,6,7,8,9,0,3,5,5,5
After doubling : 2,2,6,4,1,6,5,8,9,0,6,5,1,5
Sum of digits : 2+2+6+4+1+6+5+8+9+0+6+5+1+5 = 60 = 6*10 and hence a valid credit card number.

Luhn Algorithm in Java

Here I am providing java Luhn Algorithm program to validate credit card numbers.

Here I am taking input to the validation method as String, so that it will work also where the first digit is 0.

Output of the above program is:

Note that mobile phone IMEI number also follows the Luhn algorithm, go ahead and test it for your credit card numbers. 🙂

By admin

Leave a Reply

%d bloggers like this: