IMEI Validity Java Program

IMEI (International Mobile Equipment Identity) is a number which is used to identify mobile phones. It consists of 15 digits that includes various information about the mobile device.

The steps to check if an IMEI number is valid is as follows:

  1. Starting from the rightmost digit, find the double of every second digit.
  2. If the new value is a 2-digit number, then add the digits of that number to form a new 1-digit number.
  3. Find the sum of all the digits.
  4. If the sum is divisible by 10, then it is a valid IMEI number, otherwise not.

Write a Java program to accept a number and check if it is a valid IMEI number. Display a suitable message accordingly.

import java.io.*;
class IMEI{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter the IMEI number: ");
        long imei = Long.parseLong(br.readLine());
        String s = Long.toString(imei);
        if(s.length() != 15){
            System.out.println("IMEI must be a 15-digit number.");
            return;
        }
        long num = imei;
        int sum = 0;
        int a[] = new int[15];
        for(int i = 14; i >= 0; i--){
            a[i] = (int)(num % 10);
            num /= 10;
        }
        for(int i = 14; i >= 0; i--){
            if(i % 2 == 1){
                a[i] *= 2;
                while(a[i] > 9)
                    a[i] = sumOfDigits(a[i]);
            }
            sum += a[i];
        }
        System.out.println("Sum = " + sum);
        if(sum % 10 == 0)
            System.out.println(imei + " is a valid IMEI");
        else
            System.out.println(imei + " is not a valid IMEI");
    }
    public static int sumOfDigits(int n){
        int sum = 0;
        while(n != 0){
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }
}

Leave a Reply