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"
Table of contents
- Java Program to Print Hello World
- Java Program to print Hello World string 10 times using for loop
- Java Program to Print an Integer (Entered by the User)
- Java Program to Add Two Integers
- Java Program to Multiply two Floating Point Numbers
- Java Program to Find ASCII Value of a character
- Java Program to Compute Quotient and Remainder
- Java Program to Swap Two Numbers Using temp Variable
- Java Program to Swap Two Numbers Using XOR bitwise operator
- Java Program to Check Whether a Number is Even or Odd
- Java Program to Find the Largest Among Three Numbers
- Java Program to Find the Frequency of Character in a String
- Java Program to remove white spaces from String
- Java Program to Round a Number to n Decimal Places
- Java Program to Check if a String is Empty or Null
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 :
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.
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.
The third line defines a class called "HelloWorld". A class is a template for creating objects that share similar properties and behaviors.
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.
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.
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.
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:
We first import the
Scanner
class, which allows us to read user input from the console.We declare a class called
QuotientRemainder
which contains amain
method.Inside the
main
method, we create aScanner
object calledinput
.We then prompt the user to enter the dividend and divisor, using the
print
method to display the message and thenextInt
method to read the integer input.We then calculate the quotient and remainder using the
/
and%
operators, respectively.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:
We first import the
Scanner
class, which allows us to read user input from the console.We declare a class called
SwapNumbers
which contains amain
method.Inside the
main
method, we create aScanner
object calledinput
.We then prompt the user to enter the first and second numbers, using the
print
method to display the message and thenextInt
method to read the integer input.We then display the original values of the two numbers using the
println
method.To swap the numbers, we use a temporary variable
temp
. We assign the value ofnum1
totemp
, then assign the value ofnum2
tonum1
, and finally assign the value oftemp
tonum2
.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:
We first import the
Scanner
class, which allows us to read user input from the console.We declare a class called
SwapNumbers
which contains amain
method.Inside the
main
method, we create aScanner
object calledinput
.We then prompt the user to enter the first and second numbers, using the
print
method to display the message and thenextInt
method to read the integer input.We then display the original values of the two numbers using the
println
method.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
. Nownum1
contains both numbers XORed which meansnum1 = num1 ^ num2
. Then, we assign the XOR result ofnum1
andnum2
tonum2
. Nownum2
has the original value ofnum1
which was stored innum2
in previous step, which meansnum2 = num1 ^ num2
. Finally, we assign the XOR result ofnum1
andnum2
tonum1
. Nownum1
has the original value ofnum2
which was stored innum1
in the first step, which meansnum1 = num1 ^ num2
.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 ofnum
(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 ofnum
is 0, which means thatnum
is even. Otherwise, if the result is 1, then the least significant bit ofnum
is 1, which means thatnum
is odd.The code inside the
if
andelse
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 namedLargestAmongThree
.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 calledinput
, 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();
, andint num3 = input.nextInt();
statements read the user input as integers and store them innum1
,num2
, andnum3
, respectively.The
int max = num1;
statement initializes a variablemax
with the value ofnum1
. This assumes thatnum1
is the largest among the three numbers.The
if (num2 > max)
statement checks whethernum2
is greater thanmax
. If it is, thenmax
is updated tonum2
.The
if (num3 > max)
statement checks whethernum3
is greater thanmax
. If it is, thenmax
is updated tonum3
.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 threeMath.max()
calls to find the largest among three numbers.The
int max = Math.max(num1, Math.max(num2, num3));
statement finds the largest amongnum1
,num2
, andnum3
, and stores the result inmax
.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
;
, andimport java.util.Scanner;
statements are used to import the necessary Java classes.The
public class FrequencyOfCharacter
statement defines a public class namedFrequencyOfCharacter
.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 calledinput
, 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 instr
.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 inch
.The
Map<Character, Integer> freqMap = new HashMap<>();
statement creates a new HashMap object calledfreqMap
, which will be used to store the frequency of each character in the stringstr
.The
for (int i = 0; i < str.length(); i++)
statement iterates over each character in the stringstr
.The
char c = str.charAt(i);
statement retrieves the current character from the string and stores it inc
.The
freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
statement updates the frequency of the characterc
in thefreqMap
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 characterch
from thefreqMap
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 characterch
in the stringstr
.
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 namedRemoveWhiteSpaces
.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 calledinput
, 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 instr
.The
char[] chars = str.toCharArray();
statement converts the stringstr
to a character array calledchars
.The
int len = chars.length;
statement stores the length of the character arraychars
inlen
.The
int index = 0;
statement initializes the variableindex
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 arraychars
.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 thechars
array at the indexindex
, and then incrementsindex
by 1.The
String result = new String(chars, 0, index);
statement creates a new string calledresult
by constructing a new String object from the character arraychars
, starting from index 0 and ending at indexindex
.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 namedRoundNumber
.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 calledinput
, 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 innum
.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 inn
.The
double factor = Math.pow(10, n);
statement calculates the factor used to round the number ton
decimal places. It does this by raising 10 to the power ofn
.The
double roundedNum = Math.round(num * factor) / factor;
statement calculates the rounded number by multiplying the original numbernum
by the factor, rounding it to the nearest integer using theMath.round()
method, and then dividing the result by the factor to get the number rounded ton
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 ton
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 namedStringChecker
.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 calledinput
, 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 instr
.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 thetrim()
andisEmpty()
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.