Google News
logo
ISBN Number in Java with example Program
An ISBN (International Standard Book Number) is a unique identifier for a book. It is a 10-digit or 13-digit code that identifies a particular book, edition, and format.

In this code, the last digit is a check digit calculated from the other digits, so it helps detect errors in the code.

Here is an example program in Java to check if a given string is a valid ISBN number or not :
Program :
import java.util.Scanner;

public class ISBNChecker {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a 10-digit ISBN number: ");
        String isbn = input.next();
        if (isValidISBN(isbn)) {
            System.out.println(isbn + " is a valid ISBN number.");
        } else {
            System.out.println(isbn + " is not a valid ISBN number.");
        }
    }

    public static boolean isValidISBN(String isbn) {
        if (isbn.length() != 10) {
            return false;
        }
        int sum = 0;
        for (int i = 0; i < 9; i++) {
            char c = isbn.charAt(i);
            if (!Character.isDigit(c)) {
                return false;
            }
            sum += (c - '0') * (i + 1);
        }
        char last = isbn.charAt(9);
        if (last == 'X') {
            sum += 10;
        } else if (Character.isDigit(last)) {
            sum += (last - '0') * 10;
        } else {
            return false;
        }
        return (sum % 11 == 0);
    }
}
Output :
Enter a 10-digit ISBN number: 1259060977
1259060977 is a valid ISBN number.
Enter a 10-digit ISBN number: 5236027917
5236027917 is not a valid ISBN number.
In this program, we first prompt the user to enter a 10-digit ISBN number. Then, we call the isValidISBN() method to check if the entered string is a valid ISBN number.

The isValidISBN() method checks if the length of the string is 10. If it is not, then it returns false. Then, it calculates the sum of the first 9 digits of the ISBN number, multiplied by their position, and adds the last digit (which could be a digit or an 'X') multiplied by 10.

If this sum is divisible by 11, then the ISBN number is valid, and the method returns true. Otherwise, it returns false.

Example : 1259060977

Sum = (1*10) + (2*9) + (5*8) + (9*7) + (0*6) + (6*5) + (0*4) + (9*3) + (7*2) + (7*1)

Sum = 10 + 18 + 40 + 63 + 0 + 30 + 0 + 27 + 14 + 7

Sum = 209

Now, we divide the sum with 11 and check whether the remainder is 0 or not.

rem = 209 % 11

rem = 0

Number 1259060977 is a legal ISBN because the remainder is equal to 0.