Mastering Core Java: Essential Programs for Beginners and Interview Prep

"Transform from a Java Novice to a Coding Hero: Mastering Essential Programs and Slaying Interviews with Confidence"

Mastering Core Java: Essential Programs for Beginners and Interview Prep

Are you ready to take your Java skills to the next level? If you're a beginner looking to become a coding hero, then "From Zero to Java Hero: Mastering Essential Programs and Crushing Interviews" is the perfect guide for you. This comprehensive article is designed to equip you with the essential programs With easy-to-follow instructions and expert advice, you'll learn how to write optimized code and solve real-world problems like a pro. So what are you waiting for? Unleash your inner Java hero and transform your coding journey today!

Java Program to Print Hello World

This Java program is designed to display the string "Hello World" on the screen. It is considered to be one of the most basic programs in the Java programming language and is often the first program that new programmers learn. The purpose of this program is to help them understand the fundamental syntax and structure of Java programs.

package com.pp.java.programs;

/**
 * Java Program to Print Hello World on Screen
 */
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

Output: Hello World

Explanation :

  1. The first line of the program specifies the package that the program belongs to. In this case, the package is "com.pp.java.programs". A package is a group of related classes that can be used together.

  2. The second line is a comment that explains what the program does. Comments are used to provide information about the program that is not executed.

  3. The third line defines a class called "HelloWorld". A class is a template for creating objects that share similar properties and behaviors.

  4. Inside the "HelloWorld" class, there is a "main" method. The "main" method is the entry point of the program. When the program is executed, the "main" method is the first method that is called.

  5. The "main" method takes an array of strings called "args" as a parameter. "args" is short for "arguments" and it allows the program to accept command-line arguments.

  6. Inside the "main" method, there is a single line of code that uses the "System.out.println" method to print the message "Hello World" on the screen.

  7. Finally, the program is terminated when the "main" method finishes executing.

Java Program to print Hello World string 10 times using for loop

// Define a class called HelloWorld
public class HelloWorld {

   // Define the main method that will be executed when the program runs
   public static void main(String[] args) {

      // Start a for loop that will run 10 times
      for(int i = 1; i <= 10; i++) {

         // Print the string "Hello World" to the console
         System.out.println("Hello World");
      }

   } // End of main method

} // End of HelloWorld class

Output:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

Java Program to Print an Integer (Entered by the User)

This program takes an integer input from the user and prints it on the console.

import java.util.Scanner;

public class PrintInteger {
    public static void main(String[] args) {
// create a Scanner object to read user input
        Scanner input = new Scanner(System.in); 
// prompt the user to enter an integer
        System.out.print("Enter an integer: "); 
// read the integer input from the user
        int num = input.nextInt(); 
// print the integer entered by the user
        System.out.println("You entered " + num); 
    }
}

Java Program to Add Two Integers

This program takes two integer inputs from the user and adds them together, then prints the sum on the console.

import java.util.Scanner;

public class AddIntegers {
    public static void main(String[] args) {
// create a Scanner object to read user input
        Scanner input = new Scanner(System.in); 
// prompt the user to enter the first integer
        System.out.print("Enter the first integer: "); 
/ read the first integer input from the user
        int num1 = input.nextInt(); /
// prompt the user to enter the second integer
        System.out.print("Enter the second integer: "); 
// read the second integer input from the user
        int num2 = input.nextInt(); 
// add the two integers
        int sum = num1 + num2; 
// print the sum of the two integers
        System.out.println("The sum is " + sum); /
    }
}

Java Program to Multiply two Floating Point Numbers

This program takes two floating point numbers as inputs from the user and multiplies them together, then prints the product on the console.

import java.util.Scanner;

public class MultiplyFloats {
    public static void main(String[] args) {
// create a Scanner object to read user input
        Scanner input = new Scanner(System.in); 
// prompt the user to enter the first floating point number
        System.out.print("Enter the first floating point number: "); 
// read the first floating point number input from the user
        float num1 = input.nextFloat(); 
// prompt the user to enter the second floating point number
        System.out.print("Enter the second floating point number: "); 
// read the second floating point number input from the user
        float num2 = input.nextFloat(); 
// multiply the two floating point numbers
        float product = num1 * num2; 
// print the product of the two floating point numbers
        System.out.println("The product is " + product); 
    }
}

Java Program to Find ASCII Value of a character

This program takes a character input from the user and finds its ASCII value, then prints it on the console.

import java.util.Scanner;

public class ASCIIValue {
    public static void main(String[] args) {
// create a Scanner object to read user input
        Scanner input = new Scanner(System.in); 
// prompt the user to enter a character
        System.out.print("Enter a character: "); 
// read the character input from the user
        char ch = input.next().charAt(0); 
// convert the character to its ASCII value
        int asciiValue = (int) ch; 
// print the ASCII value of the character
        System.out.println("The ASCII value of " + ch + " is " + asciiValue); 
    }
}

Java Program to Compute Quotient and Remainder

import java.util.Scanner; // Import Scanner class

public class QuotientRemainder {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in); // Create Scanner object

        System.out.print("Enter dividend: ");
        int dividend = input.nextInt(); // Read user input for dividend

        System.out.print("Enter divisor: ");
        int divisor = input.nextInt(); // Read user input for divisor

        int quotient = dividend / divisor; // Calculate quotient
        int remainder = dividend % divisor; // Calculate remainder

        System.out.println("Quotient = " + quotient); // Display quotient
        System.out.println("Remainder = " + remainder); // Display remainder
    }
}

Explanation:

  1. We first import the Scanner class, which allows us to read user input from the console.

  2. We declare a class called QuotientRemainder which contains a main method.

  3. Inside the main method, we create a Scanner object called input.

  4. We then prompt the user to enter the dividend and divisor, using the print method to display the message and the nextInt method to read the integer input.

  5. We then calculate the quotient and remainder using the / and % operators, respectively.

  6. Finally, we use the println method to display the quotient and remainder to the console.

Note that this program assumes that the user will enter valid integer inputs for the dividend and divisor. If you want to add input validation, you can use the hasNextInt method of the Scanner class to check if the input is an integer before calling nextInt.

Java Program to Swap Two Numbers Using temp Variable

import java.util.Scanner; // Import Scanner class

public class SwapNumbers {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in); // Create Scanner object

        System.out.print("Enter first number: ");
        int num1 = input.nextInt(); // Read user input for first number

        System.out.print("Enter second number: ");
        int num2 = input.nextInt(); // Read user input for second number

        System.out.println("Before swapping:");
        System.out.println("First number = " + num1);
        System.out.println("Second number = " + num2);

        // Swap numbers using a temporary variable
        int temp = num1;
        num1 = num2;
        num2 = temp;

        System.out.println("After swapping:");
        System.out.println("First number = " + num1);
        System.out.println("Second number = " + num2);
    }
}

Explanation:

  1. We first import the Scanner class, which allows us to read user input from the console.

  2. We declare a class called SwapNumbers which contains a main method.

  3. Inside the main method, we create a Scanner object called input.

  4. We then prompt the user to enter the first and second numbers, using the print method to display the message and the nextInt method to read the integer input.

  5. We then display the original values of the two numbers using the println method.

  6. To swap the numbers, we use a temporary variable temp. We assign the value of num1 to temp, then assign the value of num2 to num1, and finally assign the value of temp to num2.

  7. We then display the swapped values of the two numbers using the println method.

Note that there are other ways to swap two numbers without using a temporary variable, such as using arithmetic operations or the XOR bitwise operator. However, using a temporary variable is the simplest and most straightforward method.

Java Program to Swap Two Numbers Using XOR bitwise operator

import java.util.Scanner; // Import Scanner class

public class SwapNumbers {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in); // Create Scanner object

        System.out.print("Enter first number: ");
        int num1 = input.nextInt(); // Read user input for first number

        System.out.print("Enter second number: ");
        int num2 = input.nextInt(); // Read user input for second number

        System.out.println("Before swapping:");
        System.out.println("First number = " + num1);
        System.out.println("Second number = " + num2);

        // Swap numbers using XOR bitwise operator
        num1 = num1 ^ num2;
        num2 = num1 ^ num2;
        num1 = num1 ^ num2;

        System.out.println("After swapping:");
        System.out.println("First number = " + num1);
        System.out.println("Second number = " + num2);
    }
}

Explanation:

  1. We first import the Scanner class, which allows us to read user input from the console.

  2. We declare a class called SwapNumbers which contains a main method.

  3. Inside the main method, we create a Scanner object called input.

  4. We then prompt the user to enter the first and second numbers, using the print method to display the message and the nextInt method to read the integer input.

  5. We then display the original values of the two numbers using the println method.

  6. To swap the numbers using XOR bitwise operator, we don't use any temporary variable. We assign the XOR result of both numbers to num1. Now num1 contains both numbers XORed which means num1 = num1 ^ num2. Then, we assign the XOR result of num1 and num2 to num2. Now num2 has the original value of num1 which was stored in num2 in previous step, which means num2 = num1 ^ num2. Finally, we assign the XOR result of num1 and num2 to num1. Now num1 has the original value of num2 which was stored in num1 in the first step, which means num1 = num1 ^ num2.

  7. We then display the swapped values of the two numbers using the println method.

Java Program to Check Whether a Number is Even or Odd

import java.util.Scanner;

public class EvenOrOdd {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = input.nextInt();

        // Check if the least significant bit is 0
        if ((num & 1) == 0) {
            System.out.println(num + " is even.");
        } else {
            System.out.println(num + " is odd.");
        }
    }
}

Explanation:

  • This program is similar to the previous one, but it uses a different technique to check whether the number is even or odd.

  • The & operator is the bitwise AND operator, which compares the bits of the two operands and returns a new value with all the bits that are set to 1 in both operands.

  • In this program, the num & 1 expression compares the least significant bit of num (i.e., the rightmost bit) to 1. If the bit is 1, the result is 1. If the bit is 0, the result is 0.

  • If the result of num & 1 is 0, then the least significant bit of num is 0, which means that num is even. Otherwise, if the result is 1, then the least significant bit of num is 1, which means that num is odd.

  • The code inside the if and else blocks is the same as in the previous program.

Java Program to Find the Largest Among Three Numbers

Method 1

import java.util.Scanner;

public class LargestAmongThree {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter three numbers: ");
        int num1 = input.nextInt();
        int num2 = input.nextInt();
        int num3 = input.nextInt();

        int max = num1; // Assume num1 is the largest

        if (num2 > max) {
            max = num2;
        }

        if (num3 > max) {
            max = num3;
        }

        System.out.println("The largest number is: " + max);
    }
}

Explanation:

  • The import java.util.Scanner; statement is used to import the Scanner class, which is used to take user input from the console.

  • The public class LargestAmongThree statement defines a public class named LargestAmongThree.

  • The public static void main(String[] args) method is the entry point of the program.

  • The Scanner input = new Scanner(System.in); statement creates a new Scanner object called input, which reads input from the console.

  • The System.out.print("Enter three numbers: "); statement prompts the user to enter three numbers.

  • The int num1 = input.nextInt();, int num2 = input.nextInt();, and int num3 = input.nextInt(); statements read the user input as integers and store them in num1, num2, and num3, respectively.

  • The int max = num1; statement initializes a variable max with the value of num1. This assumes that num1 is the largest among the three numbers.

  • The if (num2 > max) statement checks whether num2 is greater than max. If it is, then max is updated to num2.

  • The if (num3 > max) statement checks whether num3 is greater than max. If it is, then max is updated to num3.

  • The System.out.println("The largest number is: " + max); statement prints the result to the console, indicating the largest number among the three input numbers.

Method 2

import java.util.Scanner;

public class LargestAmongThree {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter three numbers: ");
        int num1 = input.nextInt();
        int num2 = input.nextInt();
        int num3 = input.nextInt();

        int max = Math.max(num1, Math.max(num2, num3));

        System.out.println("The largest number is: " + max);
    }
}

Explanation:

  • This program uses the Math.max() method to find the largest among three numbers.

  • The Math.max() method takes two arguments and returns the maximum value of the two. In this program, we nest three Math.max() calls to find the largest among three numbers.

  • The int max = Math.max(num1, Math.max(num2, num3)); statement finds the largest among num1, num2, and num3, and stores the result in max.

  • The System.out.println("The largest number is: " + max); statement prints the result to the console, indicating the largest number among the three input numbers.

Java Program to Find the Frequency of Character in a String

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class FrequencyOfCharacter {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = input.nextLine();
        System.out.print("Enter a character: ");
        char ch = input.next().charAt(0);

        Map<Character, Integer> freqMap = new HashMap<>();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
        }

        int freq = freqMap.getOrDefault(ch, 0);

        System.out.println("The frequency of character '" + ch + "' in the string is: " + freq);
    }
}

Explanation:

  • The import java.util.HashMap;, import java.util.Map;, and import java.util.Scanner; statements are used to import the necessary Java classes.

  • The public class FrequencyOfCharacter statement defines a public class named FrequencyOfCharacter.

  • The public static void main(String[] args) method is the entry point of the program.

  • The Scanner input = new Scanner(System.in); statement creates a new Scanner object called input, which reads input from the console.

  • The System.out.print("Enter a string: "); statement prompts the user to enter a string.

  • The String str = input.nextLine(); statement reads the user input as a string and stores it in str.

  • The System.out.print("Enter a character: "); statement prompts the user to enter a character.

  • The char ch = input.next().charAt(0); statement reads the user input as a character and stores it in ch.

  • The Map<Character, Integer> freqMap = new HashMap<>(); statement creates a new HashMap object called freqMap, which will be used to store the frequency of each character in the string str.

  • The for (int i = 0; i < str.length(); i++) statement iterates over each character in the string str.

  • The char c = str.charAt(i); statement retrieves the current character from the string and stores it in c.

  • The freqMap.put(c, freqMap.getOrDefault(c, 0) + 1); statement updates the frequency of the character c in the freqMap object. If the character does not exist in the map, its frequency is initialized to 0 and then incremented by 1. If the character already exists in the map, its frequency is incremented by 1.

  • The int freq = freqMap.getOrDefault(ch, 0); statement retrieves the frequency of the character ch from the freqMap object. If the character does not exist in the map, its frequency is set to 0.

  • The System.out.println("The frequency of character '" + ch + "' in the string is: " + freq); statement prints the result to the console, indicating the frequency of the character ch in the string str.

Java Program to remove white spaces from String

import java.util.Scanner;

public class RemoveWhiteSpaces {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = input.nextLine();

        char[] chars = str.toCharArray();
        int len = chars.length;
        int index = 0;

        for (int i = 0; i < len; i++) {
            if (chars[i] != ' ') {
                chars[index++] = chars[i];
            }
        }

        String result = new String(chars, 0, index);

        System.out.println("The string with white spaces removed is: " + result);
    }
}

Explanation:

  • The import java.util.Scanner; statement is used to import the necessary Java classes.

  • The public class RemoveWhiteSpaces statement defines a public class named RemoveWhiteSpaces.

  • The public static void main(String[] args) method is the entry point of the program.

  • The Scanner input = new Scanner(System.in); statement creates a new Scanner object called input, which reads input from the console.

  • The System.out.print("Enter a string: "); statement prompts the user to enter a string.

  • The String str = input.nextLine(); statement reads the user input as a string and stores it in str.

  • The char[] chars = str.toCharArray(); statement converts the string str to a character array called chars.

  • The int len = chars.length; statement stores the length of the character array chars in len.

  • The int index = 0; statement initializes the variable index to 0, which will be used to store the index of the next non-space character in the array.

  • The for (int i = 0; i < len; i++) statement iterates over each character in the character array chars.

  • The if (chars[i] != ' ') statement checks if the current character is not a space.

  • The chars[index++] = chars[i]; statement copies the current character to the chars array at the index index, and then increments index by 1.

  • The String result = new String(chars, 0, index); statement creates a new string called result by constructing a new String object from the character array chars, starting from index 0 and ending at index index.

  • The System.out.println("The string with white spaces removed is: " + result); statement prints the result to the console, indicating the string with white spaces removed.

This approach has a time complexity of O(n), where n is the length of the string, and a space complexity of O(n), since we only use a single character array to store the string and do not create any additional data structures. Additionally, the code uses meaningful variable names and comments to enhance readability and maintainability.

Java Program to Round a Number to n Decimal Places

import java.util.Scanner;

public class RoundNumber {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        double num = input.nextDouble();
        System.out.print("Enter the number of decimal places: ");
        int n = input.nextInt();

        double factor = Math.pow(10, n);
        double roundedNum = Math.round(num * factor) / factor;

        System.out.println("The number rounded to " + n + " decimal places is: " + roundedNum);
    }
}

Explanation:

  • The import java.util.Scanner; statement is used to import the necessary Java classes.

  • The public class RoundNumber statement defines a public class named RoundNumber.

  • The public static void main(String[] args) method is the entry point of the program.

  • The Scanner input = new Scanner(System.in); statement creates a new Scanner object called input, which reads input from the console.

  • The System.out.print("Enter a number: "); statement prompts the user to enter a number.

  • The double num = input.nextDouble(); statement reads the user input as a double and stores it in num.

  • The System.out.print("Enter the number of decimal places: "); statement prompts the user to enter the number of decimal places to round to.

  • The int n = input.nextInt(); statement reads the user input as an integer and stores it in n.

  • The double factor = Math.pow(10, n); statement calculates the factor used to round the number to n decimal places. It does this by raising 10 to the power of n.

  • The double roundedNum = Math.round(num * factor) / factor; statement calculates the rounded number by multiplying the original number num by the factor, rounding it to the nearest integer using the Math.round() method, and then dividing the result by the factor to get the number rounded to n decimal places.

  • The System.out.println("The number rounded to " + n + " decimal places is: " + roundedNum); statement prints the result to the console, indicating the number rounded to n decimal places.

This approach has a time complexity of O(1) and a space complexity of O(1), since we only use a few double variables to store the input, factor, and rounded number. Additionally, the code uses meaningful variable names and comments to enhance readability and maintainability.

Java Program to Check if a String is Empty or Null

import java.util.Scanner;

public class StringChecker {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = input.nextLine();

        if (str != null && !str.trim().isEmpty()) {
            System.out.println("The string is not empty or null.");
        } else {
            System.out.println("The string is empty or null.");
        }
    }
}

Explanation:

  • The import java.util.Scanner; statement is used to import the necessary Java classes.

  • The public class StringChecker statement defines a public class named StringChecker.

  • The public static void main(String[] args) method is the entry point of the program.

  • The Scanner input = new Scanner(System.in); statement creates a new Scanner object called input, which reads input from the console.

  • The System.out.print("Enter a string: "); statement prompts the user to enter a string.

  • The String str = input.nextLine(); statement reads the user input as a string and stores it in str.

  • The if (str != null && !str.trim().isEmpty()) { statement checks if the string is not null and not empty by using the != operator to check for null and the trim() and isEmpty() methods to remove leading and trailing whitespace and check for empty string, respectively.

  • If the string is not null and not empty, the program prints "The string is not empty or null." using the System.out.println() method.

  • If the string is null or empty, the program prints "The string is empty or null." using the System.out.println() method.

This approach has a time complexity of O(1) and a space complexity of O(1), since we only use a few String and boolean variables to store the input and the check result. Additionally, the code uses meaningful variable names and comments to enhance readability and maintainability.

Did you find this article valuable?

Support Sandeep Bonagiri by becoming a sponsor. Any amount is appreciated!