The Best Java Programs for Beginners and Experienced Programmers to Practice and Upskill

As the adage goes, “practice makes perfect.” This piece of wisdom is true in so many aspects of life, including the world of IT. People who want to become good Java programmers need to 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 Java language basics and more complex programs for expert Java programmers expanding their skillset. 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. This includes 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 up to date on the latest procedures and processes.

If you, as an employee, practice upskilling, you become more valuable. 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 who’s not getting compensated commensurate with your skillset, your newfound skills potentially make you a very desirable catch for another company!

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

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

What Are Some Java Basic Programs?

Let’s begin with a collection of seven basic Java programs, perfect for the neophyte programmer. You can find the actual code later in the article. If you’re still learning your way around 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.


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

Garbage Collection

This program has nothing to do with 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. Note that the code example below uses the GregorianCalendar class.

Fibonacci Series

The Fibonacci Sequence is a series of numbers where each number is the sum of the two numbers preceding it. So, this advanced program calculates the series.

What Are Some Advanced Java Programs?

If you’ve mastered the basic Java programs, then 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 there are more efficient algorithms available. For example, this approach isn't efficient when using sparse matrices, which contain a significant number of elements listed as zero.

Remove Elements from an ArrayList

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

Implementing HashMap

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

Circular LinkedList Program

This Java program prints the nodes found 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 tasked with managing the database. The procedure mostly involves opening a connection, building a SQL Database, executing any SQL queries, and at last arriving at the output. 

Java Program Code Examples

We’ve broken down 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.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(;

    x = in.nextInt();

    if (x % 2 == 0)

      System.out.println("The number is even.");


      System.out.println("The number is odd.");





import java.util.*;

class Palindrome


  public static void main(String args[])


    String original, reverse = ""; // Objects of String class

    Scanner in = new Scanner(;

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


      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());


    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;





Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

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




         last = middle - 1;

      middle = (first + last)/2;


   if (first > last)

      System.out.println(search + " isn't present in the list.\n");




Heap Sort:




































































package org.arpit.java2blog;

import java.util.*;

public class HeapSortMain {

   public static void buildheap(int []arr) {



  * As last non leaf node will be at (arr.length-1)/2

  * so we will start from this location for heapifying the elements

  * */

    for(int i=(arr.length-1)/2; i>=0; i--){




   public static void heapify(int[] arr, int i,int size) {

      int left = 2*i+1;

      int right = 2*i+2;

      int max;

      if(left <= size && arr[left] > arr[i]){


      } else {



      if(right <= size && arr[right] > arr[max]) {



      // If max is not current node, exchange it with max of left and right child

      if(max!=i) {

      exchange(arr,i, max);

      heapify(arr, max,size);



   public static void exchange(int[] arr,int i, int j) {

        int t = arr[i];

        arr[i] = arr[j];

        arr[j] = t;


   public static int[] heapSort(int[] arr) {



      int sizeOfHeap=arr.length-1;

      for(int i=sizeOfHeap; i>0; i--) {

      exchange(arr,0, i);


      heapify(arr, 0,sizeOfHeap);


      return arr;


   public static void main(String[] args) {

      int[] arr={1,10,16,19,3,5};

      System.out.println("Before Heap Sort : ");




      System.out.println("After Heap Sort : ");






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



      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++)








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>();







    System.out.println("Original List- " + cityList);



    System.out.println("List after removing elements- " + cityList);




Circular LinkList Program:

  1. public class CreateList {  
  2.     //Represents the node of list.  
  3.     public class Node{  
  4.         int data;  
  5.         Node next;  
  6.         public Node(int data) {  
  7.    = data;  
  8.         }  
  9.     }  
  11.     //Declaring head and tail pointer as null.  
  12.     public Node head = null;  
  13.     public Node tail = null;  
  15.     //This function will add the new node at the end of the list.  
  16.     public void add(int data){  
  17.         //Create new node  
  18.         Node newNode = new Node(data);  
  19.         //Checks if the list is empty.  
  20.         if(head == null) {  
  21.              //If list is empty, both head and tail would point to new node.  
  22.             head = newNode;  
  23.             tail = newNode;  
  24.    = head;  
  25.         }  
  26.         else {  
  27.             //tail will point to new node.  
  28.    = newNode;  
  29.             //New node will become new tail.  
  30.             tail = newNode;  
  31.             //Since, it is circular linked list tail will point to head.  
  32.    = head;  
  33.         }  
  34.     }  
  36.     //Displays all the nodes in the list  
  37.     public void display() {  
  38.         Node current = head;  
  39.         if(head == null) {  
  40.             System.out.println("List is empty");  
  41.         }  
  42.         else {  
  43.             System.out.println("Nodes of the circular linked list: ");  
  44.              do{  
  45.                 //Prints each node by incrementing pointer.  
  46.                 System.out.print(" "+;  
  47.                 current =;  
  48.             }while(current != head);  
  49.             System.out.println();  
  50.         }  
  51.     }  
  53.     public static void main(String[] args) {  
  54.         CreateList cl = new CreateList();  
  55.         //Adds data to the list  
  56.         cl.add(1);  
  57.         cl.add(2);  
  58.         cl.add(3);  
  59.         cl.add(4);  
  60.         //Displays all the nodes present in the list  
  61.         cl.display();  
  62.     }  
  63. }  


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;


      //STEP 2: Register 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


         //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




   }catch(SQLException se){

      //Handle errors for JDBC


   }catch(Exception e){

      //Handle errors for Class.forName



      //finally block used to close resources




      }catch(SQLException se2){

      }// nothing we can do




      }catch(SQLException se){


      }//end finally try

   }//end try


}//end main

}//end FirstExample


Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Are You Interested in Becoming a Java Full Stack Web Developer?

Full stack developers are in big demand again, which means now’s the time to launch that new career in development. In these days of economic uncertainty, you want a career that offers job security and appropriate compensation, and full-stack development is that kind of career. According to Glassdoor, Java full-stack developers earn an average yearly salary of USD 79,137. Meanwhile, Payscale reports that a Java full-stack developer in India can earn an annual income of ₹595,973 on average.

Simplilearn provides you with the resources necessary to make your dreams of becoming a full-stack developer into a reality. The Full Stack Java Developer master’s program is designed to give you a solid understanding of front-end, middleware, and back-end Java web developer technologies. With this program, you will gain the know-how to build end-to-end applications, test and deploy code, use MongoDB to store data, and much more.

You will benefit from over 250 hours of applied learning, 20 lesson-end and a half-dozen phase-end projects, and over 30 in-demand tools and skills. You will master the most in-demand skills in the IT development industry, including Angular, Hibernate, Servlets, Spring Boot, and JSPs, in addition to MVC, web services, and SOA to help you build highly web scalable apps.

Once you finish the master’s program, consider Simplilearn’s Post Graduate Program in Full Stack Web Development, a global online coding bootcamp offered in collaboration with Caltech CTME.

If you’re interested in full-stack development but want to work with something other than Java, Simplilearn has you covered. You can take the Full Stack Developer - MEAN Stack Master’s Program and bolster your career as a MEAN stack developer. On the other hand, if you want to learn about software testing, you can benefit from Simplilearn’s Automation Test Engineer Master’s Program.

Wherever your software development interests lie, Simplilearn has the program for you. Visit the course listings today and take charge of your developer career!

About the Author


Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.