Top 50 Java program examples that are commonly used and often asked in interviews. Each program is accompanied by a brief description
1. Hello World:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
```
2. Add Two Numbers:
public class AddTwoNumbers {
public static void main(String[] args) {
int num1 = 5, num2 = 10, sum;
sum = num1 + num2;
System.out.println("Sum: " + sum);
}
}
```
3. Check Prime Number:
public class PrimeNumber {
public static void main(String[] args) {
int num = 29;
boolean isPrime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
System.out.println(num + " is prime? " + isPrime);
}
}
```
4. Factorial Calculation:
public class Factorial {
public static void main(String[] args) {
int num = 5;
long factorial = 1;
for (int i = 1; i <= num; ++i) {
factorial *= i;
}
System.out.println("Factorial of " + num + " = " + factorial);
}
}
```
5. Fibonacci Series:
public class Fibonacci {
public static void main(String[] args) {
int n = 10, firstTerm = 0, secondTerm = 1;
System.out.println("Fibonacci Series up to " + n + " terms:");
for (int i = 1; i <= n; ++i) {
System.out.print(firstTerm + ", ");
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}
```
6. Reverse a String:
public class ReverseString {
public static void main(String[] args) {
String original = "Hello, World!";
StringBuilder reversed = new StringBuilder(original).reverse();
System.out.println("Reversed String: " + reversed);
}
}
```
7. Palindrome Check:
public class Palindrome {
public static void main(String[] args) {
String str = "madam";
String reversed = new StringBuilder(str).reverse().toString();
boolean isPalindrome = str.equals(reversed);
System.out.println(str + " is palindrome? " + isPalindrome);
}
}
```
8. Armstrong Number:
public class ArmstrongNumber {
public static void main(String[] args) {
int num = 153;
int original = num;
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += Math.pow(digit, 3);
num /= 10;
}
boolean isArmstrong = sum == original;
System.out.println(original + " is Armstrong? " + isArmstrong);
}
}
```
9. Swap Two Numbers:
public class SwapNumbers {
public static void main(String[] args) {
int a = 5, b = 10;
System.out.println("Before swap: a = " + a + ", b = " + b);
int temp = a;
a = b;
b = temp;
System.out.println("After swap: a = " + a + ", b = " + b);
}
}
```
10. Calculate Average:
public class CalculateAverage {
public static void main(String[] args) {
double[] numbers = { 5.5, 10.1, 11, 12.8, 56.9, 2.5 };
double sum = 0;
for (double num : numbers) {
sum += num;
}
double average = sum / numbers.length;
System.out.println("Average: " + average);
}
}
```
11. Linear Search in an Array:
public class LinearSearch {
public static void main(String[] args) {
int[] array = { 2, 5, 8, 12, 16, 23, 38, 42, 55, 72 };
int target = 16;
boolean found = false;
for (int element : array) {
if (element == target) {
found = true;
break;
}
}
System.out.println("Element " + target + " found? " + found);
}
}
```
12. Binary Search in an Array:
public class BinarySearch {
public static void main(String[] args) {
int[] array = { 2, 5, 8, 12, 16, 23, 38, 42, 55, 72 };
int target = 23;
int low = 0, high = array.length - 1;
boolean found = false;
while (low <= high) {
int mid = (low + high) / 2;
if (array[mid] == target) {
found = true;
break;
} else if (array[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
System.out.println("Element " + target + " found? " + found);
}
}
```
13. Bubble Sort:
public class BubbleSort {
public static void main(String[] args) {
int[] array = { 64, 34, 25, 12, 22, 11, 90 };
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
System.out.println("Sorted array: " + Arrays.toString(array));
}
}
```
14. Insertion Sort:
public class InsertionSort {
public static void main(String[] args) {
int[] array = { 64, 34, 25, 12, 22, 11, 90 };
int n = array.length;
for (int i = 1; i < n; ++i) {
int key = array[i];
int j = i - 1;
while (j >= 0 && array[j
] > key) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = key;
}
System.out.println("Sorted array: " + Arrays.toString(array));
}
}
```
15. Selection Sort:
public class SelectionSort {
public static void main(String[] args) {
int[] array = { 64, 34, 25, 12, 22, 11, 90 };
int n = array.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
System.out.println("Sorted array: " + Arrays.toString(array));
}
}
```
16. Calculate Factorial Using Recursion:
public class FactorialRecursion {
static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
int num = 5;
int result = factorial(num);
System.out.println("Factorial of " + num + " = " + result);
}
}
```
17. Generate Fibonacci Series Using Recursion:
public class FibonacciRecursion {
static int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
public static void main(String[] args) {
int n = 10;
System.out.println("Fibonacci Series up to " + n + " terms:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + ", ");
}
}
}
```
18. Calculate GCD (Greatest Common Divisor):
public class GCD {
static int findGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static void main(String[] args) {
int num1 = 48, num2 = 18;
System.out.println("GCD of " + num1 + " and " + num2 + " = " + findGCD(num1, num2));
}
}
```
19. Largest Element in an Array:
public class LargestElement {
public static void main(String[] args) {
int[] array = { 10, 4, 45, 23, 98, 50 };
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
System.out.println("Largest element in the array: " + max);
}
}
```
20. Smallest Element in an Array:
public class SmallestElement {
public static void main(String[] args) {
int[] array = { 34, 56, 12, 89, 7, 23 };
int min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
System.out.println("Smallest element in the array: " + min);
}
}
```
21. Calculate Power Using Recursion:
public class PowerRecursion {
static int power(int base, int exponent) {
if (exponent == 0) {
return 1;
} else {
return base * power(base, exponent - 1);
}
}
public static void main(String[] args) {
int base = 2, exponent = 3;
System.out.println(base + " raised to the power of " + exponent + " = " + power(base, exponent));
}
}
```
22. Check Leap Year:
public class LeapYear {
public static void main(String[] args) {
int year = 2024;
boolean isLeapYear = false;
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
isLeapYear = true;
}
System.out.println(year + " is a leap year? " + isLeapYear);
}
}
```
23. Print Pascal's Triangle:
public class PascalsTriangle {
static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
static int binomialCoefficient(int n, int r) {
return factorial(n) / (factorial(r) * factorial(n - r));
}
public static void main(String[] args) {
int rows = 5;
for (int i = 0; i < rows; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(binomialCoefficient(i, j) + " ");
}
System.out.println();
}
}
}
```
24. Count Words in a Sentence:
public class WordCount {
public static void main(String[] args) {
String sentence = "This is a sample sentence.";
String[] words = sentence.split(" ");
int wordCount = words.length;
System.out.println("Word count: " + wordCount);
}
}
```
25. Reverse a Number:
public class ReverseNumber {
public static void main(String[] args) {
int num = 12345;
int reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
System.out.println("Reversed number: " + reversed);
}
}
```
26. Check Armstrong Number for n Digits:
public class ArmstrongNumberNDigits {
public static void main(String[] args) {
int num = 1634;
int original = num;
int numDigits = (int) Math.log10(num) + 1;
int sum = 0;
while (num != 0) {
int digit = num % 10;
sum += Math
--------------------------------
27. ArrayList Example:
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
System.out.println("ArrayList Elements: " + colors);
}
}
28. HashMap Example:
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> studentMap = new HashMap<>();
studentMap.put(101, "John");
studentMap.put(102, "Alice");
studentMap.put(103, "Bob");
System.out.println("HashMap Elements: " + studentMap);
}
}
29. HashSet Example:
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> uniqueNames = new HashSet<>();
uniqueNames.add("John");
uniqueNames.add("Alice");
uniqueNames.add("Bob");
System.out.println("HashSet Elements: " + uniqueNames);
}
}
30. LinkedList Example:
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("LinkedList Elements: " + numbers);
}
}
--------------------------------31. TreeMap Example:
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<String, Integer> ageMap = new TreeMap<>();
ageMap.put("John", 25);
ageMap.put("Alice", 30);
ageMap.put("Bob", 28);
System.out.println("TreeMap Elements: " + ageMap);
}
}
32. Vector Example:
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
Vector<String> fruits = new Vector<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
System.out.println("Vector Elements: " + fruits);
}
}
33. Stack Example:
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("Java");
stack.push("Python");
stack.push("C++");
System.out.println("Stack Elements: " + stack);
}
}
34. PriorityQueue Example:
import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> numbers = new PriorityQueue<>();
numbers.add(3);
numbers.add(1);
numbers.add(2);
System.out.println("PriorityQueue Elements: " + numbers);
}
}
35 ArrayDeque Example:
import java.util.ArrayDeque;
public class ArrayDequeExample {
public static void main(String[] args) {
ArrayDeque<String> deque = new ArrayDeque<>();
deque.add("Front");
deque.add("Middle");
deque.add("Rear");
System.out.println("ArrayDeque Elements: " + deque);
}
}
36. LinkedHashSet Example:
import java.util.LinkedHashSet;
public class LinkedHashSetExample {
public static void main(String[] args) {
LinkedHashSet<String> uniqueWords = new LinkedHashSet<>();
uniqueWords.add("Apple");
uniqueWords.add("Banana");
uniqueWords.add("Orange");
System.out.println("LinkedHashSet Elements: " + uniqueWords);
}
}
0 Comments
Thank You for comment
if you have any queries then Contact us k2aindiajob@gmail.com