• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

2 Different Magic Number in Java | Check whether a number is Magic Number or Not?

August 28, 2019 by javainterviewpoint Leave a Comment

Before looking at the Magic number in Java, let’s gets some basic understanding on a Magic number

What is a Magic Number?

A Magic Number is a text or numeric value which is used in the code which is used for some identification. Using such constant can help us distinguish the files among the many other file formats.

Say for example,

  • PDF Files will start with the magic text %PDF –> Hex (25 50 44 46)
  • PNG Files will start with the magic text %PNG –> Hex (25 50 4E 47)
  • Java class Files will start with the magic text Êþº¾ –> Hex (CAFEBABE)

What is a Magic Number in programming?

I got two different answers for a magic number in programming, let’s take a look into the code for both of them.

Program 1: Ramanujan Number or Taxicab Number

A Magic Number is a number which is equal to the product of the sum of all digits of a number and reverse of the sum. This is also known as Ramanujan Number or Taxicab Number. For Example, 1729 is a Magic Number. Sum of all digits is 19, the reverse of the Sum is 91, and Product of these numbers 19 * 91 is equal to the original number (19 * 91 = 1729). In this program, let’s print the Ramanujan Number

Magic Number in Java

  • Get the input number from the user
  • Calculate the sum of the individual digits
  • Find the reverse of the sum of digits
  • Multiply both sum and reverse, If the product is the same as the original number then it is a Magic Number
package com.javainterviewpoint;

import java.util.Scanner;

public class MagicNumber
{
    public static void main(String[] args)
    {
        System.out.println("Enter any number to check : ");    
        Scanner scanner = new Scanner(System.in);
        int originalNumber = scanner.nextInt();
        
        
        int sum = calculateSum(originalNumber);
        int reverseSum = findReverse(sum);
        
        if( (sum * reverseSum) == originalNumber)
            System.out.println(originalNumber +" is a Magic Number");
        else
            System.out.println(originalNumber +" is not a Magic Number");
    }
    
    public static int calculateSum(int number)
    {
        int sum = 0;
        while (number > 0)
        {
            sum = sum + number % 10;
            number = number / 10;
        }
        return sum;
    }
    public static int findReverse(int number)
    {
        int reverse = 0;
        while (number > 0)
        {
            int digit = number % 10;
            reverse = reverse * 10 + digit;
            number = number / 10;
        }
        return reverse;
    }
}

originalNumber hold the input number entered by the user

Calculate the Sum of each digit

The calculateSum() calculates the sum of all individual digits, while loop continues to run until the number is greater than zero.

First Iteration

At the start, number is 1729 and sum is 0, while (1729 > 0) is TRUE, now inside the while loop

sum = sum + number % 10 ( sum = 0 + 9), now sum is 9

Now we need to remove the last digit from the number, so we need to divide the number by 10 and so now number = 172

Second Iteration

The value of both number and sum are changed [number = 172 and sum = 9], while (172 > 0) is TRUE, so the execution continues into the while loop

sum = (9 + 172 % 10) —> sum = 11

Now remove the last digit from the number,

number  =  (number / 10)  —> number = (172 / 10) —> number = 17

Third Iteration

Now number is 17 and sum is 11, while (17 > 0) is TRUE

sum = (11 + 17 % 10) —> sum = 18

number = (17 / 10) —> number = 1

Fourth Iteration

Now number is 1 and sum is 18, while (1 > 0) is TRUE

sum = 18 + 1 % 10 —> sum = 19

number = 1 / 10 —> number = 0

Fifth Iteration fails as the number is now zero.

Find the reverse of sum

Now need to calculate the reverse of the sum, the findReverse() method calculates the reverse of the sum, here also the loop continues to executes until the value is not zero

First Iteration

number is 19 and reverse is 0, while( 19 > 0) is TRUE

digit = number % 10 (digit = 19 % 10), now digit is 9

reverse = reverse * 10 + digit (reverse = 0 + 9), now reverse is 9

Remove the last digit from the number, so we need to divide the number by 10 and so now number = 1

Second Iteration

Now number is 1 and reverse is 9, while( 1 > 0) is TRUE

digit = 1 % 10 —> digit = 1

reverse = 9 *10 + 1 —> reverse = 91

number = 1 / 10 —> number = 0

Third Iteration fails as the value of the number is zero.

Finally, calculate the product of sum and reverseSum, and check if it is equal to the original number.

Output:

Enter any number to check : 
1854
1854 is not a Magic Number
Enter any number to check : 
1729
1729 is a Magic Number

Java Program to Find Magic Numbers between 1 and 10000

Let’s now take a look into the program which prints all the Magic Numbers within the range of 1 to 10000

package com.javainterviewpoint;

public class MagicNumber
{
	public static void main(String[] args)
	{
		int i = 1;
		System.out.println("*** List of Magic Numbers between 1 to 10000 ***");
		while (i <= 10000)
		{
			int sum = calculateSum(i);
			int reverseSum = findReverse(sum);
			if ((sum * reverseSum) == i)
				System.out.println(i);
			i++;
		}
	}

	public static int calculateSum(int number)
	{
		int sum = 0;
		while (number > 0)
		{
			sum = sum + number % 10;
			number = number / 10;
		}
		return sum;
	}

	public static int findReverse(int number)
	{
		int reverse = 0;
		while (number > 0)
		{
			int digit = number % 10;
			reverse = reverse * 10 + digit;
			number = number / 10;
		}
		return reverse;
	}
}

Output:

*** List of Magic Numbers between 1 to 10000 ***
1
81
1458
1729

Program 2:

In this type, when the sum of all digits recursively added till the sum is a single digit, if the sum is equal to 1 then the number is a magic number.

For Example, 1234 is a magic number because the recursive sum of digits is 1

1 + 2 + 3 + 4 = 10  [10 is not a single digit, and hence we need to continue with the adding the digits again]

1 + 0 = 1   [Sum is now 1 and it is a single-digit]

package com.javainterviewpoint;

import java.util.Scanner;

public class MagicNumber
{
	public static void main(String[] args)
	{
		System.out.println("Enter any number to check : ");
		Scanner scanner = new Scanner(System.in);
		int number = scanner.nextInt();

		if(checkMagicNumber(number))
			System.out.println(number +" is a Magic Number");
		else
			System.out.println(number +" is not a Magic Number");
	}

	public static boolean checkMagicNumber(int number)
	{
		int sum = 0;
		while (number > 0 || sum > 9)
		{
			if (number == 0)
			{
				number = sum;
				sum = 0;
			}
			sum = sum + number % 10;
			number = number / 10;
		}
		
		if(sum == 1)
			return true;
		else
			return false;
	}
}

A simple tip for this approach is all the multiples of 9 + 1 will be a magic number.

1, 10, 19, 28, 37, 46, 55 …. so on..

We can re-write the above code simply like below

package com.javainterviewpoint;

import java.util.Scanner;

public class MagicNumber
{
	public static void main(String[] args)
	{
		System.out.println("Enter any number to check : ");
		Scanner scanner = new Scanner(System.in);
		int number = scanner.nextInt();

		if(checkMagicNumber(number))
			System.out.println(number +" is a Magic Number");
		else
			System.out.println(number +" is not a Magic Number");
	}

	public static boolean checkMagicNumber(int number)
	{
		//if( ( ((number / 9)*9) +1 ) == number)
			
		//if( number % 9 == 1)
		
		if( ((number - 1) % 9) == 0)
			return true;
		else
			return false;
	}
}

Bonus

Why is CAFEBABE Java’s Magic Word?

Explanation from James Gosling

“We used to go to lunch at a place called St Michael’s Alley. According to local legend, in the deep dark past, the Grateful Dead used to perform there before they made it big. It was a pretty funky place that was definitely a Grateful Dead Kinda Place.

When Jerry died, they even put up a little Buddhist shrine. When we used to go there, we referred to the place as Cafe Dead. Somewhere along the line, it was noticed that this was a HEX number.

I was re-vamping some file format code and needed a couple of magic numbers: one for the persistent object file, and one for classes. I used CAFEDEAD for the object file format, and in grepping for 4 character hex words that fit after “CAFE” (it seemed to be a good theme) I hit on BABE and decided to use it.

At that time, it didn’t seem terribly important or destined to go anywhere but the trash-can of history. So CAFEBABE became the class file format, and CAFEDEAD was the persistent object format. But the persistent object facility went away, and along with it went the use of CAFEDEAD – it was eventually replaced by RMI.

– Wikipedia

Filed Under: Core Java, Java, Java Interview Tagged With: CAFEBABE, CAFEDEAD, Magic Number, Magic Number in Java, Magic Numbers, Ramanujan Number, Taxicab Number

Leave a Reply Cancel reply

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

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

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·