As the adage goes, “practice makes perfect.” This wisdom is true in so many aspects of life, including IT. People who want to become good Java programmers must practice their skills and become familiar with Java language basics. Experienced Java programmers who wish to upskill need to try out the new programming skills they’ve learned.

This article includes some of the best Java programs for newbies who want to practice the Java language basics and more complex programs for expert Java programmers who want to expand their skills. We’re here to help Java programmers of all levels!

The Advantages of Upskilling

Upskilling is defined as the practice of teaching employees new skills, including self-learning. When professionals embark on a career, they’re in that profession for the long haul, as opposed to someone just accepting any old job offered to them with no thought of the future. However, a professional pursuing a career cannot remain static. Like a shark, they must keep swimming and moving forward.

Upskilling helps career employees improve and expand their skill sets. Employees who regularly practice upskilling have an easier time staying current and relevant, keeping current on the latest procedures and processes.

As an employee, you become more valuable if you practice upskilling. Improving your skills means you are more likely to get promoted. Companies don’t want to lose highly skilled workers. Of course, if you’re an employee not getting compensated commensurate with your skill set, your newfound skills potentially make you a desirable catch for another company!

But no matter how much you upskill, you must practice and try your new skills. So, let’s start with some basic Java programs for beginners and then move on to the more advanced ones for experienced Java programmers.

What Are Some Java Basic Programs?

Let’s begin with seven basic Java programs, perfect for the neophyte programmer. You can find the actual code later in the article. If you’re still learning Java’s fundamentals, you should consider a Java Certification Training Course to provide you with a solid foundation in Java.

Hello World

Let’s start things off with a greeting. This introductory program displays the words “Hello world” on the screen.

Fahrenheit to Celsius

For those nations too stubborn to adopt the metric system (We’re looking at you, USA!), this program converts temperatures from the Fahrenheit scale to the Centigrade/Celsius scale.

Find Odd or Even

This basic program checks whether a number is even or odd.

Palindrome

A palindrome is a word spelt the same backwards and forward. For example, “pop” is a palindrome. “Wombat” is not.

Garbage Collection

This program does not involve the household chore of taking out the trash. In programmer terms, “garbage collection” frees up memory in a Java virtual machine.

Display Date and Time

This program prints or displays the current time and date.

Fibonacci Series

The Fibonacci Sequence is a series of numbers in which each number is the sum of the two numbers preceding it. This advanced program calculates the series.

Recommended Read: Java Interview Questions and Answers

What Are Some Advanced Java Programs?

If you’ve mastered the basic Java programs, it’s time to move up to this collection of seven advanced Java programming examples.

Binary Search Algorithm Implementation

This search algorithm finds the position of a target value within a sorted array. A binary search compares a target value to the center element of an array.

Heap Sort

This program is a comparison-based sorting technique based on the Binary Heap data structure. It’s like a selection sort, where we initially find the maximum element and then place it at the end, repeating the process for the remaining values.

Matrix Multiplication

This Java program multiplies two matrices. Before multiplication, we must check whether they can be multiplied. This program uses the simplest multiplication method, and more efficient algorithms are available. For example, this approach isn't efficient when using sparse matrices, which contain many elements listed as zero.

Remove Elements from an ArrayList

ArrayList implements a list interface where elements may be added or removed dynamically from the original list. If added elements exceed the initial list size, the list is dynamically expanded.

Implementing HashMap

This program implements HashMap, a map-based collection class for storing key and value pairs. However, the class cannot guarantee map order. HasMap resembles HashTable, except it’s unsynchronized and allows NULLs.

Circular LinkedList Program

This Java program prints the nodes in the circular LinkedList, using the “first things first” approach. In this case, the node is divided into two parts, “data” and “next,” and is an element of the list. “Data” covers the information stored in the node, and “next” functions as the pointer to the next node.

SQL Database Connectivity Program

This advanced application program interface (API) allows you to encode access request statements in Structured Query Language (SQL). The access statements are then moved to the program managing the database. The procedure mostly involves opening a connection, building an SQL Database, executing any SQL queries, and finally arriving at the output.

Java Program Code Examples

We’ve broken these Java code examples into Basic and Advanced Java programs. They relate to the above-listed Basic and Advanced programs.

Basic Java Program Codes

Hello World

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

Fahrenheit to Celsius

import java.util.*;
class FahrenheitToCelsius {
  public static void main(String[] args) {
    float temperature;
    Scanner in = new Scanner(System.in);
    System.out.println("Enter temperature in Fahrenheit");
    temperature = in.nextInt();
    temperature = ((temperature - 32)*5)/9;
    System.out.println("temperature in Celsius = " + temperature);
  }
}

Find Odd or Even

import java.util.Scanner;
class OddOrEven
{
  public static void main(String args[])
  {
    int x;
    System.out.println("Enter an integer to check if it's odd or even");
    Scanner in = new Scanner(System.in);
    x = in.nextInt();
    if (x % 2 == 0)
      System.out.println("The number is even.");
    else
      System.out.println("The number is odd.");
  }
}

Palindrome

import java.util.*;
class Palindrome
{
  public static void main(String args[])
  {
    String original, reverse = ""; // Objects of String class
    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.");
  }
}

Garbage Collection

import java.util.*;
class GarbageCollection
{
  public static void main(String s[]) throws Exception
  {
    Runtime rs = Runtime.getRuntime();
    System.out.println("Free memory in JVM before Garbage Collection = "+rs.freeMemory());
    rs.gc();
    System.out.println("Free memory in JVM after Garbage Collection = "+rs.freeMemory());
  }
}

Display Date and Time

import java.util.*;
class GetCurrentDateAndTime
{
   public static void main(String args[])
   {
      int day, month, year;
      int second, minute, hour;
      GregorianCalendar date = new GregorianCalendar();
      day = date.get(Calendar.DAY_OF_MONTH);
      month = date.get(Calendar.MONTH);
      year = date.get(Calendar.YEAR);
      second = date.get(Calendar.SECOND);
      minute = date.get(Calendar.MINUTE);
      hour = date.get(Calendar.HOUR);
      System.out.println("Current date is  "+day+"/"+(month+1)+"/"+year);
      System.out.println("Current time is  "+hour+" : "+minute+" : "+second);
   }
}

Fibonacci Series

public class JavaExample {
    public static void main(String[] args) {
        int count = 7, num1 = 0, num2 = 1;
        System.out.print("Fibonacci Series of "+count+" numbers:");
        for (int i = 1; i <= count; ++i)
        {
            System.out.print(num1+" ");
            /* On each iteration, we are assigning second number
             * to the first number and assigning the sum of last two
             * numbers to the second number
             */
            int sumOfPrevTwo = num1 + num2;
            num1 = num2;
            num2 = sumOfPrevTwo;
        }
    }
}
Become job-ready by opting for the decade's hottest career option. Score your dream job in no time by enrolling in our Full Stack Java Developer Program Today!

Advanced Java Program Codes

Binary Search Algorithm Implementation

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");
    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.");
  }
}

Heap Sort

public class HeapSort {
    // Method to build a max heap
    public void heapify(int arr[], int n, int i) {
        int largest = i; // Initialize largest as root
        int left = 2 * i + 1; // Left child index
        int right = 2 * i + 2; // Right child index
        // If left child is larger than root
        if (left < n && arr[left] > arr[largest])
            largest = left;
        // If right child is larger than the largest so far
        if (right < n && arr[right] > arr[largest])
            largest = right;
        // If the largest is not the root
        if (largest != i) {
            int swap = arr[i];
            arr[i] = arr[largest];
            arr[largest] = swap;
            // Recursively heapify the affected subtree
            heapify(arr, n, largest);
        }
    }
    // Main method to perform heap sort
    public void heapSort(int arr[]) {
        int n = arr.length;
        // Build the max heap
        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);
        // Extract elements one by one from the heap
        for (int i = n - 1; i > 0; i--) {
            // Move the current root to the end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;
            // Call max heapify on the reduced heap
            heapify(arr, i, 0);
        }
    }
    // Utility method to print the array
    public void printArray(int arr[]) {
        int n = arr.length;
        for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");
        System.out.println();
    }
    // Main method to run the program
    public static void main(String args[]) {
        int arr[] = {12, 11, 13, 5, 6, 7};
        HeapSort heapSort = new HeapSort();
        System.out.println("Original array:");
        heapSort.printArray(arr);
        heapSort.heapSort(arr);
        System.out.println("Sorted array:");
        heapSort.printArray(arr);
    }
}

Matrix Multiplication

import java.util.Scanner;
class MatrixMultiplication
{
  public static void main(String args[])
  {
    int m, n, p, q, sum = 0, c, d, k;
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the number of rows and columns of first matrix");
    m = in.nextInt();
    n = in.nextInt();
    int first[][] = new int[m][n];
    System.out.println("Enter elements of first matrix");
    for (c = 0; c < m; c++)
      for (d = 0; d < n; d++)
        first[c][d] = in.nextInt();
    System.out.println("Enter the number of rows and columns of second matrix");
    p = in.nextInt();
    q = in.nextInt();
    if (n != p)
      System.out.println("The matrices can't be multiplied with each other.");
    else
    {
      int second[][] = new int[p][q];
      int multiply[][] = new int[m][q];
      System.out.println("Enter elements of second matrix");
      for (c = 0; c < p; c++)
        for (d = 0; d < q; d++)
          second[c][d] = in.nextInt();
      for (c = 0; c < m; c++) {
        for (d = 0; d < q; d++) {
          for (k = 0; k < p; k++)
            sum = sum + first[c][k]*second[k][d];
          multiply[c][d] = sum;
          sum = 0;
        }
      }
      System.out.println("Product of the matrices:");
      for (c = 0; c < m; c++) {
        for (d = 0; d < q; d++)
          System.out.print(multiply[c][d]+"\t");
        System.out.print("");
      }
    }
  }
}

Remove Elements from an ArrayList

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");
    System.out.println("Original List- " + cityList);
    cityList.remove(1);
    cityList.remove("Mumbai");
    System.out.println("List after removing elements- " + cityList);
  }
}

Circular LinkList Program

public class CreateList {  
    //Represents the node of list.  
    public class Node{  
        int data;  
        Node next;  
        public Node(int data) {  
            this.data = data;  
        }  
    }  
    //Declaring head and tail pointer as null.  
    public Node head = null;  
    public Node tail = null;  
    //This function will add the new node at the end of the list.  
    public void add(int data){  
        //Create new node  
        Node newNode = new Node(data);  
        //Checks if the list is empty.  
        if(head == null) {  
             //If list is empty, both head and tail would point to new node.  
            head = newNode;  
            tail = newNode;  
            newNode.next = head;  
        }  
        else {  
            //tail will point to new node.  
            tail.next = newNode;  
            //New node will become new tail.  
            tail = newNode;  
            //Since, it is circular linked list tail will point to head.  
            tail.next = head;  
        }  
    }  
    //Displays all the nodes in the list  
    public void display() {  
        Node current = head;  
        if(head == null) {  
            System.out.println("List is empty");  
        }  
        else {  
            System.out.println("Nodes of the circular linked list: ");  
             do{  
                //Prints each node by incrementing pointer.  
                System.out.print(" "+ current.data);  
                current = current.next;  
            }while(current != head);  
            System.out.println();  
        }  
    }  
    public static void main(String[] args) {  
        CreateList cl = new CreateList();  
        //Adds data to the list  
        cl.add(1);  
        cl.add(2);  
        cl.add(3);  
        cl.add(4);  
        //Displays all the nodes present in the list  
        cl.display();  
    }  
}

SQL Database Connectivity Program

//STEP 1. Import required packages
import java.sql.*;
public class FirstExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/EMP";
   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";
   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");
      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);
      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);
      //STEP 5: Extract data from result set
      while(rs.next()){
         //Retrieve by column name
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");
         //Display values
         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      }
      //STEP 6: Clean-up environment
      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      }// nothing we can do
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end FirstExample

Are You Interested in Becoming a Full Stack Java Developer?

Mastering Java is a rewarding journey that opens up numerous opportunities in software development, from building simple applications to designing complex systems. Whether you're a beginner looking to strengthen your basics or an experienced programmer honing advanced skills, these Java programs provide a solid foundation to deepen your knowledge and improve your coding proficiency.

If you're ready to advance your Java expertise, consider Simplilearn’s Full Stack Java Developer Masters Program. This comprehensive course covers essential Java skills, web development, and backend frameworks, preparing you for an exciting career as a full-stack developer. Start your journey today and unlock a world of opportunities in Java development.

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
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 18 Dec, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449

Get Free Certifications with free video courses

  • Getting Started with Full Stack Development

    Software Development

    Getting Started with Full Stack Development

    12 hours4.551.5K learners
  • Full-Stack Development 101: What is Full-Stack Development ?

    Software Development

    Full-Stack Development 101: What is Full-Stack Development ?

    1 hours4.415K 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