Credit Card Check Digit Generator Java Program

Filed Under: Java

In the last post, we saw that Credit Card numbers are not random and it can be validated using Luhn Algorithm and I wrote a java program for credit card number validation.

A credit card number last digit is called Check Digit and its appended to a partial credit card number to generate the complete valid credit card number. For example, if we have a partial card number of 15 digits as 123456789012345 then using Luhn algorithm, we find that check digit should be 2, so the valid credit card number will be 1234567890123452.

Here I am providing a method in java to generate the check digit for a partial credit card number.


public class GenerateCheckDigit {

	public static void main(String[] args) {
		long l = 123456789012345L;
		int cd = generateCheckDigit(l);
		System.out.println("Valid card number="+l+cd);

	private static int generateCheckDigit(long l) {
		String str = Long.toString(l);
		int[] ints = new int[str.length()];
		for(int i = 0;i< str.length(); i++){
			ints[i] = Integer.parseInt(str.substring(i, i+1));
		for(int i = ints.length-2; i>=0; i=i-2){
			int j = ints[i];
			j = j*2;
				j = j%10 + 1;
		int sum=0;
		for(int i = 0;i< ints.length; i++){
			return 0;
		}else return 10-(sum%10);


Once the valid account number is generated by adding check digit to the partial credit card number, you can validate it using my last program to validate credit card number.

Leave a Reply

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

Generic selectors
Exact matches only
Search in title
Search in content