Java Program to Check Happy number

Learn to write a simple java program to verify if a given number is happy number or not.

1. what is a happy number

A number is called happy if it will yield '1' when it is replaced by the sum of the square of its digits repeatedly. In other words if we start with Happy Number and keep replacing it with digits square sum, we reach 1

If this process results in an endless cycle of numbers, then the number is called an unhappy number (or sad numbers).

For example, consider following example of number 32.

Number is : 32

32 + 22 = 13

12 + 32 = 10

12 + 02 = 1

Some of the other examples of happy numbers are 7, 28, 100, 320 and so on.

2. Algorithm to determine happy number

To find if a given number is happy or not –

  1. Calculate the square of each digit present in number and add it to a variable sum.
    • If resulting sum is equal to 1 then given number is a happy number.
    • If the sum is equal to previously encountered number, then it is unhappy number.
  2. Else replace the number with the sum of the square of digits.

3. Java Program to find Happy number

package com.howtodoinjava.java8.example;

import java.util.HashSet;
import java.util.Set;

public class Main 
	public static void main(String[] args) {
		System.out.println("32 is happy number " + isHappyNumber(32));
		System.out.println("7  is happy number " + isHappyNumber(7));
		System.out.println("28 is happy number " + isHappyNumber(28));
		System.out.println("30 is happy number " + isHappyNumber(30));
		System.out.println("9  is happy number " + isHappyNumber(9));
		System.out.println("24 is happy number " + isHappyNumber(24));
    static boolean isHappyNumber(int numberToCheck) 
    	Set<Integer> uniqueNumbersEncounterd = new HashSet<Integer>();
    	//Just to avoid any infinite loop
    	while (uniqueNumbersEncounterd.add(numberToCheck))
            int value = 0;
            while (numberToCheck > 0)
                value += Math.pow(numberToCheck % 10, 2);
                numberToCheck /= 10;
            numberToCheck = value;

        return numberToCheck == 1;

Program output.

32 is happy number true
7  is happy number true
28 is happy number true

30 is happy number false
9  is happy number false
24 is happy number false

Happy Learning !!

Ref : Wikipedia


Notify of
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.