15 Basic Java Programs: Building Foundation

In this article, we will explore a collection of basic Java programs that serve as an excellent starting point for beginners. By grasping these fundamentals, aspiring programmers can lay a strong foundation for their Java journey.

Basic Java Programs

Swapping of Two Numbers

This is one of the very basic java programs, where we use a temporary variable to swap two numbers.

Java Code

public class NumberSwapper {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 20;
        System.out.println("Before swapping: num1 = " + num1 + ", num2 = " + num2);
        swapNumbers(num1, num2);
        System.out.println("After swapping: num1 = " + num1 + ", num2 = " + num2);
    }

    public static void swapNumbers(int a, int b) {
        int temp = a;
        a = b;
        b = temp;
    }
}

Output

Before swapping: num1 = 10, num2 = 20
After swapping: num1 = 10, num2 = 20

check whether a word is a palindrome or not

Java Code

public class PalindromeChecker {
    public static void main(String[] args) {
        String word = "radar";
        boolean isPalindrome = checkPalindrome(word);
        System.out.println("Is \"" + word + "\" a palindrome? " + isPalindrome);
    }

    public static boolean checkPalindrome(String word) {
        int length = word.length();
        for (int i = 0; i < length / 2; i++) {
            if (word.charAt(i) != word.charAt(length - i - 1)) {
                return false;
            }
        }
        return true;
    }
}

Output

Is "radar" a palindrome? true

Find Factorial(n!) of a given number(n)

Java Code

public class Factorial {
    public static void main(String[] args) {
        int number = 5;
        int factorial = calculateFactorial(number);
        System.out.println("Factorial of " + number + ": " + factorial);
    }

    public static int calculateFactorial(int number) {
        if (number == 0) {
            return 1;
        } else {
            return number * calculateFactorial(number - 1);
        }
    }
}

Output

Factorial of 5: 120

Find if the input number is Prime

Java Code

public class PrimeNumberChecker {
    public static void main(String[] args) {
        int number = 13;
        boolean isPrime = checkPrime(number);
        System.out.println(number + " is a prime number? " + isPrime);
    }

    public static boolean checkPrime(int number) {
        if (number <= 1) {
            return false;
        }

        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Output

13 is a prime number? true

Print Fibonacci Series

Java Code

public class FibonacciSeries {
    public static void main(String[] args) {
        int limit = 10;
        System.out.print("Fibonacci Series: ");

        int firstTerm = 0;
        int secondTerm = 1;
        System.out.print(firstTerm + ", " + secondTerm);

        for (int i = 2; i < limit; i++) {
            int nextTerm = firstTerm + secondTerm;
            System.out.print(", " + nextTerm);
            firstTerm = secondTerm;
            secondTerm = nextTerm;
        }
    }
}

Output

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Check this Generate Fibonacci Series in Java: Top 4 different ways

Checking Armstrong Number

Java Code

public class ArmstrongNumberChecker {
    public static void main(String[] args) {
        int number = 153;
        boolean isArmstrong = checkArmstrong(number);
        System.out.println(number + " is an Armstrong number? " + isArmstrong);
    }

    public static boolean checkArmstrong(int number) {
        int originalNumber = number;
        int result = 0;

        while (number != 0) {
            int remainder = number % 10;
            result += Math.pow(remainder, 3);
            number /= 10;
        }

        return result == originalNumber;
    }
}

Output

153 is an Armstrong number? true

Check this Armstrong Number in Java: Top 4 Simple ways

Find largest Number in an Array

Java Code

public class LargestNumber {
    public static void main(String[] args) {
        int[] numbers = {10, 5, 20, 8, 15};
        int largestNumber = findLargestNumber(numbers);
        System.out.println("Largest number: " + largestNumber);
    }

    public static int findLargestNumber(int[] numbers) {
        int max = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > max) {
                max = numbers[i];
            }
        }
        return max;
    }
}

Output

Largest number: 20

Find Smallest Number in an Array

Java Code

public class SmallestNumber {
    public static void main(String[] args) {
        int[] numbers = {10, 5, 20, 8, 15};
        int smallestNumber = findSmallestNumber(numbers);
        System.out.println("Smallest number: " + smallestNumber);
    }

    public static int findSmallestNumber(int[] numbers) {
        int min = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] < min) {
                min = numbers[i];
            }
        }
        return min;
    }
}

Output

Smallest number: 5

Check if two Strings are Anagram

Java Code

public class AnagramChecker {
    public static void main(String[] args) {
        String str1 = "listen";
        String str2 = "silent";
        boolean isAnagram = checkAnagram(str1, str2);
        System.out.println(str1 + " and " + str2 + " are anagrams? " + isAnagram);
    }

    public static boolean checkAnagram(String str1, String str2) {
        if (str1.length() != str2.length()) {
            return false;
        }

        int[] count = new int[26];

        for (int i = 0; i < str1.length(); i++) {
            count[str1.charAt(i) - 'a']++;
            count[str2.charAt(i) - 'a']--;
        }

        for (int c : count) {
            if (c != 0) {
                return false;
            }
        }
        return true;
    }
}

Output

listen and silent are anagrams? true

Find Unique Characters in the String

Java Code

public class UniqueCharacters {
    public static void main(String[] args) {
        String word = "hello";
        String uniqueChars = findUniqueCharacters(word);
        System.out.println("Unique characters: " + uniqueChars);
    }

    public static String findUniqueCharacters(String word) {
        StringBuilder unique = new StringBuilder();
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            if (unique.indexOf(String.valueOf(ch)) == -1) {
                unique.append(ch);
            }
        }
        return unique.toString();
    }
}

Output

Unique characters: helo

Find Duplicate Characters in a String

Java Code

public class DuplicateCharacters {
    public static void main(String[] args) {
        String word = "hello";
        String duplicateChars = findDuplicateCharacters(word);
        System.out.println("Duplicate characters: " + duplicateChars);
    }

    public static String findDuplicateCharacters(String word) {
        StringBuilder duplicates = new StringBuilder();
        StringBuilder allChars = new StringBuilder();

        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            if (allChars.indexOf(String.valueOf(ch)) == -1) {
                allChars.append(ch);
            } else if (duplicates.indexOf(String.valueOf(ch)) == -1) {
                duplicates.append(ch);
            }
        }
        return duplicates.toString();
    }
}

Output

Duplicate characters: l

Reverse a String in Java

Java Code

public class StringReverser {
    public static void main(String[] args) {
        String word = "hello";
        String reversed = reverseString(word);
        System.out.println("Reversed string: " + reversed);
    }

    public static String reverseString(String word) {
        StringBuilder reversed = new StringBuilder();
        for (int i = word.length() - 1; i >= 0; i--) {
            reversed.append(word.charAt(i));
        }
        return reversed.toString();
    }
}

Output

Reversed string: olleh

Generate Random Number in Java

Java Code

import java.util.Random;

public class RandomNumberGenerator {
    public static void main(String[] args) {
        int randomNum = generateRandomNumber();
        System.out.println("Random number: " + randomNum);
    }

    public static int generateRandomNumber() {
        Random random = new Random();
        return random.nextInt();
    }
}

Output

Random number: 1541134490

Find Number of Words Separated by Space in a String

Java Code

public class WordCount {
    public static void main(String[] args) {
        String sentence = "This is a sample sentence";
        int wordCount = countWords(sentence);
        System.out.println("Number of words: " + wordCount);
    }

    public static int countWords(String sentence) {
        String[] words = sentence.split(" ");
        return words.length;
    }
}

Output

Number of words: 5

Check Leap Year

Java Code

import java.util.Scanner;

public class LeapYearChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a year: ");
        int year = scanner.nextInt();
        scanner.close();

        if (isLeapYear(year)) {
            System.out.println(year + " is a leap year.");
        } else {
            System.out.println(year + " is not a leap year.");
        }
    }

    public static boolean isLeapYear(int year) {
        if (year % 4 == 0) {
            if (year % 100 == 0) {
                if (year % 400 == 0) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        } else {
            return false;
        }
    }
}

Output

Enter a year: 2010
2010 is not a leap year.

More Java Programs

For more basic and advanced Programs Check this Top Java Programs asked in Interviews

Conclusion: Basic Java Programs

In conclusion, this article has explored a collection of 15 basic Java programs that serve as building blocks for establishing a strong foundation in Java programming.Mastering these basic Java programs lays the groundwork for tackling more complex coding tasks and exploring advanced Java topics.

As beginners become more comfortable with these basic java programs, they can gradually explore more advanced Java concepts, algorithms, data structures, and frameworks.

Leave a Reply

Your email address will not be published. Required fields are marked *