TL;DR: The best Java programs for practice start with fundamentals like string reversal and array manipulation, then move to intermediate projects like matrix multiplication and sorting algorithms. Advanced practice should focus on database connectivity, object-oriented design, and the use of data structures such as HashMaps to build a strong foundation for professional software development.

Introduction

In late 2023, as Netflix engineers began rolling out Java 21 across their vast infrastructure, they hit a snag. Services using the new, highly anticipated "virtual threads" feature started hanging during deployment. The culprit was a surge of sockets stuck in a CLOSE_WAIT state, a subtle but critical issue* that could cripple services at Netflix's scale. Debugging this required a deep, fundamental understanding of Java’s core mechanics, from thread management to network protocols. The engineers traced the problem, documented their findings, and operationalized a solution.

The situation at Netflix reveals something important about software development. Skillful programming comes from a strong foundation built on core concepts. Memorizing complex frameworks is a poor substitute for consistent practice. Writing and understanding fundamental programs is the only way to develop the intuition needed to solve complex, real-world problems.

This guide provides a curated list of Java programs for practice suitable for both beginners and experienced developers. We will walk through several Java programming examples with code snippets that reinforce essential concepts, from basic syntax to more advanced logic, helping you build the skills necessary to tackle any challenge.

Did You Know?
Adoption of modern Java versions is accelerating rapidly. Java 17 usage grew nearly 300% in just one year (2023-2024), and Java 21 adoption is happening almost three times as fast as Java 17's initial uptake. [Source: New Relic]

Why Practice With Java Programs?

A musician practices scales before playing a symphony. A programmer needs to work on the fundamentals before building a complex application. Working through basic Java programs offers excellent practice in Java coding and helps you develop a knack for problem-solving. It helps you understand how to break down a large problem into smaller, manageable steps, a skill essential for any software developer.

For beginners, these exercises provide a hands-on way to see abstract concepts like loops, conditional statements, and data structures in action. For experienced programmers, returning to the basics can reinforce good habits, introduce new ways to solve old problems (especially with newer Java versions), and keep skills sharp.

Regular practice helps you stay current and relevant in a rapidly changing tech landscape. It makes you a more valuable asset to your team and can lead to promotions and new career opportunities. Companies do not want to lose highly skilled developers who can solve problems efficiently.

Setting Up Your Java Environment

Before you can start coding, you need a proper development environment. This typically consists of the Java Development Kit (JDK) and an Integrated Development Environment (IDE).

  • The JDK is the core component that includes the Java compiler, the Java Virtual Machine (JVM), and standard class libraries. It’s everything you need to compile and run Java code.
  • An IDE is a software application that provides comprehensive facilities to programmers for software development. An IDE typically includes a source code editor, build automation tools, and a debugger. Popular choices for Java include IntelliJ IDEA, Eclipse, and Visual Studio Code.

Once you have the JDK installed and an IDE set up, you are ready to write your first program. Below are several Java program examples with output to get you started.

Java Programs for Beginners: Basic Examples

These Java code examples for beginners are just perfect. They cover the absolute essentials and provide a solid starting point for your coding work. Each basic Java program example includes the Java example code, an explanation, and a sample output.

1. The Classic "Hello, World!"

This is the traditional first program for anyone learning a new language. It confirms that your environment is set up correctly and introduces you to the basic structure of a Java program.

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

How it Works

  • public class HelloWorld declares a class named HelloWorld. In Java, all code must reside inside a class.
  • public static void main(String[] args) is the entry point for the application. The Java Virtual Machine (JVM) starts executing code here.
  • System.out.println("Hello, World!"); is the statement that prints the text to the console.

Output

Hello, World!

2. Adding Two Numbers

This program demonstrates how to declare variables, assign values to them, and perform a simple arithmetic operation.

public class AddTwoNumbers {
public static void main(String[] args) {
int num1 = 15;
int num2 = 10;
int sum = num1 + num2;
System.out.println("The sum is: " + sum);
}
}

How it Works

  • The lines int num1 = 15; and int num2 = 10; declare two integer variables and initialize them with values.
  • The line int sum = num1 + num2; adds the two numbers and stores the result in a new variable called sum.
  • System.out.println("The sum is: " + sum); prints the result to the console. The + operator combines the text string with the value of the sum variable.

Output

The sum is: 25

3. Swapping Two Numbers

This Java program to swap two numbers is a common introductory exercise that demonstrates the use of a temporary variable to swap the values of two other variables.

public class SwapNumbers {
public static void main(String[] args) {
int first = 10;
int second = 20;
System.out.println("--Before swap--");
System.out.println("First number: " + first);
System.out.println("Second number: " + second);
// Value of first is assigned to a temporary variable
int temporary = first;
// Value of second is assigned to first
first = second;
// Value of temporary (which contains the initial value of first) is assigned to second
second = temporary;
System.out.println("--After swap--");
System.out.println("First number: " + first);
System.out.println("Second number: " + second);
}
}

How it Works

  • Two integer variables, first and second, are initialized.
  • A temporary third variable is created to hold the value of first.
  • The value of the second is copied into the first. At this point, first holds the value 20.
  • The original value of first, which is stored in a temporary, is copied into second. This completes the swap.

Output

--Before swap--

First number: 10

Second number: 20

--After swap--

First number: 20

Second number: 10

4. Checking for an Even or Odd Number

This simple Java program to check whether a number is even or odd introduces conditional logic using an if-else statement and the modulo operator (%), which returns the remainder of a division.

import java.util.Scanner;
public class EvenOrOdd {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = reader.nextInt();
if (num % 2 == 0) {
System.out.println(num + " is an even number.");
} else {
System.out.println(num + " is an odd number.");
}
}
}

How it Works

  • import java.util.Scanner; makes the Scanner class available, which is needed for user input.
  • Scanner reader = new Scanner(System.in); creates an object to read from the keyboard.
  • The program prompts the user, then reads the integer they enter and stores it in the num variable.
  • The if (num % 2 == 0) statement checks whether num divided by 2 has a remainder of 0. If it does, the number is even. Otherwise, the code in the else block is executed.

Output

Enter a number: 42

42 is an even number.

5. Calculating the Factorial of a Number

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. This Java factorial program example demonstrates the use of a for loop.

public class Factorial {
public static void main(String[] args) {
int number = 5;
long factorialResult = 1;
for(int i = 1; i <= number; ++i) {
factorialResult = factorialResult * i;
}
System.out.println("Factorial of " + number + " is: " + factorialResult);
}
}

How it Works

  • A long variable factorialResult is initialized to 1. The long type is used to prevent overflow with larger factorials.
  • A for loop iterates from 1 up to the target number.
  • In each pass of the loop, factorialResult is multiplied by the current loop counter i. This builds the factorial product step by step.

Output

Factorial of 5 is: 120

6. Generating the Fibonacci Series

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. This program is a great way to practice loops and variable assignments.

public class Fibonacci {
public static void main(String[] args) {
int n = 10; // Number of terms to generate
int firstTerm = 0;
int secondTerm = 1;
System.out.println("Fibonacci Series up to " + n + " terms:");
for (int i = 1; i <= n; ++i) {
System.out.print(firstTerm + " ");
// Compute the next term
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}

How it Works

  • The program starts by setting up the first two terms of the sequence, firstTerm (0) and secondTerm (1).
  • A for loop runs for the desired number of terms (n).
  • Inside the loop, it first prints the current firstTerm. Then, it calculates the nextTerm by adding the two previous terms.
  • To prepare for the next iteration, it updates firstTerm to the value of secondTerm, and secondTerm to the value of the new nextTerm.

Output

Fibonacci Series up to 10 terms:

0 1 1 2 3 5 8 13 21 34

Working with text is fundamental in programming. The following Java programs for string manipulation cover common tasks such as reversal and palindrome checks.

7. Reversing a String

This common Java program to reverse a string is a great exercise for understanding string manipulation and loops. It teaches you how to iterate through a string and build a new one in reverse order.

public class ReverseString {
public static void main(String[] args) {
String originalStr = "Hello";
String reversedStr = "";
for (int i = 0; i < originalStr.length(); i++) {
reversedStr = originalStr.charAt(i) + reversedStr;
}
System.out.println("Original string: " + originalStr);
System.out.println("Reversed string: " + reversedStr);
}
}

How it Works

  • An empty string, reversedStr, is created to hold the result.
  • The program uses a for loop to iterate over the characters of the originalStr from the first to the last.
  • Inside the loop, originalStr.charAt(i) gets the character at the current position. The key part is originalStr.charAt(i) + reversedStr, which prepends the current character to the result string, effectively building it in reverse.

Output

Original string: Hello

Reversed string: olleH

8. Checking for a Palindrome

A palindrome reads the same backward as forward. This Java palindrome program combines string reversal logic with a conditional statement to check for this property.

import java.util.Scanner;
public class PalindromeCheck {
public static void main(String[] args) {
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it's a palindrome:");
original = in.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + original.charAt(i);
}
if (original.equals(reverse)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string isn't a palindrome.");
}
}
}

How it Works

  • The program first reverses the input string. It uses a for loop that starts from the last character (length - 1) and works its way backward to the first character (i >= 0).
  • In each iteration, it appends the character at the current index to the reverse string.
  • After the loop, the original input string is compared to the reverse string using the .equals() method. If they are identical, the string is a palindrome.

Output

Enter a string to check if it's a palindrome:

racecar

The string is a palindrome.

Did You Know?

LinkedIn's Java-based Apache Kafka system processes an astounding 7 trillion messages every single day. This massive infrastructure consists of over 100 Kafka clusters and more than 4,000 brokers. [Source: LinkedIn]

Intermediate Java Array Program Examples and More

Once you are comfortable with the basics, you can move on to programs that involve more complex data structures like arrays and more sophisticated logic.

9. Finding the Largest Element in an Array

This program teaches you how to iterate through an array to find the largest value. The logic can be easily adapted if you need a Java program to find the largest of three numbers. It is a foundational algorithm for data analysis.

public class LargestInArray {
public static void main(String[] args) {
int[] numbers = {25, 11, 7, 75, 56};
int largest = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
}
System.out.println("The largest number in the array is: " + largest);
}
}

How it Works

  • The program initializes a variable, largest, to the value of the array's first element.
  • It then uses a for loop to iterate over the remaining elements of the array, starting with the second element (index 1).
  • Inside the loop, it compares each element (numbers[i]) with the current largest value.
  • If the current element is greater than the largest, the largest is updated to the current element's value. After the loop finishes, the largest holds the maximum value.

Output

The largest number in the array is: 75

Matrices, represented as 2D arrays, are common in various computational tasks. These Java 2D array program examples demonstrate transposition and multiplication.

10. Transposing a Matrix

Transposing a matrix means swapping its rows with its columns. This exercise is excellent for practicing nested loops and manipulating 2D arrays.

public class TransposeMatrix {
public static void main(String[] args) {
int[][] matrix = { {1, 2, 3}, {4, 5, 6} };
// Display original matrix
System.out.println("The original matrix is: ");
printMatrix(matrix);
int rows = matrix.length;
int cols = matrix[0].length;
int[][] transpose = new int[cols][rows];
for(int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transpose[j][i] = matrix[i][j];
}
}
// Display transposed matrix
System.out.println("The transposed matrix is: ");
printMatrix(transpose);
}
public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
}
}

How it Works

  • A new 2D array, transpose, is created with its dimensions swapped. The number of rows from the original becomes the number of columns in the new one, and vice versa.
  • Two nested for loops iterate through every element of the original matrix.
  • The core of the operation is the assignment transpose[j][i] = matrix[i][j]. This takes the element from row i, column j of the original matrix and places it into row j, column i of the transpose matrix.

Output

The original matrix is:

1 2 3

4 5 6

The transposed matrix is:

1 4

2 5

3 6

11. Matrix Multiplication

This program deals with two-dimensional arrays (matrices) and involves nested loops to perform multiplication. It is a great exercise for understanding how to work with more complex data structures.

public class MultiplyMatrices {
public static void main(String[] args) {
int r1 = 2, c1 = 3;
int r2 = 3, c2 = 2;
int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} };
int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} };
// To store the result
int[][] product = new int[r1][c2];
// Multiplying the matrices
for(int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
// Displaying the result
System.out.println("Product of two matrices is: ");
for(int[] row : product) {
for (int column : row) {
System.out.print(column + "    ");
}
System.out.println();
}
}
}

How it Works

  • The operation requires three nested for loops. The outer two loops (i and j) iterate through each cell of the product matrix that will store the result.
  • The innermost loop (k) performs the dot product calculation.
  • For each cell [i][j] in the product matrix, the innermost loop sums the products of corresponding elements from row i of the firstMatrix and column j of the secondMatrix.

Output

Product of two matrices is:

24    29

6      25

12. Removing Duplicate Elements from an Array

This program demonstrates a practical data-cleaning task. While Java's Collections framework provides easier ways to do this (like using a Set), implementing it manually with an array is an excellent exercise in algorithmic thinking.

import java.util.Arrays;
public class RemoveDuplicates {
public static int[] removeDuplicates(int[] arr) {
if (arr.length == 0) {
return new int[0];
}
// Sort the array to bring duplicates together
Arrays.sort(arr);
int[] temp = new int[arr.length];
int j = 0;
temp[j++] = arr[0]; // First element is always unique
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
temp[j++] = arr[i];
}
}
// Create a new array with the correct size
int[] uniqueArray = new int[j];
System.arraycopy(temp, 0, uniqueArray, 0, j);
return uniqueArray;
}
public static void main(String[] args) {
int[] arr = {10, 20, 20, 30, 30, 40, 50, 50};
int[] uniqueArr = removeDuplicates(arr);
System.out.println("Array with Duplicates: " + Arrays.toString(arr));
System.out.println("Array without Duplicates: " + Arrays.toString(uniqueArr));
}
}

How it Works

  • The program first sorts the array using Arrays.sort(). This is a key step that groups duplicate values.
  • It then iterates through the sorted array. An element is copied to a new temporary array only if it is different from the element that came immediately before it. This logic ensures unique values are copied.
  • Because the temporary array may contain extra empty slots, a final array is created with the exact number of unique elements, and the values are copied into it. For a deeper dive into methods, see our guide on methods in Java.

Output

Array with Duplicates: [10, 20, 20, 30, 30, 40, 50, 50]

Array without Duplicates: [10, 20, 30, 40, 50]

13. Checking for a Prime Number

A prime number is a natural number greater than 1 with no positive divisors other than 1 and itself. This Java prime number program checks if a given number meets this condition.

public class PrimeCheck {
public static void main(String[] args) {
int num = 29;
boolean isPrime = true;
if (num <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= num / 2; ++i) {
// condition for non-prime number
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}

How it Works

  • The logic starts by assuming the number is prime and using a boolean flag, isPrime.
  • It handles the base cases first: any number less than or equal to 1 is not prime.
  • A for loop iterates from 2 up to half of the number. If num is evenly divisible by any number i in this range (num % i == 0), then it cannot be prime.
  • If a divisor is found, the isPrime flag is set to false, and the break statement exits the loop immediately, as no more checks are needed.

Output

29 is a prime number.

14. Printing a Pyramid Pattern

Pattern-printing programs, like this Java pattern printing program for a pyramid, are a popular way to practice nested loops and develop logical thinking. This example prints a simple pyramid of asterisks.

public class PyramidPattern {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; ++i) {
// Loop for spaces
for (int j = 1; j <= rows - i; ++j) {
System.out.print("  ");
}
// Loop for asterisks
for (int k = 1; k <= 2 * i - 1; ++k) {
System.out.print("* ");
}            
System.out.println();
}
}
}

How it Works

  • The outer for loop (i) controls the number of rows in the pyramid.
  • The first inner loop (j) is responsible for printing the leading spaces that center the pyramid. The number of spaces decreases as the row number i increases.
  • The second inner loop (k) prints the asterisks. The number of asterisks for each row is calculated as 2 * i - 1, which produces an odd-numbered sequence (1, 3, 5, ...).
  • After each row is complete, System.out.println() moves the cursor to the next line.

Output

         * 

      * * * 

     * * * * * 

  * * * * * * * 

* * * * * * * * *

Advanced Java Programs

These programs introduce more sophisticated concepts, such as common algorithms and data structures from the Java Collections Framework. They are designed for those who have a good grasp of the basics and want to tackle more challenging problems.

15. Binary Search Algorithm

Binary search is an efficient algorithm for finding an item in a sorted list. It works by repeatedly dividing the portion of the list that could contain the item in half until you have narrowed down the possible locations to just one.

import java.util.Scanner;
class BinarySearch {
public static void main(String args[]) {
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers in sorted order");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first  = 0;
last   = n - 1;
middle = (first + last)/2;
while( first <= last ) {
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search ) {
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
} else {
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " isn't present in the list.");
}
}

How it Works

  • The algorithm requires a sorted array. It maintains two pointers, first and last, initially pointing to the start and end of the array.
  • Inside a while loop, it calculates the middle index. It then compares the element at this index with the search value.
  • Halve the Search Space:
    • If the middle element is smaller than the search value, the left half of the array is discarded by moving first to middle + 1.
    • If it is larger, the right half is discarded by moving the last to middle - 1.
  • This halving process repeats until the value is found or the first and last pointers cross, indicating that the value is not in the array.

Output

Enter number of elements

5

Enter 5 integers in sorted order

10

20

30

40

50

Enter value to find

30

30 found at location 3

16. Removing Elements from an ArrayList

An ArrayList is a resizable array. This program shows how to add elements to an ArrayList and then remove them, demonstrating its dynamic nature.

import java.util.ArrayList;
import java.util.List;
public class RemoveFromListDemo {
public static void main(String[] args) {
List<String> cityList = new ArrayList<String>();
cityList.add("Delhi");
cityList.add("Mumbai");
cityList.add("Kolkata");
cityList.add("Hyderabad");
cityList.add("Bangalore");
cityList.add("Mumbai"); // Adding a duplicate for demonstration
System.out.println("Original List: " + cityList);
// Removing element by index
cityList.remove(1); // Removes the element at index 1 ("Mumbai")
// Removing element by value
cityList.remove("Mumbai"); // Removes the first occurrence of "Mumbai"
System.out.println("List after removing elements: " + cityList);
}
}

How it Works

  • An ArrayList named cityList is created. Elements are added using the .add() method.
  • The line cityList.remove(1) removes the element located at the specified index (the second element in this case).
  • The line cityList.remove("Mumbai") searches the list for the first element that matches the given string and removes it.

Output

Original List: [Delhi, Mumbai, Kolkata, Hyderabad, Bangalore, Mumbai]

List after removing elements: [Delhi, Kolkata, Hyderabad, Bangalore, Mumbai]

17. Implementing a HashMap

A HashMap is a data structure that stores key-value pairs. This is incredibly useful for fast lookups. This example demonstrates basic HashMap operations.

import java.util.HashMap;
public class HashMapDemo {
public static void main(String[] args) {
// Create a HashMap object called capitalCities
HashMap<String, String> capitalCities = new HashMap<String, String>();
// Add keys and values (Country, City)
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington D.C.");
System.out.println("HashMap: " + capitalCities);
// Access an item
String capitalOfGermany = capitalCities.get("Germany");
System.out.println("Capital of Germany is: " + capitalOfGermany);
// Remove an item
capitalCities.remove("England");
System.out.println("HashMap after removing England: " + capitalCities);
}
}

How it Works

  • A HashMap object is created, specifying the data types for its keys (String) and values (String).
  • The .put() method inserts a new key-value pair. If the key already exists, this method updates the corresponding value.
  • The .get() method retrieves the value associated with a specific key.
  • The .remove() method deletes the key-value pair for a given key.

Output

HashMap: {USA=Washington D.C., Norway=Oslo, England=London, Germany=Berlin}

Capital of Germany is: Berlin

HashMap after removing England: {USA=Washington D.C., Norway=Oslo, Germany=Berlin}

18. Heap Sort Algorithm

Heap Sort is an efficient, comparison-based sorting algorithm. It will build max heap from the input data. Then, the largest item is repeatedly removed from the heap and placed at the end of the sorted portion of the array.

public class HeapSort {
public void sort(int arr[]) {
int n = arr.length;
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i = n - 1; i > 0; i--) {
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
void heapify(int arr[], int n, int i) {
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
heapify(arr, n, largest);
}
}
public static void main(String args[]) {
int arr[] = {12, 11, 13, 5, 6, 7};
HeapSort ob = new HeapSort();
ob.sort(arr);
System.out.println("Sorted array is");
for (int val : arr) {
System.out.print(val + " ");
}
}
}

How it Works

  • The first phase of the algorithm converts the input array into a max-heap. A max-heap is a specific tree-based structure where the value of each parent node is greater than or equal to the values of its children. This is achieved using a helper function, heapify.
  • The second phase repeatedly extracts the largest element. It swaps the root of the heap (which is always the largest element) with the last element in the heap. It then reduces the heap's conceptual size by 1 and calls heapify on the new root to maintain the heap property. This process continues until the array is sorted.

Output

Sorted array is

5 6 7 11 12 13

19. SQL Database Connectivity (JDBC)

Java Database Connectivity (JDBC) is an API that enables you to connect to and execute queries against a database. This example shows the basic steps to connect to a database, run a SELECT query, and print the results.

//NOTE: This code requires a JDBC driver for your specific database (e.g., MySQL Connector/J)
//and a configured database with a table.
import java.sql.*;
public class JdbcExample {
static final String DB_URL = "jdbc:mysql://localhost/YOUR_DATABASE";
static final String USER = "your_username";
static final String PASS = "your_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// Register JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT id, first_name, last_name FROM employees";
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while(rs.next()){
int id  = rs.getInt("id");
String first = rs.getString("first_name");
String last = rs.getString("last_name");
System.out.println("ID: " + id + ", Name: " + first + " " + last);
}
rs.close();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt!=null) stmt.close();
if(conn!=null) conn.close();
} catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}

How it Works

  • Class.forName() loads the database-specific driver class into memory.
  • DriverManager.getConnection() uses the database URL, username, and password to establish a connection.
  • conn.createStatement() creates a Statement object that sends SQL commands to the database.
  • stmt.executeQuery() runs the SQL query and returns the data in a ResultSet object.
  • The while(rs.next()) loop moves through each row of the ResultSet. Getter methods such as getInt() and getString() are used to retrieve data from each column.
  • The finally block is essential. It ensures that the Connection, Statement, and ResultSet are closed, freeing up database and memory resources even if an error occurs.

Output (assuming a database with data):

Connecting to database...

Creating statement...

ID: 101, Name: John Doe

ID: 102, Name: Jane Smith

Goodbye!

20. Simple Employee Management System

This program, one of our Java object-oriented example programs, introduces the fundamentals of OOP in Java. It involves creating a simple Employee class to represent an employee's data (encapsulation) and then creating objects of that class to use in a main program.

// Employee.java - The class definition
class Employee {
private int id;
private String name;
private String department;
private double salary;
// Constructor to initialize the object
public Employee(int id, String name, String department, double salary) {
this.id = id;
this.name = name;
this.department = department;
this.salary = salary;
}
// Method to display employee details
public void displayDetails() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Department: " + department);
System.out.println("Salary: $" + salary);
System.out.println("--------------------");
}
// Getter method for salary
public double getSalary() {
return salary;
}
// Setter method to update salary
public void setSalary(double newSalary) {
if (newSalary > 0) {
this.salary = newSalary;
}
}
}
// Main.java - The main class to run the program
public class EmployeeManagement {
public static void main(String[] args) {
// Create two Employee objects
Employee emp1 = new Employee(101, "Alice Smith", "Engineering", 80000.00);
Employee emp2 = new Employee(102, "Bob Johnson", "Marketing", 65000.00);
System.out.println("Initial Employee Details:");
emp1.displayDetails();
emp2.displayDetails();
// Update an employee's salary
System.out.println("Updating Alice's salary...");
emp1.setSalary(85000.00);
System.out.println("\nUpdated Employee Details:");
emp1.displayDetails();
}
}

How it Works

  • The program is split into two parts. The Employee class serves as a blueprint, defining fields (such as id and name) and methods (such as displayDetails). The fields are private to encapsulate the data.
  • The Employee(...) method is a special constructor that creates and initializes new Employee objects with initial values.
  • In the main method of the EmployeeManagement class, new Employee(...) is used to create instances (objects) of the Employee class. emp1 and emp2 are two distinct objects.
  • Actions are performed by calling methods on these objects using the dot (.) operator, such as emp1.displayDetails() to print information or emp1.setSalary() to change a value.

Output

Initial Employee Details:

ID: 101

Name: Alice Smith

Department: Engineering

Salary: $80000.0

--------------------

ID: 102

Name: Bob Johnson

Department: Marketing

Salary: $65000.0

--------------------

Updating Alice's salary...

Updated Employee Details:

ID: 101

Name: Alice Smith

Department: Engineering

Salary: $85000.0

--------------------

Did You Know?
Microsoft revealed in 2024 that it runs over 2.5 million Java Virtual Machines (JVMs) in production. This includes massive systems like LinkedIn, highlighting the scale of Java even within companies known for other technologies. [Source: YouTube]

From Practice to Profession: Connecting Programs to Real Skills

It might be hard to see how a simple program like a palindrome checker connects to a high-paying job. But these fundamental exercises are the building blocks for the complex logic required in professional software development. Every feature in a large-scale application, from a social media feed to a banking transaction, is built on these core concepts.

Practice Program

Core Concept Learned

Real-World Application

Palindrome Checker

String Manipulation, Loops

Validating user input, processing text data

Factorial Calculator

Loops, Algorithmic Logic

Financial calculations, scientific modeling

Largest in Array

Array Traversal, Comparison

Finding max values in datasets, analytics

Binary Search

Efficient Searching, Algorithms

Fast data lookups in databases and applications

HashMap Demo

Key-Value Data Structures

Caching, indexing, and managing application configuration

JDBC Example

Database Interaction

Building any application that needs to persist data

Taking the Next Step in Your Java Work

Once you have a good handle on these programs, you'll have a solid foundation. You can then move on to advanced topics required for a career as a modern developer. Building on what you have practiced here will prepare you for professional development.

  • Use a framework like Spring Boot to build a simple API. This allows different applications to communicate over the web, forming the backbone of the microservices architecture.
  • Write programs that can perform multiple tasks simultaneously. This is crucial for building responsive and high-performance applications.
  • Learn about common solutions to recurring software design problems. Understanding patterns like Singleton, Factory, and Observer will make your code more robust and maintainable.

If you are ready to move from individual programs to building complete, job-ready applications, our Full Stack Java Developer Masters Program is a perfect next step. This comprehensive program covers everything from front-end frameworks like React to back-end technologies like Spring Boot and Hibernate, preparing you for an exciting career.

For those who want to solidify their foundational knowledge, our Java course offers a deep dive into the language's fundamentals and features.

Conclusion

The path to becoming a skilled Java programmer is built on a foundation of consistent practice with basic Java programs and progressively harder examples. By working through these programs, you are learning how to think like a programmer. Each challenge, from a simple "Hello, World!" to a more complex database connection, sharpens your problem-solving abilities and prepares you for the real-world tasks you will face in your career.

As your confidence grows, you might tackle other fundamental areas, perhaps by building a Java calculator program to practice handling user input and arithmetic operations, exploring Java recursion examples to understand alternative ways to solve problems like factorials, or learning how programs interact with data persistence through Java file I/O examples.

Remember the engineers at Netflix. Their ability to diagnose and fix a critical issue with a brand-new technology came from a deep-seated understanding of the fundamentals. Keep practicing, stay curious, and continue building on your knowledge. The opportunities in the world of Java development are vast, and with a strong foundation, you will be well-equipped to seize them.

Key Takeaways

  • Working through basic programs on loops, strings, and arrays is essential before tackling more complex software
  • Each program is chosen to teach a specific, practical concept, such as data validation, algorithm design, or object-oriented principles
  • Simple exercises, such as checking for a palindrome, are directly applicable to real-world tasks, such as validating user input in web applications
  • A portfolio of practice programs clearly demonstrates your problem-solving skills to employers, opening opportunities in software development and engineering

FAQs

1. What should my first Java project be?

Your first Java project should be simple enough to reinforce the basics. A basic calculator, a number guessing game, or a simple to-do list application are excellent choices. They help you get familiar with core concepts like variables, user input, and conditional logic without being overwhelming.

2. What are some real-world projects I can build with Java?

Real-world Java projects often involve live data and complex interactions. Examples include an e-commerce platform, an online voting system, a chat application, or an airline reservation system. These projects require a strong understanding of database connectivity, networking, and Spring.

3. Is Java a good language for beginners?

Yes, Java is an excellent choice for beginners. Its syntax is relatively clear, and its strict, object-oriented nature enforces good programming habits from the start. The large, supportive community and vast number of learning resources also make it easier for newcomers to find help and guidance.

4. Which Java framework should I learn first?

For building web applications, Spring is highly recommended as the first framework to learn. It is the most widely used framework in the industry, particularly Spring Boot, which simplifies the process of building production-ready applications. Hibernate is another crucial framework to learn for database interaction.

5. What is the difference between Java and JavaScript?

Though their names are similar, Java and JavaScript are two completely different languages. Java is a compiled, object-oriented programming language often used for back-end development, Android apps, and large-scale enterprise systems. JavaScript is an interpreted scripting language that primarily runs in web browsers to create interactive front-end experiences. However, it can also be used on the back-end with environments such as Node.js.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Full Stack Development Program with Generative AI

Cohort Starts: 13 Nov, 2025

20 weeks$4,000
Full Stack Java Developer Masters Program

Cohort Starts: 24 Nov, 2025

7 months$1,449
AI-Powered Automation Test Engineer Program8 months$1,499

Get Free Certifications with free video courses

  • Getting Started with Full Stack Development

    Software Development

    Getting Started with Full Stack Development

    12 hours4.567K learners
  • Full-Stack Development 101

    Software Development

    Full-Stack Development 101

    1 hours4.525.5K learners
prevNext

Learn from Industry Experts with free Masterclasses

  • Key 2025 Software Development Trends- Learn How To Leverage them for your career

    Software Development

    Key 2025 Software Development Trends- Learn How To Leverage them for your career

    9th Dec, Monday9:30 PM IST
  • Must-Know Full Stack Java Dev Career Trends for 2024

    Software Development

    Must-Know Full Stack Java Dev Career Trends for 2024

    6th Aug, Tuesday9:00 PM IST
  • Full Stack Java Development: A 2024 Blueprint for Recession-Proofing Your Career

    Software Development

    Full Stack Java Development: A 2024 Blueprint for Recession-Proofing Your Career

    27th Jun, Thursday7:30 PM IST
prevNext