Java Basic Programs: 5 Simple Examples

By , last updated July 18, 2018

This tutorial explains how to start writing programs in Java with step by step examples and explanation. This is a very simple coding for beginners guide.

We will show 5 basic examples of Java programs: how to print “Hello World!” in Java, how to print numbers from 1 to 10, how to add numbers and take user input, how to print a Christmas Tree pattern with stars in Java and how to reverse a string.

Introduction to Java

Java is the most popular programming language throughout the globe. In Java we write program once and then can execute on multiple operating systems. It is object oriented programming language developed originally by Sun Microsystems and now Oracle.

The concept of Java Virtual Machine (JVM) makes it platform independent language. We can run Java byte code on any platform such as Linux, Windows or Mac OS.

Prerequisite to Java Programming

Let’s start programming in Java, following are the prerequisite for writing and running Java programs in your systems.

  • JDK (Java Development Kit)
  • JRE (Java Runtime Environment)
  • IDE (Integrated Development Environment)

If you are not sure what these are, head to our detailed explanation on how to start programming in Java.

1. Hello World Example in Java

Let’s start writing simple programs in Java. Open your IDE and create a new project called HelloWorld. Create a new class Helloworld and paste the following code there:

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

Explanation of Hello World Example: Showing “Hello World” to the screen is the most basic example of any language. Here’s an example of printing “Hello World!” in C++.

In this example the Helloworld is a reserved word used to declare a class name. While the word public is an access modifier, used to express visibility. Again, static is a keyword which is used to create static methods and objects. Void is the return type of the method and main is the name of method, it is the starting point of the program. System.out is the output class while println() is a method to print statements on screen.

Running Hello World

Now save your program and run. Here is the output that you can see in the console window of your IDE. For this example we use Eclipse IDE:

2. Java Count from 1 to 10

Let’s examine another Java program which prints numbers from 1 to 10 to the screen. We will use Java for loop and create a local variable i that will contain the numbers. The first or initial value of the variable i will be a 0 (zero). We will increment the value of this variable one by one and print out the result:

public class Counting {
	public static void main(String[] args) {
		for(int i=0;i<=10;i++){
			System.out.println(i);
		}
	}
}

Output
Here is the output how it looks in the console window:

3. Add two numbers taking input from user

In this example we will show how to add the numbers in Java where a user inputs the values.

There are several ways to take input from a user in Java.

Take input using Scanner class

Here is an example program where the system asks the user to input 2 numbers and adds them together:

import java.util.Scanner;

public class AddNumbers {
    public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter 1 number:");
        int x = scan.nextInt();

        System.out.println("Enter 2 number:");
        int y=scan.nextInt();
        int z=x+y;

        System.out.println("Sum of x+y = " + z);
    }
}

Output
The output of the program will be an interaction between the system and the user. To run this program we used IntelliJ IDEA Community Addition (free):

User input with BufferedReader example

Here’s another example of a Java program that will take input from a user and add two numbers using a Java object BufferedReader:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class AddNumbers {
    public static void main(String args[]) throws IOException {
        InputStreamReader inp = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(inp);
        System.out.println("Enter 1 number:");
        String text1 = br.readLine();
        int x = Integer.parseInt(text1);

        System.out.println("Enter 2 number:");
        String text2 = br.readLine();
        int y = Integer.parseInt(text2);
        int z=x+y;

        System.out.println("Sum of x+y = " + z);
    }
}

This code may throw several exceptions (IOException during reading operation and ParseException during conversion from String to Integer).

The output will be the same as with the Scanner example.

4. Print patterns in Java

There are millions of patterns you can print with Java. We will print a simple Christmas Tree in this example.

We are already familiar with for loops that we used in a counting example nr.2. This time we are going to use nested for loops to print values in rows and columns to form a Christmas tree:

class ChristmasTree
{
    public static void main(String[] args)
    {
        for(int row=1; row<=5; row++)
        {
            for(int emptySpace=4; emptySpace>=row; emptySpace--)
            {
                System.out.print(" ");
            }
            for(int star=1; star<=(2*row-1); star++)
            {
                System.out.print("*");
            }
            System.out.println(""); //new line
        }
    }
}

In this example we used 2 nested loops: one for each row and 2 loops after each other to print out the stars. The last line System.out.println(""); will take the cursor to the next line or else all the stars will be put on one line.

Output
The output of this pattern program is a set of stars places as a Christmas tree:

5. Java program to reverse a string

“Reverse a string” is a popular interview question for a junior Java developer position.

You can perform the task in different ways. The easiest way is to use a built-in function reverse() in StringBuilder class:

public class ReverseString
{
    public static void main(String[] args)
    {
        String str = "I'm the String to be reversed";

        StringBuilder reverse = new StringBuilder();

        reverse.append(str);
        reverse = reverse.reverse();

        System.out.println(str);
        System.out.println(reverse);
    }
}

Output
The output of this program will be two strings: the initial “I’m the String to be reversed” and the reversed version:

Another way is good as well and is based on simple for-loop:

public class ReverseString
{
    public static void main(String[] args)
    {
        String str = "I'm the String to be reversed";
        String reverse = "";

        for(int i = str.length() - 1; i >= 0; i--)
        {
            reverse = reverse + str.charAt(i);
        }

        System.out.println(str);
        System.out.println(reverse);
    }
}

The output will be the same.

Senior Software Engineer developing all kinds of stuff.

Comments

Be the first to comment.

Leave a Reply


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*