Java Programs
Java Programs
START
1. Read an integer number from the user.
2. Multiply the number by 2.
3. Convert the result into a string.
4. Extract the middle two digits of the result.
5. If both middle digits are the same, then the number is a Strontio
Number.
6. Otherwise, it is not a Strontio Number.
END
Java Program
import java.util.Scanner;
class Strontio {
int num; // variable to hold input number
// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();
// Object creation
Strontio s = new Strontio(n);
// Output
if (s.isStrontio())
System.out.println(n + " is a Strontio Number.");
else
System.out.println(n + " is NOT a Strontio Number.");
sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
num int Stores the input number to check Strontio property
result int Stores the doubled value of the input number
str String Holds the string representation of result
mid1 int Index of first middle digit of str
mid2 int Index of second middle digit of str
n int Temporary variable in main to store user input
Algorithm for EVIL Number
START
1. Read an integer number from the user.
2. Convert the number into its binary equivalent.
3. Count the number of 1s in the binary representation.
4. If the count of 1s is even, then it is an EVIL number.
5. Otherwise, it is NOT an EVIL number.
END
Java Program
import java.util.Scanner;
class Evil {
int num; // variable to hold input number
// Constructor
Evil(int n) {
num = n;
}
// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();
// Object creation
Evil e = new Evil(n);
// Output
if (e.isEvil())
System.out.println(n + " is an EVIL Number.");
else
System.out.println(n + " is NOT an EVIL Number.");
sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
num int Stores the input number to check EVIL property
binary String Holds the binary representation of the number
count int Counts the number of 1s in the binary string
n int Temporary variable in main to store user input
Algorithm for Keith Number
START
1. Read an integer number from the user.
2. Store its digits in an array (digit by digit).
3. Repeatedly:
a) Add all the digits of the array.
b) Shift the array left (discard the first digit).
c) Append the sum at the end of the array.
4. Continue until the sum is greater than or equal to the original number.
5. If the sum equals the original number, it is a Keith Number.
6. Otherwise, it is NOT a Keith Number.
END
Java Program
import java.util.Scanner;
class Keith {
int num; // input number
// Constructor
Keith(int n) {
num = n;
}
int sum = 0;
while (sum < num) {
sum = 0;
for (int i = 0; i < d; i++) {
sum += arr[i];
}
if (sum == num) return true;
// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();
// Object
Keith k = new Keith(n);
// Output
if (k.isKeith())
System.out.println(n + " is a Keith Number.");
else
System.out.println(n + " is NOT a Keith Number.");
sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
num int Stores the input number to check Keith property
s String Holds string form of number to count digits
d int Number of digits in the input number
arr[] int[] Array storing digits and later sequence values
sum int Stores sum of last d terms for Keith sequence
n int Temporary variable in main to store user input
Algorithm for Pronic Number
START
1. Read an integer number from the user.
2. Initialize i = 0.
3. Repeat until i * (i + 1) is greater than or equal to the number:
a) If i * (i + 1) = number, then it is a Pronic Number.
b) Otherwise increase i by 1.
4. If no such i exists, then it is NOT a Pronic Number.
END
Java Program
import java.util.Scanner;
class Pronic {
// Function to check Pronic number
boolean isPronic(int num) {
for (int i = 0; i <= num; i++) {
if (i * (i + 1) == num)
return true;
}
return false;
}
}
// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();
// Object creation
Pronic p = new Pronic();
// Output
if (p.isPronic(n))
System.out.println(n + " is a Pronic Number.");
else
System.out.println(n + " is NOT a Pronic Number.");
sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
num int Stores the input number to check Pronic property
i int Loop variable used to test i * (i+1)
n int Temporary variable in main to store user input
Algorithm for Composite Magic Number
START
1. Read a number from the user.
2. Check if the number is composite:
- If it has more than 2 factors, it is composite.
3. If composite:
a) Find the sum of its digits.
b) Repeat: Replace the number by the sum of its digits until it
becomes a single digit.
c) If the final single digit = 1, then it is a Magic Number.
4. If both composite AND magic → Composite Magic Number.
5. Else → Not a Composite Magic Number.
END
Java Program
import java.util.Scanner;
class CompositeMagic {
// Function to check composite number
boolean isComposite(int num) {
if (num <= 3) return false;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0)
return true;
}
return false;
}
// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();
CompositeMagic cm = new CompositeMagic();
// Output
if (cm.isComposite(n) && cm.isMagic(n))
System.out.println(n + " is a Composite Magic Number.");
else
System.out.println(n + " is NOT a Composite Magic Number.");
sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
num int General variable used in checking composite/magic
i int Loop variable for checking factors
sum int Stores digit sum at each reduction step
n int Stores user input in main
Algorithm for ORE Number
START
1. Read a number from the user.
2. Find all divisors of the number.
3. Count the number of divisors and compute their sum.
4. Find the sum of digits of the number.
5. Count the number of digits in the number.
6. Calculate both ratios:
- Divisor ratio = (sum of divisors) / (count of divisors)
- Digit ratio = (sum of digits) / (count of digits)
7. If both ratios are equal → ORE Number.
8. Otherwise → Not an ORE Number.
END
Java Program
import java.util.Scanner;
class ORE {
// Function to check ORE number
boolean isORE(int num) {
int sumDiv = 0, countDiv = 0;
// find divisors
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
sumDiv += i;
countDiv++;
}
}
// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();
// Output
if (o.isORE(n))
System.out.println(n + " is an ORE Number.");
else
System.out.println(n + " is NOT an ORE Number.");
sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
num int Stores the input number to check ORE property
sumDiv int Sum of divisors of the number
countDiv int Count of divisors of the number
temp int Temporary copy of num used for digit operations
sumDig int Sum of digits of the number
countDig int Count of digits of the number
n int User input stored in main
Algorithm For Kaprekar number
START
1. Read a number from the user.
2. Compute square of the number.
3. Count the number of digits in the original number.
4. Split the square into two parts:
- Right part: last (digit count) digits of the square.
- Left part: remaining digits of the square.
5. If (left part + right part) = original number, it is a Kaprekar Number.
6. Otherwise, it is NOT a Kaprekar Number.
END
Java Program
import java.util.Scanner;
class Kaprekar {
// Function to check Kaprekar number
boolean isKaprekar(int num) {
if (num == 1) return true; // 1 is Kaprekar by definition
// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();
// Output
if (k.isKaprekar(n))
System.out.println(n + " is a Kaprekar Number.");
else
System.out.println(n + " is NOT a Kaprekar Number.");
sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
num int Stores the input number to check Kaprekar property
sq long Stores the square of the number (can be large)
d int Number of digits in the input number
right long Last d digits of the square
left long Remaining digits of the square
n int User input stored in main
Algorithm For Goldbach number
START
1. Read an even number n from the user (n > 2).
2. For every i from 2 to n/2:
a) Check if both i and (n - i) are prime.
b) If yes, then n can be expressed as sum of two primes → Goldbach
Number.
3. If no such pair exists, then it is NOT a Goldbach Number.
END
Java Program
import java.util.Scanner;
class Goldbach {
// Function to check prime
boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0)
return false;
}
return true;
}
// Input
System.out.print("Enter an even number greater than 2: ");
int n = sc.nextInt();
// Output
if (g.isGoldbach(n))
System.out.println(n + " is a Goldbach Number.");
else
System.out.println(n + " is NOT a Goldbach Number.");
sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
num int Input number to check Goldbach property
i int Loop variable to try prime pairs
n int User input in main
Algorithm for ISBN Number
START
1. Read a 10-digit number from the user.
2. Initialize sum = 0.
3. For each digit (from left to right):
- Multiply the digit by its position (1 to 10).
- Add to sum.
4. If sum % 11 == 0 → Valid ISBN number.
5. Otherwise → Invalid ISBN number.
END
Java Program
import java.util.Scanner;
class ISBN {
// Function to check ISBN number
boolean isISBN(long num) {
String s = String.valueOf(num);
if (s.length() != 10) return false; // must be 10 digits
int sum = 0;
for (int i = 0; i < 10; i++) {
int digit = s.charAt(i) - '0';
sum += (i + 1) * digit;
}
return sum % 11 == 0;
}
}
// Input
System.out.print("Enter a 10-digit number: ");
long n = sc.nextLong();
// Output
if (obj.isISBN(n))
System.out.println(n + " is a Valid ISBN Number.");
else
System.out.println(n + " is NOT a Valid ISBN Number.");
sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
num long Stores the input 10-digit number
s String String form of the number (to access each digit)
sum int Stores weighted sum of digits
digit int Individual digit extracted from the string
i int Loop counter for digit positions
n long User input stored in main
Algorithm for Potential of String
START
1. Read a string from the user.
2. Initialize sum = 0.
3. For each character in the string:
a) Convert it to uppercase.
b) If it is a letter between A–Z:
- Find its position: (ch - 'A' + 1).
- Add to sum.
4. Print the sum as the potential of the string.
END
Java Program
import java.util.Scanner;
class Potential {
// Function to calculate potential of a string
int getPotential(String str) {
int sum = 0;
str = str.toUpperCase();
// Input
System.out.print("Enter a string: ");
String s = sc.nextLine();
// Output
int pot = p.getPotential(s);
System.out.println("Potential of \"" + s + "\" = " + pot);
sc.close();
}
}
Variable Description
Variable Name Data Type Description (Purpose)
str String Stores the input string
sum int Stores the total potential of the string
ch char Holds individual character of the string
i int Loop counter for traversing characters
s String User input stored in main
pot int Final computed potential value
Algorithm for Clockwise Rotation of a Matrix
START
1. Read the size (n) of the matrix.
2. Input the n×n matrix elements.
3. To rotate clockwise:
a) Transpose the matrix (swap rows with columns).
b) Reverse each row.
4. Print the rotated matrix.
END
Java Program
import java.util.Scanner;
class MatrixRotation {
// Function to rotate matrix clockwise by 90 degrees
void rotateClockwise(int[][] mat, int n) {
// Step 1: Transpose
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
System.out.println("Original Matrix:");
mr.printMatrix(mat, n);
mr.rotateClockwise(mat, n);
sc.close();
}
}
Variable Description
Variable Name Data Type Description
n int Size of the square matrix
mat int[][] 2D array storing matrix elements
i, j int Loop counters for rows and columns
temp int Temporary variable for swapping elements
sc Scanner To take user input
Algorithm for Anticlockwise Rotation of a
Matrix
START
1. Read the size (n) of the matrix.
2. Input the n×n matrix elements.
3. To rotate anticlockwise:
a) Transpose the matrix (swap rows with columns).
b) Reverse each column.
4. Print the rotated matrix.
END
class MatrixRotation {
// Function to rotate matrix anticlockwise by 90 degrees
void rotateAnticlockwise(int[][] mat, int n) {
// Step 1: Transpose
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
System.out.println("Original Matrix:");
mr.printMatrix(mat, n);
mr.rotateAnticlockwise(mat, n);
sc.close();
}
}
🔹 Variable Description
Variable Name Data Type Description
n int Size of the square matrix
mat int[][] 2D array storing matrix elements
i, j int Loop counters for rows and columns
temp int Temporary variable for swapping elements
sc Scanner To take user input
Concept/Algorithm
Octal Number System → Base 8 (digits: 0–7).
Decimal Number System → Base 10.
To convert an octal number to decimal, multiply each digit by the corresponding
power of 8 and sum the results. The rightmost digit is multiplied by 8⁰ (which is 1),
the next digit to the left by 8¹, then 8², and so on for the whole number part. For
fractional parts, the powers of 8 become negative (8⁻¹, 8⁻², etc.).
// Conversion
while (temp > 0) {
int lastDigit = temp % 10; // extract last digit
decimal += lastDigit * base; // add to decimal
base *= 8; // increase power of 8
temp /= 10; // remove last digit
}
sc.close();
}
}
Variable Description
Variable Name Data Type Description
octal int Stores input octal number
decimal int Stores converted decimal value
base int Keeps track of powers of 8 (1, 8, 64, …)
temp int Temporary copy of octal for processing
lastDigit int Extracted last digit of the octal number
Algorithm FOR ODIOUS NUMBER
START
Step 1: Input a number n.
Step 2: Initialize count = 0.
Step 3: Repeat until n > 0:
- If n % 2 == 1, increase count by 1.
- Divide n by 2 (n = n / 2).
Step 4: If count is odd → Odious Number.
Step 5: Else → Not Odious Number.
END
Java Program
import java.util.Scanner;
if (isOdious(num))
System.out.println(num + " is an Odious Number");
else
System.out.println(num + " is NOT an Odious Number");
sc.close();
}
}
Variable Description
Variable Name Data Type Description
n int Number being checked in the function
count int Counts number of 1’s in binary representation
num int User input number
sc Scanner To accept user input
Algorithm (Mystery Number)
START
Step 1: Input a number n.
Step 2: For i = 1 to n/2:
- Reverse i → rev
- If i + rev = n, then n is a Mystery Number.
Step 3: If such i exists, print "Mystery Number".
Step 4: Otherwise, print "Not a Mystery Number".
END
Java Program
import java.util.Scanner;
if (isMystery(num))
System.out.println(num + " is a Mystery Number");
else
System.out.println(num + " is NOT a Mystery Number");
sc.close();
}
}
Variable Description
Variable Name Data Type Description
n int Number to be checked
i int Iterator for possible parts of n
rev int Stores reverse of i
num int User input number
sc Scanner For user input
Algorithm (Undulating Number)
START
Step 1: Input a number n.
Step 2: Convert n into a string s.
Step 3: If length of s < 3, then not undulating.
Step 4: Let first digit = a, second digit = b.
Step 5: If a == b, then not undulating.
Step 6: For i from 0 to length-1:
- If i is even → digit must be a
- If i is odd → digit must be b
- If condition fails → not undulating.
Step 7: If loop completes, then n is undulating.
END
Java Program
import java.util.Scanner;
if (s.length() < 3)
return false;
char a = s.charAt(0);
char b = s.charAt(1);
if (a == b)
return false;
if (isUndulating(num))
System.out.println(num + " is an Undulating Number");
else
System.out.println(num + " is NOT an Undulating Number");
sc.close();
}
}
Variable Description
Variable Name Data Type Description
n int Number to be checked
s String String form of number
a char First digit
b char Second digit
i int Loop counter
num int User input number
sc Scanner For user input
Algorithm
START
Step 1: Input a number n.
Step 2: Copy n into temp.
Step 3: Initialize sum = 0.
Step 4: While temp > 0:
- Extract digit = temp % 10
- If digit == 0 → add 0
- Else → add digit^digit to sum
- temp = temp / 10
Step 5: If sum == n → n is a Münchhausen number
else not.
END
Java Program
import java.util.Scanner;
if (digit == 0) {
sum += 0; // 0^0 = 0 (by definition here)
} else {
int power = 1;
for (int i = 1; i <= digit; i++) {
power *= digit; // calculate digit^digit
}
sum += power;
}
temp /= 10;
}
return sum == n;
}
if (isMunchhausen(num))
System.out.println(num + " is a Münchhausen Number");
else
System.out.println(num + " is NOT a Münchhausen Number");
sc.close();
}
}
Variable Description
Variable Name Data Type Description
n int Number to be checked
temp int Copy of number for digit extraction
sum int Sum of digit^digit
digit int Current extracted digit
power int Value of digit^digit
num int User input number
sc Scanner For user input
Algorithm (Steps)
1. Read the number n.
2. Find sum of digits of n.
3. Check if n % sum == 0.
o If yes → Good Number.
o Else → Not a Good Number.
Java Program
import java.util.Scanner;
if (isGoodNumber(num))
System.out.println(num + " is a Good Number");
else
System.out.println(num + " is NOT a Good Number");
sc.close();
}
}
Variable Description
Variable Type Meaning
n int Input number to check
temp int Copy of number for digit extraction
sum int Sum of digits
num int User input number
sc Scanner Input object
Algorithm (Steps)
1. START
2. Read number n.
3. Compute cuberoot = round(cube root of n).
4. If cuberoot * cuberoot * cuberoot != n, then it is not a Dudeney Number →
END.
5. Find sum of digits of n.
6. If sum of digits = cube root → Dudeney Number.
7. Else → Not a Dudeney Number.
8. END
Java Program
import java.util.Scanner;
if (isDudeney(num))
System.out.println(num + " is a Dudeney Number");
else
System.out.println(num + " is NOT a Dudeney Number");
sc.close();
}
}
Variable Description
Variable Data Type Description
n int Input number to be checked
cuberoot int Cube root of the number
temp int Copy of number for digit extraction
sum int Sum of digits
num int User input number
sc Scanner Input object
Algorithm (Steps)
1. START
2. Read the number n.
3. Compute the sum of digits of n.
4. Reverse the sum of digits.
5. Check:
o if n % sum == 0
o AND n % reverseSum == 0
6. If both true → Doubly Markov Number.
7. Else → Not a Doubly Markov Number.
8. END
Java Program
import java.util.Scanner;
// reverse of sum
int rev = 0, s = sum;
while (s > 0) {
rev = rev * 10 + (s % 10);
s /= 10;
}
// check divisibility
return (n % sum == 0 && n % rev == 0);
}
if (isDoublyMarkov(num))
System.out.println(num + " is a Doubly Markov Number");
else
System.out.println(num + " is NOT a Doubly Markov Number");
sc.close();
}
}
Variable Description
Variable Data Type Description
1. START
2. Input a number n.
3. Convert n into digits.
4. Assume two flags:
o inc = true if digits are increasing.
o dec = true if digits are decreasing.
5. Traverse the digits from left to right:
o If a digit is greater than the next, set inc = false.
o If a digit is smaller than the next, set dec = false.
6. After traversal:
o If both inc and dec are false → Bouncy Number.
o Else → Not a Bouncy Number.
7. END
Java Program
import java.util.Scanner;
if (isBouncy(num))
System.out.println(num + " is a Bouncy Number");
else
System.out.println(num + " is NOT a Bouncy Number");
sc.close();
}
}
Variable Description
Variable Data Type Description
1. START
2. Input number n.
3. If number has fewer than 3 digits → Not a Fascinating Number.
4. Compute:
on2 = n * 2
on3 = n * 3
5. Concatenate → concat = n + n2 + n3.
6. Check if concat contains all digits 1–9 exactly once.
7. If yes → Fascinating Number.
Else → Not Fascinating.
8. END
🔹 Java Program
import java.util.Scanner;
int n2 = n * 2;
int n3 = n * 3;
// Also check that digits are unique (no repeats for 1–9)
for (int i = 0; i < concat.length(); i++) {
char c = concat.charAt(i);
if (c >= '1' && c <= '9') {
if (concat.indexOf(c) != concat.lastIndexOf(c))
return false;
}
}
return true;
}
sc.close();
}
}
Variable Description
Variable Data Type Description
1. START
2. Input size of matrix (m, n) and matrix elements.
3. Extract all non-boundary elements into a list.
4. Sort the list.
5. Replace sorted elements back into their non-boundary positions.
6. Display final matrix.
7. END
Java Program
import java.util.*;
// Input dimensions
System.out.print("Enter rows: ");
int m = sc.nextInt();
System.out.print("Enter columns: ");
int n = sc.nextInt();
// Input matrix
System.out.println("Enter matrix elements:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = sc.nextInt();
}
}
sc.close();
}
}
Variable Description
Variable Data Type Description
Program (Java)
import java.util.*;
// Input sentences
System.out.println("Enter first sentence: ");
String s1 = sc.nextLine();
System.out.println("Enter second sentence: ");
String s2 = sc.nextLine();
// Compare words
for (String w1 : words1) {
for (String w2 : words2) {
if (w1.equalsIgnoreCase(w2)) {
common.add(w1.toLowerCase());
}
}
}
// Display results
if (common.isEmpty()) {
System.out.println("No common words found.");
} else {
System.out.println("Common words: " + common);
}
}
}
Variable Description
Variable Name Data Type Description (Purpose)
sc Scanner To take input from user
s1 String Stores the first sentence
s2 String Stores the second sentence
words1 String[] Stores words of the first sentence
words2 String[] Stores words of the second sentence
common HashSet<String> Stores unique common words between both sentences
w1, w2 String Temporary variables used in comparison
Algorithm
1. START
2. Input the upper limit n.
3. For each number p from 2 to n:
o Check if (p, p+2, p+6) are all prime → print triplet.
o Else check if (p, p+4, p+6) are all prime → print triplet.
4. Repeat until all numbers up to n are checked.
5. END
Program (Java)
import java.util.*;
Program (Java)
import java.util.*;
// Input matrix
System.out.println("Enter matrix elements:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = sc.nextInt();
}
}
Variable Description
Variable Name Data Type Description
sc Scanner For taking input
m int Number of rows
n int Number of columns
matrix int[][] 2D array to store the matrix
i, j int Loop counters for rows and columns
temp int Temporary variable to store last element of row before shifting
Algorithm
1. START
2. Input the sentence.
3. Convert the sentence to lowercase (for case-insensitivity).
4. Create a boolean array present[26] initialized as false.
5. Traverse each character ch in the sentence:
o If ch is a letter (a–z), mark present[ch - 'a'] = true.
6. After traversal, check if all 26 positions in present[] are true.
o If yes → the sentence is a pangram.
o Otherwise → it is not a pangram.
7. Print the result.
8. END
Program (Java)
import java.util.*;
// Input sentence
System.out.println("Enter a sentence:");
String sentence = sc.nextLine().toLowerCase();
// Output
if (isPangram) {
System.out.println("The sentence is a Pangram.");
} else {
System.out.println("The sentence is NOT a Pangram.");
}
}
}
Variable Description
Variable Name Data Type Description
sc Scanner To take input sentence
sentence String Stores the input sentence (converted to lowercase)
present boolean[] Array of size 26, tracks whether each alphabet letter is present
i int Loop counter for traversing the sentence
ch char Current character being checked
isPangram boolean Stores final result (true if pangram, false otherwise)
Algorithm
1. START
2. Input the sentence.
3. Input the word to delete.
4. Split the sentence into words using space " " as the delimiter.
5. Traverse each word:
o If it is not equal to the word to delete, keep it in the result.
o Otherwise, skip it.
6. Join the remaining words back into a sentence.
7. Print the new sentence.
8. END
Program (Java)
import java.util.*;
// Input sentence
System.out.println("Enter a sentence:");
String sentence = sc.nextLine();
Program (Java)
import java.util.*;
// Input sentence
System.out.println("Enter a sentence:");
String sentence = sc.nextLine();
// Input position
System.out.println("Enter the position (after which word to
insert):");
int pos = sc.nextInt();
Program (Java)
import java.util.*;
// Input sentence
System.out.println("Enter a sentence:");
String sentence = sc.nextLine();
if (!found) {
System.out.println("No word begins and ends with a vowel.");
}
}