Best Java Programs for Beginners and Experienced Programmers

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!

Contents

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

   }

}

Source

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

  }

}

Source

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

  }

}

Source

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

  }

}

Source

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

  }

}

Source

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

   }

}    

Source

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;

        }

    }

}

Source

Get the Coding Skills You Need to Succeed

Full Stack Development-MEANExplore Program

Get the Coding Skills You Need to Succeed

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

  }

}

Source

Heap Sort:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

 

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–){

        heapify(arr,i,arr.length-1);

      }

   }

   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]){

      max=left;

      } else {

      max=i;

      }

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

      max=right;

      }

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

 

      buildheap(arr);

      int sizeOfHeap=arr.length-1;

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

      exchange(arr,0, i);

      sizeOfHeap=sizeOfHeap-1;

      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(Arrays.toString(arr));

      arr=heapSort(arr);

      System.out.println(“=====================”);

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

      System.out.println(Arrays.toString(arr));

   }

}

 

Source

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

      }

    }

  }

}

Source

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

  }

}

Source

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.             this.data = data;  
  8.         }  
  9.     }  
  10.   
  11.     //Declaring head and tail pointer as null.  
  12.     public Node head = null;  
  13.     public Node tail = null;  
  14.   
  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.             newNode.next = head;  
  25.         }  
  26.         else {  
  27.             //tail will point to new node.  
  28.             tail.next = newNode;  
  29.             //New node will become new tail.  
  30.             tail = newNode;  
  31.             //Since, it is circular linked list tail will point to head.  
  32.             tail.next = head;  
  33.         }  
  34.     }  
  35.   
  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(” “+ current.data);  
  47.                 current = current.next;  
  48.             }while(current != head);  
  49.             System.out.println();  
  50.         }  
  51.     }  
  52.   
  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. }  

Source

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

Source

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. They are designed to give you a solid understanding of front-end, middleware, and back-end Java web developer technologies. With these programs, 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.

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

#Java #Programs #Beginners #Experienced #Programmers

Leave a Reply

Your email address will not be published. Required fields are marked *