10 common Java programs that every programmer should know how to write
- Hello, World!” program: A simple program that prints “Hello, World!” to the console. This is often the first program that programmers write when learning a new programming language.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation:
- The program defines a class called
HelloWorld
. - Inside the class, there is a method called
main
. - The
main
method is the entry point of the program, and is where the program starts executing. - The
main
method takes an array of strings as its argument, which can be used to pass command-line arguments to the program. - Inside the
main
method, there is a single line of code:System.out.println("Hello, World!");
. - This line of code uses the
println
method of theSystem.out
object to print the string "Hello, World!" to the console.
2. Basic calculator: A program that can perform basic mathematical operations, such as addition, subtraction, multiplication, and division.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double num1, num2;
char operator;
double result;
System.out.print("Enter first number: ");
num1 = scanner.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
operator = scanner.next().charAt(0);
System.out.print("Enter second number: ");
num2 = scanner.nextDouble();
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 '/':
result = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + result);
break;
default:
System.out.println("Invalid operator");
break;
}
}
}
Explanation:
- The program defines a class called
Calculator
. - Inside the class, there is a method called
main
. - The
main
method is the entry point of the program, and is where the program starts executing. - The program uses the
Scanner
class from thejava.util
package to read input from the user. - The program prompts the user to enter two numbers and an operator.
- The program uses a switch statement to determine which operation to perform based on the operator entered by the user.
- The program then performs the corresponding operation and prints the result to the console.
- The program also include a default case to handle the case where the operator is not valid.
- You can run the program by compiling it with the
javac
command and then running it with thejava
command.
3. Fibonacci sequence: A program that generates the Fibonacci sequence, which is a series of numbers in which each number is the sum of the two preceding ones.
public class Fibonacci {
public static void main(String[] args) {
int n = 10, t1 = 0, t2 = 1;
System.out.print("First " + n + " terms: ");
for (int i = 1; i <= n; ++i) {
System.out.print(t1 + " + ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
Explanation:
- The program defines a class called
Fibonacci
. - Inside the class, there is a method called
main
. - The
main
method is the entry point of the program, and is where the program starts executing. - The program uses a for loop to generate the first
n
terms of the Fibonacci sequence. - The variable
n
is used to specify how many terms of the sequence should be generated. - The variable
t1
is initialized to 0, andt2
is initialized to 1. - Inside the loop, the value of
t1
is printed to the console, and the sum oft1
andt2
is calculated and stored in the variablesum
. - The values of
t1
andt2
are then updated to be equal to the previous value oft2
and the new value ofsum
, respectively. - The loop continues until the specified number of terms have been generated.
4. Palindrome checker: A program that checks if a given string is a palindrome, which is a word, phrase, or sequence of characters that reads the same forwards and backwards.
import java.util.Scanner;
public class PalindromeNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
int originalNum;
int reversedNum = 0;
System.out.print("Enter a number: ");
num = scanner.nextInt();
originalNum = num;
while (num != 0) {
int lastDigit = num % 10;
reversedNum = reversedNum * 10 + lastDigit;
num /= 10;
}
if (originalNum == reversedNum) {
System.out.println(originalNum + " is a palindrome number.");
} else {
System.out.println(originalNum + " is not a palindrome number.");
}
}
}
Explanation:
- The program defines a class called
PalindromeNumber
. - Inside the class, there is a method called
main
. - The
main
method is the entry point of the program, and is where the program starts executing. - The program uses the
Scanner
class from thejava.util
package to read input from the user. - The program prompts the user to enter a number.
- The program then assigns the value entered by the user to the variable
num
and also assigns the same value to the variableoriginalNum
for later comparison. - The program then uses a while loop to reverse the digits of the number. In each iteration, the program extracts the last digit of the number by using the modulus operator and adds it to a new variable called
reversedNum
. - Then the program divides the
num
by 10 so that the next iteration will consider the next digit. - After the while loop, the program checks if the original number is equal to the reversed number, if yes then it’s a palindrome otherwise not.
5. Array sorting: A program that sorts an array of integers in ascending or descending order.
import java.util.Arrays;
public class ArraySorter {
public static void main(String[] args) {
int[] numbers = {5, 2, 9, 1, 7};
for (int i = 0; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] > numbers[j]) {
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
System.out.println("Sorted array: " + Arrays.toString(numbers));
}
}
Explanation:
- The program defines a class called
ArraySorter
. - Inside the class, there is a method called
main
. - The
main
method is the entry point of the program, and is where the program starts executing. - The program defines an array of integers called
numbers
. - The program uses two nested for loops to compare each element of the array with the rest of the elements.
- The program uses an if statement to check if the current element is greater than the next element. If it is, it swaps the elements using a temporary variable.
- The outer for loop will run until the last element of the array, and the inner for loop will run until the last element of the array.
- The program then uses the
Arrays.toString()
method to print the sorted array to the console. - You can run the program by compiling it with the
javac
command and then running it with thejava
command.
6. Object-oriented program: A program that demonstrates the use of classes, objects, and inheritance in Java.
class Shape {
protected int width;
protected int height;
public Shape(int width, int height) {
this.width = width;
this.height = height;
}
public int getArea() {
return width * height;
}
}
class Rectangle extends Shape {
public Rectangle(int width, int height) {
super(width, height);
}
}
class Square extends Shape {
public Square(int side) {
super(side, side);
}
}
public class OOPExample {
public static void main(String[] args) {
Shape shape = new Shape(5, 10);
System.out.println("Shape area: " + shape.getArea());
Rectangle rect = new Rectangle(5, 10);
System.out.println("Rectangle area: " + rect.getArea());
Square square = new Square(5);
System.out.println("Square area: " + square.getArea());
}
}
Explanation:
- The program defines a class called
Shape
, which is the base class for the program. It has two protected fields calledwidth
andheight
and a constructor that initializes them. It also has a method calledgetArea
that calculates the area of the shape. - The program defines a class called
Rectangle
that extends theShape
class. It has a constructor that calls the constructor of theShape
class and passes thewidth
andheight
parameters. - The program defines a class called
Square
that extends theShape
class. It has a constructor that calls the constructor of theShape
class and passes the same value for thewidth
andheight
parameters. - The program defines a class called
OOPExample
which is the entry point of the program, and is where the program starts executing. - Inside the
main
method, it creates an object of theShape
class, an object of theRectangle
class, and an object of theSquare
class. - It calls the
getArea
method on each object and prints the result to the console.
7. File IO: A program that can read and write to a file.
import java.io.*;
public class FileIO {
public static void main(String[] args) {
String fileName = "example.txt";
String line;
// Writing to a file
try {
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("Hello, World!");
bufferedWriter.newLine();
bufferedWriter.write("This is a sample text file.");
bufferedWriter.close();
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("Error writing to file '" + fileName + "'");
}
// Reading from a file
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch (FileNotFoundException e) {
System.out.println("Error: File '" + fileName + "' not found.");
} catch (IOException e) {
System.out.println("Error reading file '" + fileName + "'");
}
}
}
Explanation:
- The program defines a class called
FileIO
. - Inside the class, there is a method called
main
. - The
main
method is the entry point of the program, and is where the program starts executing. - The program defines a string variable called
fileName
which contains the name of the file that the program will read from and write to. - The program then creates a
FileWriter
object and aBufferedWriter
object, and uses them to write the string "Hello, World!" and "This is a sample text file." to the file.
8. Exception handling: A program that demonstrates how to handle exceptions in Java.
public class ExceptionExample {
public static void main(String[] args) {
try {
int a = 5;
int b = 0;
int c = a / b;
System.out.println("Result: " + c);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero");
} finally {
System.out.println("This code will always run");
}
}
}
Explanation:
In this example, the code inside the try block is the code that might throw an exception. In this case, it is trying to divide a number by zero, which is not allowed. The catch block is where the exception is handled. In this case, it is an ArithmeticException, which is thrown when an arithmetic operation is attempted with an illegal number. In the catch block, we print an error message. The finally block is optional, but if present, it will always run, whether an exception is thrown or not.
In this example the output would be:
Error: Cannot divide by zero
This code will always run
It’s important to note that when an exception is thrown, the program will stop executing the code inside the try block and jump directly to the catch block.
9. GUI program: A program that uses the Java Swing library to create a simple graphical user interface.
import javax.swing.*;
import java.awt.*;
public class SimpleGUI {
public static void main(String[] args) {
JFrame frame = new JFrame("Simple GUI"); // Create a new JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit the program when the user closes the window
frame.setSize(300, 200); // Set the size of the window
JButton button = new JButton("Click me!"); // Create a new button
button.setPreferredSize(new Dimension(150, 50)); // Set the size of the button
frame.add(button); // Add the button to the window
frame.setVisible(true); // Make the window visible
}
}
Explanation:
This program creates a window with a button that says “Click me!” When the user clicks the button, nothing happens, but the button can be modified to perform an action when it is clicked.
In this example we are using two core classes of Swing library JFrame and JButton. JFrame is a top-level container that provides a window with a title bar, window buttons and a content pane. JButton is a Swing component that creates a button which can be clicked by a user to perform an action.
The setDefaultCloseOperation() method sets what happens when the user closes the window. The EXIT_ON_CLOSE value causes the program to terminate. setSize() method sets the size of the window. Dimension class is used for setting the size of the button. The setVisible() method makes the window visible on the screen.
It’s important to note that this is a simple example and does not handle errors or edge cases. A real-world GUI program would likely include additional functionality and error handling.
10. Multi-threading: A program that demonstrates the use of multiple threads to perform multiple tasks simultaneously.
public class MultiThreadingExample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(), "Thread-1");
Thread t2 = new Thread(new MyRunnable(), "Thread-2");
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Both threads have finished executing");
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Explanation:
This program creates two threads, t1 and t2, which both run the same MyRunnable class. The MyRunnable class implements the Runnable interface and overrides the run() method. The run() method is where the code that will be executed by the thread goes. In this example, the run method simply prints out the current thread’s name and the current value of a loop variable and then sleeps for 500 milliseconds.
The main method of the program creates two threads, and starts both of them by calling their start() method. The join() method is called on both threads, which causes the main thread to wait for both t1 and t2 to complete before continuing.
The output would be something like:
Thread-1: 0
Thread-2: 0
Thread-1: 1
Thread-2: 1
...
Both threads have finished executing
It’s important to note that the order of the output may vary as the execution of the threads is not guaranteed to be in order.
This is a simple example of multi-threading, in a real-world program, you would likely have more complex logic and use additional synchronization mechanisms to coordinate the actions of multiple threads.
It’s important to note that these are just a few examples of the many types of programs that can be written in Java, and it’s important to understand the fundamentals of programming before diving in to more complex programs.