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.
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.
Palindrome
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.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;
}
}
}
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:
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)); } }
|
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 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.
Consider Simplilearn’s Post Graduate Program in Full Stack Web Development which can help you fast trcak your career .
Wherever your software development interests lie, Simplilearn has the program for you. Visit the course listings today and take charge of your developer career!