Frequently Asked Basics Java Programs
Check if a Number is Even or Odd? #
Explanation:
A number is classified as even or odd based on its divisibility by 2:
1. Even Number:
- A number is even if it is divisible by 2 without leaving a remainder.
- Examples: 2, 4, 6, 8, 10, etc.
- Even numbers always end with 0, 2, 4, 6, or 8.
2. Odd Number:
- A number is odd if it is not divisible by 2, meaning it leaves a remainder of 1 when divided by 2.
- Examples: 1, 3, 5, 7, 9, etc.
- Odd numbers always end with 1, 3, 5, 7, or 9.
In simple terms:
- If a number can be split into two equal whole numbers, it’s even.
- If it cannot, it’s odd.
Program:
import java.util.Scanner;
public class EvenOddChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
scanner.close();
}
}
// Output
Enter a number: 7
7 is odd.
Enter a number: 12
12 is even.
Find the Factorial of a Number #
Explanation:
The factorial of a number is the product of all positive integers from 1 to that number. It is denoted by the symbol “!”.
For example:
- 5! = 5 × 4 × 3 × 2 × 1 = 120
- 3! = 3 × 2 × 1 = 6
Key points:
- The factorial of 0 is defined as 1 (0! = 1).
- Factorials grow very quickly as the number increases.
Program:
import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println("Factorial of " + number + " is: " + factorial);
scanner.close();
}
}
// Output
Enter a number: 5
Factorial of 5 is: 120
Enter a number: 0
Factorial of 0 is: 1
Find the Fibonacci Series #
Explanation :
The Fibonacci Series is a sequence of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. The sequence looks like this:
Example :
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
The first two numbers are fixed: 0 and 1.
Every subsequent number is calculated by adding the two numbers before it.
For example:
- 0 + 1 = 1
- 1 + 1 = 2
- 1 + 2 = 3
- 2 + 3 = 5
- And so on.
This series is widely used in mathematics, computer science, and even nature (e.g., patterns in flower petals, pinecones, etc.).
Program:
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int n = scanner.nextInt();
int firstTerm = 0, secondTerm = 1;
System.out.println("Fibonacci Series:");
for (int i = 1; i <= n; i++) {
System.out.print(firstTerm + " ");
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
scanner.close();
}
}
// Output:
Enter the number of terms: 5
Fibonacci Series:
0 1 1 2 3
Enter the number of terms: 10
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34
Check if a Number is Prime #
Explanation:
A prime number is a number greater than 1 that has no positive divisors other than 1 and itself. In other words, it cannot be formed by multiplying two smaller natural numbers.
Key Points:
- Prime Numbers: 2, 3, 5, 7, 11, 13, etc.
- Non-Prime Numbers (Composite): 4, 6, 8, 9, 10, etc.
- Special Case: The number 1 is neither prime nor composite.
How to Check:
A number is prime if it is not divisible by any number other than 1 and itself.
For example:
- 7 is prime because it is only divisible by 1 and 7.
- 9 is not prime because it is divisible by 1, 3, and 9.
Program:
import java.util.Scanner;
public class PrimeNumberChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
boolean isPrime = true;
if (number <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
scanner.close();
}
}
// Output
Enter a number: 7
7 is a prime number.
Enter a number: 10
10 is not a prime number.
Enter a number: 1
1 is not a prime number.
This series is widely used in mathematics, computer science, and even nature (e.g., patterns in flower petals, pinecones, etc.).
Reverse a Number #
Explanation:
Reversing a number means rearranging its digits in the opposite order. For example:
- Original number: 1234
- Reversed number: 4321
Program:
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int reversedNumber = 0;
while (number != 0) {
int digit = number % 10; // Extract the last digit
reversedNumber = reversedNumber * 10 + digit; // Append the digit to the reversed number
number = number / 10; // Remove the last digit
}
System.out.println("Reversed number: " + reversedNumber);
scanner.close();
}
}
// Output
Enter a number: 1234
Reversed number: 4321
Enter a number: 56789
Reversed number: 98765
Check if a Number is Palindrome #
Explanation:
A palindrome number is a number that remains the same when its digits are reversed. For example:
- 121 is a palindrome because reversing it gives 121.
- 123 is not a palindrome because reversing it gives 321.
Program:
import java.util.Scanner;
public class PalindromeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int originalNumber = number;
int reversedNumber = 0;
while (number != 0) {
int digit = number % 10; // Extract the last digit
reversedNumber = reversedNumber * 10 + digit; // Append the digit to the reversed number
number = number / 10; // Remove the last digit
}
if (originalNumber == reversedNumber) {
System.out.println(originalNumber + " is a palindrome.");
} else {
System.out.println(originalNumber + " is not a palindrome.");
}
scanner.close();
}
}
// Output
Enter a number: 121
121 is a palindrome.
Enter a number: 123
123 is not a palindrome.
Enter a number: 1221
1221 is a palindrome.
Check if a Number is Armstrong #
Explanation:
An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example:
Vinoth: Below code is an image: Insert this example as image
Program:
import java.util.Scanner;
public class ArmstrongNumberChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int originalNumber = number;
int sum = 0;
int digits = String.valueOf(number).length(); // Count the number of digits
while (number != 0) {
int digit = number % 10; // Extract the last digit
sum += Math.pow(digit, digits); // Add the digit raised to the power of digits
number = number / 10; // Remove the last digit
}
if (originalNumber == sum) {
System.out.println(originalNumber + " is an Armstrong number.");
} else {
System.out.println(originalNumber + " is not an Armstrong number.");
}
scanner.close();
}
}
// Output
Enter a number: 153
153 is an Armstrong number.
Enter a number: 370
370 is an Armstrong number.
Enter a number: 123
123 is not an Armstrong number.
Calculate GCD and LCM of Two Numbers #
Explanation:
1. GCD (Greatest Common Divisor):
- The largest positive integer that divides both numbers without leaving a remainder.
- Example: GCD of 12 and 18 is 6.
2. LCM (Least Common Multiple):
- The smallest positive integer that is a multiple of both numbers.
- Example: LCM of 12 and 18 is 36.
Program:
import java.util.Scanner;
public class GCDandLCM {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
int gcd = calculateGCD(num1, num2);
int lcm = (num1 * num2) / gcd; // Using the relationship between GCD and LCM
System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd);
System.out.println("LCM of " + num1 + " and " + num2 + " is: " + lcm);
scanner.close();
}
// Function to calculate GCD using Euclidean Algorithm
public static int calculateGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
// Output:
Enter the first number: 12
Enter the second number: 18
GCD of 12 and 18 is: 6
LCM of 12 and 18 is: 36
Enter the first number: 20
Enter the second number: 25
GCD of 20 and 25 is: 5
LCM of 20 and 25 is: 100
Swap two numbers using a temporary variable #
Program:
public class SwapNumbers {
public static void main(String[] args) {
int a = 5;
int b = 10;
System.out.println("Before swapping: a = " + a + ", b = " + b);
// Swapping using a temporary variable
int temp = a; // Store the value of a in temp
a = b; // Assign the value of b to a
b = temp; // Assign the original value of a (stored in temp) to b
System.out.println("After swapping: a = " + a + ", b = " + b);
}
}
Swapping Two Numbers without a Third Variable #
Explanation:
Swapping two numbers means exchanging their values. For example:
- Before swapping: a = 5, b = 10
- After swapping: a = 10, b = 5
Program:
import java.util.Scanner;
public class SwapNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number (a): ");
int a = scanner.nextInt();
System.out.print("Enter the second number (b): ");
int b = scanner.nextInt();
System.out.println("Before swapping: a = " + a + ", b = " + b);
// Swapping logic without a third variable
a = a + b; // Step 1: a now holds the sum of a and b
b = a - b; // Step 2: b now holds the original value of a
a = a - b; // Step 3: a now holds the original value of b
System.out.println("After swapping: a = " + a + ", b = " + b);
scanner.close();
}
}
// Output:
Enter the first number (a): 5
Enter the second number (b): 10
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5
Alternative Way
a = a ^ b; // Step 1: a now holds the XOR of a and b
b = a ^ b; // Step 2: b now holds the original value of a
a = a ^ b; // Step 3: a now holds the original value of b
Note: This method is also efficient and avoids arithmetic overflow issue
Find the sum of digits of a number #
Explanation:
The sum of digits of a number refers to the total obtained by adding up each individual digit in the number. It is a basic mathematical operation that breaks down a number into its constituent digits and sums them together.
Example:
Consider the number 1234.
- The digits are: 1, 2, 3, and 4.
- The sum of the digits is: 1 + 2 + 3 + 4 = 10.
Program:
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Get the number from the user
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Initialize sum to 0
int sum = 0;
// Process: Calculate the sum of digits
int temp = number; // Temporary variable to hold the number
while (temp != 0) {
int digit = temp % 10; // Extract the last digit
sum += digit; // Add the digit to the sum
temp = temp / 10; // Remove the last digit
}
// Output: Display the sum of digits
System.out.println("Sum of digits of " + number + " is: " + sum);
scanner.close();
}
}
// output
Enter a number: 1234
Sum of digits of 1234 is: 10
Find the sum of digits of a number #
Explanation:
The largest of three numbers refers to the greatest value among three given numbers.
Example:
Consider the numbers 12, 25, and 8. Here the largest number is 25.
Program:
import java.util.Scanner;
public class LargestOfThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Get three numbers from the user
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter the third number: ");
int num3 = scanner.nextInt();
// Logic: Find the largest number
int largest;
if (num1 >= num2 && num1 >= num3) {
largest = num1; // num1 is the largest
} else if (num2 >= num1 && num2 >= num3) {
largest = num2; // num2 is the largest
} else {
largest = num3; // num3 is the largest
}
// Output: Display the largest number
System.out.println("The largest number is: " + largest);
scanner.close();
}
}
// Output
Enter the first number: 12
Enter the second number: 25
Enter the third number: 8
The largest number is: 25
Find the smallest of three numbers
Explanation:
The smallest of three numbers refers to the smallest value among three given numbers.
Example:
Consider the numbers 12, 25, and 8. Here the smallest number is 8.
Program:
import java.util.Scanner;
public class SmallestOfThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Get three numbers from the user
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter the third number: ");
int num3 = scanner.nextInt();
// Logic: Find the smallest number
int smallest;
if (num1 <= num2 && num1 <= num3) {
smallest = num1; // num1 is the smallest
} else if (num2 <= num1 && num2 <= num3) {
smallest = num2; // num2 is the smallest
} else {
smallest = num3; // num3 is the smallest
}
// Output: Display the smallest number
System.out.println("The smallest number is: " + smallest);
scanner.close();
}
}
// Output
Enter the first number: 12
Enter the second number: 25
Enter the third number: 8
The smallest number is: 8
Find the sum of digits of a number #
Explanation:
The largest of three numbers refers to the greatest value among three given numbers.
Example:
Consider the numbers 12, 25, and 8. Here the largest number is 25.
Program:
import java.util.Scanner;
public class LargestOfThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Get three numbers from the user
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter the third number: ");
int num3 = scanner.nextInt();
// Logic: Find the largest number
int largest;
if (num1 >= num2 && num1 >= num3) {
largest = num1; // num1 is the largest
} else if (num2 >= num1 && num2 >= num3) {
largest = num2; // num2 is the largest
} else {
largest = num3; // num3 is the largest
}
// Output: Display the largest number
System.out.println("The largest number is: " + largest);
scanner.close();
}
}
// Output
Enter the first number: 12
Enter the second number: 25
Enter the third number: 8
The largest number is: 25
Find the smallest of three numbers
Explanation:
The smallest of three numbers refers to the smallest value among three given numbers.
Example:
Consider the numbers 12, 25, and 8. Here the smallest number is 8.
Program:
import java.util.Scanner;
public class SmallestOfThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Get three numbers from the user
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter the third number: ");
int num3 = scanner.nextInt();
// Logic: Find the smallest number
int smallest;
if (num1 <= num2 && num1 <= num3) {
smallest = num1; // num1 is the smallest
} else if (num2 <= num1 && num2 <= num3) {
smallest = num2; // num2 is the smallest
} else {
smallest = num3; // num3 is the smallest
}
// Output: Display the smallest number
System.out.println("The smallest number is: " + smallest);
scanner.close();
}
}
// Output
Enter the first number: 12
Enter the second number: 25
Enter the third number: 8
The smallest number is: 8
Check if a number is a perfect number #
Explanation:
A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). In other words, if you add up all the numbers that divide the number evenly (except the number itself), the sum should be equal to the number.
Example:
- 6 is a perfect number because its proper divisors are 1, 2, and 3, and 1 + 2 + 3 = 6.
- 28 is also a perfect number because its proper divisors are 1, 2, 4, 7, and 14, and 1 + 2 + 4 + 7 + 14 = 28.
Program:
import java.util.Scanner;
public class PerfectNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Get the number from the user
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Logic: Check if the number is perfect
int sum = 0;
for (int i = 1; i < number; i++) {
if (number % i == 0) {
sum += i; // Add proper divisors to the sum
}
}
// Output: Display the result
if (sum == number) {
System.out.println(number + " is a perfect number.");
} else {
System.out.println(number + " is not a perfect number.");
}
scanner.close();
}
}
// Output
Enter a number: 28
28 is a perfect number.
Enter a number: 12
12 is not a perfect number.
Find the square root of a number #
Explanation:
Square Root of a Number
The square root of a number is a value that, when multiplied by itself, gives the original number. It is denoted by the symbol √.
Example:
- The square root of 25 is 5 because 5 × 5 = 25.
- The square root of 9 is 3 because 3 × 3 = 9.
Program:
import java.util.Scanner;
public class SquareRoot {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Get the number from the user
System.out.print("Enter a number: ");
double number = scanner.nextDouble();
// Logic: Calculate the square root
double squareRoot = Math.sqrt(number);
// Output: Display the square root
System.out.println("The square root of " + number + " is: " + squareRoot);
scanner.close();
}
}
// Output
Enter a number: 25
The square root of 25.0 is: 5.0