# Java: Find and print the first 10 happy numbers

## Java Numbers: Exercise-9 with Solution

Write a Java program to find and print the first 10 happy numbers.

Happy number: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1, or it loops endlessly in a cycle which does not include 1.

Example: 19 is a happy number

1^{2} + 9^{2}=82

8^{2} + 2^{2}=68

6^{2} + 8^{2}=100

1^{2} + 0^{2} + 0^{2}=1

**Pictorial Presentation:**

**Sample Solution:**

**Java Code:**

```
import java.util.HashSet;
public class Example9 {
public static void main(String[] args){
System.out.println("First 10 Happy numbers:");
for(long num = 1,count = 0;count<8;num++){
if(happy_num(num)){
System.out.println(num);
count++;
}
}
}
public static boolean happy_num(long num){
long m = 0;
int digit = 0;
HashSet<Long> cycle = new HashSet<Long>();
while(num != 1 && cycle.add(num)){
m = 0;
while(num > 0){
digit = (int)(num % 10);
m += digit*digit;
num /= 10;
}
num = m;
}
return num == 1;
}
}
```

Sample Output:

First 10 Happy numbers: 1 7 10 13 19 23 28 31

**Flowchart: **

**Java Code Editor:**

** Contribute your code and comments through Disqus.**

**Previous:** Write a Java program to print out the first 10 Catalan numbers by extracting them from Pascal's triangle.

**Next:** Write a Java program to check whether a given number is a happy number or unhappy number.

**What is the difficulty level of this exercise?**

Test your Programming skills with w3resource's quiz.

## Java: Tips of the Day

**IsPowerOfTwo**

Checks if a value is positive power of two.

To understand how it works let's assume we made a call IsPowerOfTwo(4).

As value is greater than 0, so right side of the && operator will be evaluated.

The result of (~value + 1) is equal to value itself. ~100 + 001 => 011 + 001 => 100. This is equal to value.

The result of (value & value) is value. 100 & 100 => 100.

This will value the expression to true as value is equal to value.

public static boolean isPowerOfTwo(final int value) { return value > 0 && ((value & (~value + 1)) == value); }

Ref: https://bit.ly/3sA5d4I

**Weekly Trends**- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook