Site icon JavaGoal

Java Programs for Practice: Know the Simple Java Programs for Beginners

Java is a widely-used programming language in the IT industry due to its simplicity, robustness, and code reusability. In this article, we’ll explore several important programs that can help us better understand the fundamentals of Java. You can read java basic first. Here we will see Java Programs for Practice: Know the Simple Java Programs for Beginners.

Java Programs for Practice: Know the Simple Java Programs for Beginners

  1. Simple calculator program in java
  2. Program to find factorial of a number
  3. Calculate Fibonacci Series up to n numbers
  4. String palindrome program in java
  5. Calculate the Permutation and Combination of 2 numbers
  6. Print Alphabet and Diamond Patterns
  7. Java reverse string program
  8. Check whether the given array is Mirror Inverse or not?
  9. Swap two numbers in java
  10. Swapping of two numbers without using third variable in java

1. Write a Java program to perform basic Calculator operations.

When we think of a calculator, we usually think of basic arithmetic operations like addition, subtraction, multiplication, and division. So, let’s create a program that implements these operations.

// Importing the Scanner class to take user input
import java.util.Scanner;  

public class Calculator {

    public static void main(String[] args) {

        // Creating a Scanner object to take user input
        Scanner input = new Scanner(System.in);

        // Declaring variables for the numbers and the result
        double num1, num2, result;  

        System.out.println("Enter the first number: ");
        // Taking the first number from the user
        num1 = input.nextDouble();  

        System.out.println("Enter the second number: ");
        // Taking the second number from the user
        num2 = input.nextDouble();  

        System.out.println("Select an operation (+, -, *, /): ");
        // Taking the operation from the user
        char operator = input.next().charAt(0);

        // Using a switch statement to perform the selected operation
        switch(operator) {  

            case '+':
                result = num1 + num2;
                System.out.println(num1 + " + " + num2 + " = " + result);
                break;

            case '-':
                result = num1 - num2;
                System.out.println(num1 + " - " + num2 + " = " + result);
                break;

            case '*':
                result = num1 * num2;
                System.out.println(num1 + " * " + num2 + " = " + result);
                break;

            case '/':
                if(num2 == 0) {  // Checking for division by zero
                    System.out.println("Error: division by zero");
                }
                else {
                    result = num1 / num2;
                    System.out.println(num1 + " / " + num2 + " = " + result);
                }
                break;

            default:
                System.out.println("Error: invalid operator");
                break;
        }

        // Closing the Scanner object to avoid resource leak
        input.close();  
    }
}

Enter the first number: 8
Enter the second number: 4
Select an operation (+, -, *, /): *
8.0 * 4.0 = 32.0

2. Write a Java program to calculate a Factorial of a number.

To find the factorial of a number, we multiply all the positive integers less than or equal to that number. This is denoted by n! Using recursion, we can write a program that repeatedly calls a function until it reaches the base case, and then returns the result.

import java.util.Scanner;  // Importing the Scanner class to take user input

public class Factorial {
  
  public static void main(String[] args) {
    
    Scanner input = new Scanner(System.in);  // Creating a Scanner object to take user input
    
    System.out.print("Enter a non-negative integer: ");
    int n = input.nextInt();  // Taking the number from the user
    
    int factorial = 1;  // Initializing the factorial to 1
    
    if(n < 0) {  // Checking for negative input
      System.out.println("Error: cannot calculate factorial of a negative number");
    }
    else if(n == 0) {  // Special case for 0
      System.out.println("Factorial of 0 is 1");
    }
    else {  // Calculating factorial for positive input
      for(int i = 1; i <= n; i++) {
        factorial *= i;
      }
      System.out.println("Factorial of " + n + " is " + factorial);
    }
    
    input.close();  // Closing the Scanner object to avoid resource leak
  }
}

Output: Enter a non-negative integer: 5
Factorial of 5 is 120

3. Write a Java program to calculate Fibonacci Series up to n numbers.

The Fibonacci series is a sequence of numbers in which each term is the sum of the two preceding terms. For instance, the series begins with 0 and 1, and the following term is the sum of those two, which is 1. The next term is the sum of the second and third terms, which is 2, and so on. To calculate the Fibonacci series in Java, we can use either a loop or recursion.

// Importing the Scanner class to take user input
import java.util.Scanner;

public class FibonacciSeries {

    public static void main(String[] args) {

        // Creating a Scanner object to take user input
        Scanner input = new Scanner(System.in);

        // Taking the number of terms from the user
        System.out.print("Enter the number of terms: ");
        int n = input.nextInt();

        // Initializing the first two numbers of the series
        int num1 = 0, num2 = 1, num3;

        // Printing the first two numbers of the series
        System.out.print("Fibonacci Series up to " + n + " terms: ");
        System.out.print(num1 + " " + num2 + " ");

        for(int i = 2; i < n; i++) {
            // Adding the previous two numbers to get the next number
            num3 = num1 + num2;
            // Printing the next number of the series
            System.out.print(num3 + " ");
            // Updating the values for the next iteration
            num1 = num2;
            num2 = num3;
        }

        // Closing the Scanner object to avoid resource leak
        input.close();
    }
}

Output: Enter the number of terms: 10
Fibonacci Series up to 10 terms: 0 1 1 2 3 5 8 13 21 34

4. Write a Java program to find out whether the given String is Palindrome or not. 

A palindrome is a type of sequence, such as a number or string, that remains the same even when its order is reversed. For instance, the word “ULLU” is a palindrome because it is spelled the same way both forward and backward.

// Importing the Scanner class to take user input
import java.util.Scanner;

public class Palindrome {

    public static void main(String[] args) {
        // Creating a Scanner object to take user input
        Scanner input = new Scanner(System.in);

        // Taking the input string from the user
        System.out.print("Enter a string: ");
        String str = input.nextLine();

        // Initializing an empty string to store the reversed string
        String reverse = "";

        // Adding each character of the original string in reverse order to the new string
        for(int i = str.length() - 1; i >= 0; i--) {
            reverse += str.charAt(i);
        }

        // Comparing the original and reversed strings
        if(str.equals(reverse)) {
            // If they're equal, the string is a palindrome
            System.out.println(str + " is a palindrome.");
        } else {
            // If they're not equal, the string is not a palindrome
            System.out.println(str + " is not a palindrome.");
        }
        // Closing the Scanner object to avoid resource leak
        input.close();
    }
}

Output: Enter a string: JavaGoal
JavaGoal is not a palindrome.

Enter a string: ULLU
ULLU is a palindrome.

5. Write a Java program to calculate the Permutation and Combination of 2 numbers.

Permutation refers to the various ways in which a specified number of elements can be arranged, taken individually, in groups, or all at once. Let’s take a closer look at how to implement it in Java.

// Importing the Scanner class to take user input
import java.util.Scanner;

public class PermutationCombination {

    // Define a method to calculate the factorial of a number
    public static int factorial(int n) {
        int fact = 1;
        for(int i = 1; i <= n; i++) {
            // Multiply each integer between 1 and n to calculate the factorial
            fact *= i;
        }
        return fact;
    }

    public static void main(String[] args) {

        // Creating a Scanner object to take user input
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the value of n: ");
        // Taking the value of n from the user
        int n = input.nextInt();

        System.out.print("Enter the value of r: ");
        // Taking the value of r from the user
        int r = input.nextInt();

        // Calculate the permutation and combination using the formula nPr = n! / (n-r)! and nCr = n! / (r!*(n-r)!)
        int nPr = factorial(n) / factorial(n - r);
        int nCr = factorial(n) / (factorial(r) * factorial(n - r));

        System.out.println("Permutation of " + n + " and " + r + " is: " + nPr);
        System.out.println("Combination of " + n + " and " + r + " is: " + nCr);

        input.close();  // Closing the Scanner object to avoid resource leak
    }
}

Output: Enter the value of n: 5
Enter the value of r: 3
Permutation of 5 and 3 is: 60
Combination of 5 and 3 is: 10

6. Write a program in Java to find out Alphabet and Diamond Patterns.

public class AlphabetAndDiamondPattern {

    public static void main(String[] args) {

        // print alphabet pattern
        int n = 5; // number of rows in pattern
        char c = 'A'; // starting character
        for (int i = 1; i <= n; i++) { // loop through each row
            for (int j = 1; j <= i; j++) { // loop through each character in row
                System.out.print(c + " "); // print character
                c++; // increment character
            }
            System.out.println(); // move to next line
        }

        // print diamond pattern
        int size = 5; // size of diamond
        for (int i = 1; i <= size; i++) { // loop through each row
            for (int j = size; j > i; j--) { // print spaces before asterisks
                System.out.print(" ");
            }
            for (int k = 1; k <= i; k++) { // print asterisks
                System.out.print("* ");
            }
            System.out.println(); // move to next line
        }
        for (int i = size - 1; i >= 1; i--) { // loop through each row
            for (int j = size; j > i; j--) { // print spaces before asterisks
                System.out.print(" ");
            }
            for (int k = 1; k <= i; k++) { // print asterisks
                System.out.print("* ");
            }
            System.out.println(); // move to next line
        }
    }

}

7. Write a Java Program to reverse the letters present in the given String.

This Java program enables a user to enter a string, which is then reversed by reversing the order of its letters. For example, if the user enters “Hello People”, the program will output “olleH elpoeP”. The program is implemented in Java.

import java.util.Scanner;

public class ReverseString {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        // Read input string from user
        String inputString = sc.nextLine();

        // Call reverseString function
        String reversedString = reverseString(inputString);
        System.out.println("Reversed string: " + reversedString);
    }

    // Function to reverse a given string
    public static String reverseString(String inputString) {
        String reversedString = "";

        // Traverse the input string from right to left and add each character to the reversed string
        for (int i = inputString.length() - 1; i >= 0; i--) {
            reversedString += inputString.charAt(i);
        }

        return reversedString;
    }
}

Output: Enter a string: JavaGoal.com
Reversed string: moc.laoGavaJ

8. Write a Java Program to check whether the given array is Mirror Inverse or not.

We can determine if an array is a mirror-inverse by checking if its inverse is equal to itself. Let’s write a Java program to check whether a given array is mirror-inverse or not.

import java.util.Scanner;

public class MirrorInverseArray {

    public static void main(String[] args) {

        // get the input array from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the length of the array: ");
        int n = scanner.nextInt();
        int[] arr = new int[n];
        System.out.println("Enter the array elements: ");
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        }

        // check if the array is mirror inverse
        boolean isMirrorInverse = true;
        for (int i = 0; i < n; i++) {
            if (arr[arr[i]] != i) {
                isMirrorInverse = false;
                break;
            }
        }

        // display the result
        if (isMirrorInverse) {
            System.out.println("The given array is mirror inverse.");
        } else {
            System.out.println("The given array is not mirror inverse.");
        }
    }
}

Output: Enter the length of the array: 5
Enter the array elements:
3 4 2 0 1
The given array is mirror inverse.

9. Write a program to swap two numbers by using the third number in Java

Swapping two numbers using a third variable is a commonly used technique in programming. The idea behind this technique is to use a temporary variable to store the value of one of the variables while the other variable is being swapped with it. This ensures that both variables end up with each other’s values after the swap.

public class SwapNumbers {
    public static void main(String[] args) {
        int a = 5, b = 10;

        System.out.println("Before swapping: a = " + a + ", b = " + b);

        // Swap logic using temporary variable
        int temp = a;
        a = b;
        b = temp;

        System.out.println("After swapping: a = " + a + ", b = " + b);
    }
}

Output: Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5

10. Write a program to swap two numbers without using the third number in Java

Swapping two numbers without using a third variable is a common programming task that can be accomplished using various techniques. Let’s try one

public class SwapNumbers {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 20;

        System.out.println("Before swap:");
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);

        // swapping the numbers without using a third variable

        // add the values of num1 and num2 and store the result in num1
        num1 = num1 + num2;
        // subtract the value of num2 from the updated value of num1 and store the result in num2
        num2 = num1 - num2;
        // subtract the updated value of num2 from the updated value of num1 and store the result in num1
        num1 = num1 - num2;

        System.out.println("After swap:");
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
    }
}

Output: Before swap:
num1 = 10
num2 = 20
After swap:
num1 = 20
num2 = 10

Exit mobile version