Validating ISBN number in Java

An ISBN ( International Standard Book Number) is a ten digit code which uniquely identifies a book. The first nine digits represent the Group, Publisher and Title of the book and the last digit is used to check whether ISBN is correct or not. Each of the first nine digits of the code can take a value between 0 and 9. Sometimes it is necessary to make the last digit equal to ten; this is done by writing the last digit of the code as X. To verify an ISBN, calculate 10 times the first digit, plus 9 times the second digit, plus 8 times the third and so on until we add 1 time the last digit. If the final number leaves no remainder when divided by 11, the code is a valid ISBN.

For example:

02011003311 = 10*0 + 9*2 + 8*0 + 7*1 + 6*1 + 5*0 + 4*3 + 3*3 + 2*1 + 1*1 = 55
Since 55 leaves no remainder when divisible by 11, hence it is a valid ISBN.

Design a program to accept a ten digit code from the user. For an invalid input, display an
appropriate message. Verify the code for its validity in the format specified below:
Test your program with sample data and some random data.

Example 1
INPUT CODE : 0201530821

Example 2
INPUT CODE : 035680324

Example 1
INPUT CODE : 0231428031
OUTPUT : SUM = 122

The program for the above problem is as follows:

import java.util.*;
class ISBN{
	public static boolean isValidISBN(String isbn){
		int digit, sum=0, len=isbn.length();
		if(len!=10) throw new IllegalArgumentException();
		for(int i=0;i<len;i++){
			digit=(digit==40 || digit==72)?10:digit;
			sum += digit*(10-i);
		System.out.println("OUTPUT:\tSUM = "+sum);			
		return (sum%11)==0;
	public static void main(String args[]){
		Scanner sc = new Scanner(;
		String isbn;
		System.out.print("INPUT CODE:\t");
				System.out.println("\t\tLEAVES NO REMAINDER- VALID CODE");
				System.out.println("\t\tLEAVES REMAINDER- INVALID CODE");
		}catch(IllegalArgumentException e){
			System.out.println("INVALID INPUT");

The above code is very straight forward, but the students should note that for efficiency length of the string must never be calculated with the condition part of a loop. The length function of the String class iterate through the entire string in order to calculate the length. If the length function is given in the condition part of the loop, it will be executed for each iteration of the loop, thereby increasing the computational complexity from O(N) to O(N2). Also, notice the use of try-catch block and throw statement to separate the error handling logic from the core logic leading to manageable code with increased readability which is very important in large programs where the object oriented programming (OOP) is usually used.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.