{"id":9580,"date":"2020-05-04T18:57:40","date_gmt":"2020-05-04T13:27:40","guid":{"rendered":"https:\/\/java2blog.com\/?p=9580"},"modified":"2021-01-11T18:30:20","modified_gmt":"2021-01-11T13:00:20","slug":"luhn-algorithm-java","status":"publish","type":"post","link":"https:\/\/java2blog.com\/luhn-algorithm-java\/","title":{"rendered":"Java credit card validation &#8211; Luhn Algorithm in java"},"content":{"rendered":"<p>In this post, we will see about Luhn Algorithm in java<br \/>\n<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#Introduction\">Introduction<\/a><\/li><li><a href=\"#Detailed_implementation\">Detailed implementation<\/a><\/li><li><a href=\"#Using_Apache_common_validation\">Using Apache common validation<\/a><\/li><\/ul><\/div>\n\n<h2><span id=\"Introduction\">Introduction<\/span><\/h2>\n<p><code>Luhn algorithm<\/code>, also known as <code>modulus 10<\/code> or <code>mod 10<\/code> algorithm, is a simple checksum process for validating various identification numbers such as credit card numbers, Canadian social securities numbers.<br \/>\nThis algorithm is designed to protect again mistyped or accidental error rather than malicious attacks. Most credit card companies adopted this algorithm as this was available in the public domain and can be used by anyone.<\/p>\n<p>Here are the steps involved in Luhn Algorithms.<\/p>\n<hr \/>\n<p><strong><code>Step 1:<\/code><\/strong><br \/>\nFrom the rightmost digit, we should double every second digit.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"aligncenter wp-image-9591 size-full\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmMul2.jpg\" alt=\"LuhnAlgorithmMulBy2\" width=\"1272\" height=\"517\" srcset=\"https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmMul2.jpg 1272w, https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmMul2-300x122.jpg 300w, https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmMul2-1024x416.jpg 1024w, https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmMul2-768x312.jpg 768w\" sizes=\"(max-width: 1272px) 100vw, 1272px\" \/><\/p>\n<hr \/>\n<p><strong><code>Step 2:<\/code><\/strong><br \/>\nWhen we double the digits and get product in double digits, then we should add digits of the product.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"aligncenter wp-image-9593 size-full\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmSumD.jpg\" alt=\"LuhnAlgorithmSumDigits\" width=\"1146\" height=\"412\" srcset=\"https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmSumD.jpg 1146w, https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmSumD-300x108.jpg 300w, https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmSumD-1024x368.jpg 1024w, https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmSumD-768x276.jpg 768w\" sizes=\"(max-width: 1146px) 100vw, 1146px\" \/><\/p>\n<hr \/>\n<p><strong><code>Step 3:<\/code><\/strong><br \/>\nCompute the sum of all the digits.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"aligncenter wp-image-9592 size-full\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmSumAllD.jpg\" alt=\"\" width=\"1168\" height=\"328\" srcset=\"https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmSumAllD.jpg 1168w, https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmSumAllD-300x84.jpg 300w, https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmSumAllD-1024x288.jpg 1024w, https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmSumAllD-768x216.jpg 768w\" sizes=\"(max-width: 1168px) 100vw, 1168px\" \/><\/p>\n<hr \/>\n<p><strong><code>Step 4:<\/code><\/strong><br \/>\nIf total sum is divisible by 10 i.e. total sum modulo 10 is 0, then number is valid else it is not valid.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"aligncenter wp-image-9590 size-full\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmCheckVal.jpg\" alt=\"LuhnAlgorithmCheckValid\" width=\"1142\" height=\"304\" srcset=\"https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmCheckVal.jpg 1142w, https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmCheckVal-300x80.jpg 300w, https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmCheckVal-1024x273.jpg 1024w, https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/LuhnAlgorithmCheckVal-768x204.jpg 768w\" sizes=\"(max-width: 1142px) 100vw, 1142px\" \/><\/p>\n<p>As <code>90 mod 10 is 0<\/code>, hence this is valid credit card number.<\/p>\n<h2><span id=\"Detailed_implementation\">Detailed implementation<\/span><\/h2>\n<p>Let&#8217;s create java program to implement the Luhn algorithm.<\/p>\n<div>\n<pre class=\"lang:java nums:true mark:29,36,39,42,44,47,51 decode:1 \" >\npackage org.arpit.java2blog;\n\nimport java.util.Arrays;\n\npublic class LuhnAlgorithmMain {\n\n    public static void main(String[] args) {\n\n        String cardNumber=\"1358954993914435\";\n\n        boolean validCreditCardNumber = isValidCreditCardNumber(cardNumber);\n\n        if(validCreditCardNumber)\n        {\n            System.out.println(cardNumber+\" is valid as per luhn algorithm\");\n        }\n        else\n        {\n            System.out.println(cardNumber+\" is not valid as per luhn algorithm\");\n        }\n    }\n\n    public static boolean isValidCreditCardNumber(String cardNumber)\n    {\n        \/\/ int array for processing the cardNumber\n        int[] cardIntArray=new int[cardNumber.length()];\n\n        for(int i=0;i<cardNumber.length();i++)\n        {\n            char c= cardNumber.charAt(i);\n            cardIntArray[i]=  Integer.parseInt(\"\"+c);\n        }\n\n        for(int i=cardIntArray.length-2;i>=0;i=i-2)\n        {\n            int num = cardIntArray[i];\n            num = num * 2;  \/\/ step 1\n            if(num>9)\n            {\n                num = num%10 + num\/10;  \/\/ step 2\n            }\n            cardIntArray[i]=num;\n        }\n\n        int sum = sumDigits(cardIntArray);  \/\/ step 3\n\n        System.out.println(sum);\n\n        if(sum%10==0)  \/\/ step 4\n        {\n            return true;\n        }\n\n        return false;\n\n    }\n\n    public static int sumDigits(int[] arr)\n    {\n        return Arrays.stream(arr).sum();\n    }\n}\n<\/pre>\n<\/div>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"content-box-purple\">90<br \/>\n1358954993914435 is valid as per luhn algorithm<\/div>\n<p>Here are the steps involved in above java program for luhn algorithm.<\/p>\n<div class=\"content-box-grey\">\n<ol>\n<li>Convert a String <code>cardNumber<\/code> to int array <code>cardIntArray<\/code> for processing<\/li>\n<li>Iterate <code>cardIntArray<\/code> from rightmost side starting from <code>cardIntArray.length-2<\/code> with step of <code>i=i-2<\/code><\/li>\n<li>Mulitply digit by 2<\/li>\n<li>If product is greater than 9, sum the product<\/li>\n<li>Assign result back to <code>cardIntArray[i]<\/code><\/li>\n<li>Once the loop is over, compute sum of elements of <code>cardIntArray<\/code><\/li>\n<li>if <code>sum%10<\/code> is <code>0<\/code> then credit card number is valid else not valid as per luhn algorithm<\/li>\n<\/ol>\n<\/div>\n<h2><span id=\"Using_Apache_common_validation\">Using Apache common validation<\/span><\/h2>\n<p>In case, you don&#8217;t want to implement luhn algorithm you can use Apache common validation library and validate credit card number using <code>LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(creditCardNumber);<\/code><\/p>\n<p>You need to add following dependency to <code>pom.xml<\/code>.<\/p>\n<pre class=\"lang:xml decode:1 \" >\n&lt;!-- https:\/\/mvnrepository.com\/artifact\/commons-validator\/commons-validator --&gt;\n&lt;dependency&gt;\n&lt;groupId&gt;commons-validator&lt;\/groupId&gt;\n&lt;artifactId&gt;commons-validator&lt;\/artifactId&gt;\n&lt;version&gt;1.6&lt;\/version&gt;\n&lt;\/dependency&gt;\n<\/pre>\n<p>Let&#8217;s see with the help of example:<\/p>\n<pre>package org.arpit.java2blog;\n\nimport org.apache.commons.validator.routines.checkdigit.LuhnCheckDigit;\n\npublic class LuhnAlgorithmApache {\n\n    public static void main(String[] args) {\n\n        String cardNumber=\"79927398713\";\n\n        boolean validCreditCardNumber = isValidCreditCardNumberLuhn(cardNumber); \n\n        if(validCreditCardNumber)\n        {\n            System.out.println(cardNumber+\" is valid as per luhn algorithm\");\n        }\n        else\n        {\n            System.out.println(cardNumber+\" is not valid as per luhn algorithm\");\n        }\n    }\n\n    public static boolean isValidCreditCardNumberLuhn(String creditCardNumber)\n    {\n        return LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(creditCardNumber);\n    }\n}\n\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"content-box-purple\">79927398713 is valid as per luhn algorithm<\/div>\n<p>That&#8217;s all about Luhn Algorithm in java<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Table of ContentsIntroductionDetailed implementationUsing Apache common validation In this post, we will see about Luhn Algorithm in java Introduction Luhn algorithm, also known as modulus 10 or mod 10 algorithm, is a simple checksum process for validating various identification numbers such as credit card numbers, Canadian social securities numbers. This algorithm is designed to protect [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[218],"tags":[],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/9580"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=9580"}],"version-history":[{"count":0,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/9580\/revisions"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=9580"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=9580"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=9580"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}