Tim Buchalka

Java is an object-oriented language used to develop a wide variety of applications. These include applications like simple desktop address books, enterprise level ERP systems, complex dynamic websites, and mobile applications for Android. Java is portable and can run on various platforms, including Linux, Windows, and Mac.

Developed on the principle of Write Once Run Anywhere (WORA), Java is a great place to jump into the exciting world of programming. Learning Java is highly recommended for software developers who want to add to their development skills. This is because it is one of the most popular programming languages in the world.

Java Programming Masterclass covering Java 11 & Java 17

Last Updated August 2021

Bestseller
  • 401 lectures
  • All Levels
4.6 (149,715)

Learn Java In This Course And Become a Computer Programmer. Obtain valuable Core Java Skills And Java Certification | By Tim Buchalka, Tim Buchalka’s Learn Programming Academy

Explore Course

This article contains some basic and interesting Java code examples for beginners. These Java tutorials will help the reader understand the basic features of any Java application.

1. A basic java calculator

The following code example is a simple calculator application in Java. The code takes input from the console using one of the four mathematical operations (add, subtract, multiply, and divide) and then displays the output on the console.

The application makes use of a Maths Java class which contains four methods. The methods perform each of the four mathematical operations and return the result to the calling method.

The definition of the Maths class looks like this:

public class Maths {

    public int Add (int num1, int num2)
    {
        return num1 + num2;
    }

    public int Subtract (int num1, int num2)
    {
        return num1 - num2;
    }
    public int Multiply (int num1, int num2)
    {
        return num1 * num2;
    }
    public int Divide (int num1, int num2)
    {
        return num1 / num2;
    }
}

You can see from the above code that all the methods in the code return integer values, and all of them take two integer data type parameters. 

To make use of the Maths class for performing mathematical functions, its object has to be created, and then you can call the methods from that object. The following code snippet demonstrates how a calculator application actually works.

import java.util.Scanner;

public class MyClass {

    public static void main(String[] args) {
        Maths math = new Maths();
        Scanner userInput = new Scanner(System.in);

        System.out.println("Welcome to the Java Calculator");
        System.out.println("==============================");

        System.out.print("Enter the first number:");
        int num1 = userInput.nextInt();

        System.out.print("Enter the second number:");
        int num2= userInput.nextInt();

        System.out.print("Enter operation to perform (+,-,x,/):");
        String operation= userInput.next();

        if (operation.equals("+"))
            System.out.println(math.Add(num1, num2));

        else if (operation.equals("-"))
            System.out.println(math.Subtract(num1, num2));

        else if (operation.equals("x"))
            System.out.println(math.Multiply(num1, num2));

        else if (operation.equals("/"))
            System.out.println(math.Divide(num1, num2));
        else
            System.out.println("The operation is not valid.");
    }
}

If you look closely at the above code snippet, a package named java.util.Scanner has been imported at the beginning of the code. This Scanner class allows scanning or reading console input. It includes the ability to read from files, but also from the keyboard.

In the main method of the class, the object of Maths class has been declared. Then, using the Scanner class object, the first number, second number, and operation to be performed are retrieved from the user. Finally, the string comparison of the operation is performed using the equals method. This is to decide which method of the Maths class will be called.

If the matched string is “+,” the Add method of the Maths class will be called.  If the matched string is “-,” then the Subtract method is called, and so on. The numbers taken as input from the users will be passed to the relevant method to be processed and the answer returned and printed out.

A sample run of the program is shown below.

Welcome to Java Calculator
===========================
Enter First Number:10
Enter Second Number:20
Enter operation to perform (+,-,x,/):+
30

Process finished with exit code 0

The addition of 20 to 10 gives the answer 30 in the output displayed.

2. Calculating factorial using recursive functions in Java

The second code example demonstrates how a factorial of any number can be calculated using a recursive method in Java. A recursive method in Java is a method that keeps calling itself until a particular condition is met. 

The following code snippet demonstrates the use of recursion within a Java method to calculate a factorial of a user entered number:

public int factorial(int f) {
        if(f == 1) {
            return f;
        } else {
            f = f * factorial(f - 1);
            return f;
        }
    }

And this is the code that asks the user to enter the number and calls and outputs the result of calling the factorial method:

 public static void main(String[] args) {
        MyClass test = new MyClass();
        Scanner userInput = new Scanner(System.in);
        System.out.print("Enter the number to find the factorial for: ");
        int factorialNumber = userInput.nextInt();
        System.out.println("The factorial of " + factorialNumber + " is: " + test.factorial(factorialNumber));
    }

Both methods would be added to a class in order to allow them to be executed. Here is the full listing:

import java.util.Scanner;

public class MyClass {

    public static void main(String[] args) {
        MyClass test = new MyClass();
        Scanner userInput = new Scanner(System.in);
        System.out.print("Enter the number to find the factorial for: ");
        int factorialNumber = userInput.nextInt();
        System.out.println("The factorial of " + factorialNumber + " is: " + test.factorial(factorialNumber));
    }

    public int factorial(int f) {
        if(f == 1) {
            return f;
        } else {
            f = f * factorial(f - 1);
            return f;
        }
    }

}

In the above code, the factorial method in the class MyClass is the recursive function that keeps on calling itself. The method will stop executing when the value of the passed parameter is less than or equal to one. If it is, the program returns to the calling method call. Otherwise, the factorial method calls itself with the value one less than the value passed to this method invocation.

This is a sample of the output:

Enter the number to find the factorial for: 11
The factorial of 11 is: 39916800

Process finished with exit code 0

3. Displaying first ‘n’ prime numbers

The last code example demonstrates how the first ‘n’ prime numbers can be calculated where ‘n’ is any number. For instance, if the user specifies ‘n’ as 5, the first five prime numbers starting from 2 and ending at 11 would be displayed.

This is because the first five numbers are 2,3, 5, 7, and 11.

The code of the application is as follows:

import java.util.Scanner;

public class MyClass {
    public boolean numberIsPrime(int n) {
        for (int i = 2; i < n; i++) {
            if (n % i == 0)
                return false;
        }
        return true;
    }

    public static void main(String[] args) {
        MyClass test = new MyClass();
        Scanner userInput = new Scanner(System.in);
        System.out.print("Enter the number of primes to be displayed: ");
        int num = userInput.nextInt();

        int count = 0;
        for (int i = 2; count < num; i++) {
            if (test.numberIsPrime(i)) {
                System.out.print(i + " ");
                count++;
            }

        }
    }
}

A method named numberIsPrime takes an integer type number and checks if it is a prime number. If the number passed to the method is not prime, it returns false. Otherwise, it returns true.

In the main method, a number is obtained from the user using the console. Starting from the number 2, the program starts checking if every integer number is a prime number. If it is a prime number, the number is output, and a count of found prime numbers is incremented. This continues until it reaches the number of prime numbers requested by the user, after which the program terminates.

Here is a sample run of the program:

Enter the number of primes to be displayed: 5
2 3 5 7 11 
Process finished with exit code 0

To learn more about Java programming, you can check out how to learn Java and how to get Java certifications.

Top courses in Java

Java Programming for Complete Beginners
in28Minutes Official
4.5 (19,728)
Complete Core Java In Simple Way
DURGASOFT NAGOOR BABU
4.5 (309)
Java Message Service - JMS Fundamentals
Bharath Thippireddy
4.6 (1,075)
The Complete Java Development Bootcamp
Learn The Part Inc., Rayan Slim, Jad Slim
4.7 (293)
Java Programming Masterclass covering Java 11 & Java 17
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.6 (149,715)
Bestseller
The Complete Java Certification Course
Imtiaz Ahmad
4.5 (15,899)
Design Patterns in Java
Dmitri Nesteruk
4.3 (5,930)
Java Interview Guide : 200+ Interview Questions and Answers
in28Minutes Official
4.4 (5,010)
Bestseller

More Java Courses

Java students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.

Request a demo

Courses by Tim Buchalka

Java Programming Masterclass covering Java 11 & Java 17
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.6 (149,715)
Bestseller
Android Java Masterclass - Become an App Developer
Tim Buchalka, Jean-Paul Roberts, Tim Buchalka's Learn Programming Academy
4.5 (9,719)
Learn Python Programming Masterclass
Tim Buchalka, Jean-Paul Roberts, Tim Buchalka's Learn Programming Academy
4.5 (82,394)
Android App Development Masterclass using Kotlin
Tim Buchalka, Jean-Paul Roberts, Tim Buchalka's Learn Programming Academy, David Reidy
4.3 (5,126)
Java Spring Tutorial Masterclass - Learn Spring Framework 5
Tim Buchalka, Tim Buchalka's Learn Programming Academy, Goran Lochert
4.6 (5,647)
Learn C# for Beginners Crash Course
Tim Buchalka, Jean-Paul Roberts, Tim Buchalka's Learn Programming Academy
4.5 (1,108)
Learn Java Programming Crash Course
Tim Buchalka, Goran Lochert, Tim Buchalka's Learn Programming Academy
4.6 (2,118)
Data Structures and Algorithms: Deep Dive Using Java
Tim Buchalka, Goran Lochert, Tim Buchalka's Learn Programming Academy
4.5 (10,395)
Bestseller
Kotlin for Java Developers
Tim Buchalka, Goran Lochert, Tim Buchalka's Learn Programming Academy
4.5 (2,811)
Java SE 11 Developer 1Z0-819 OCP Course - Part 1
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.5 (2,112)
Bestseller
Java SE 11 Developer 1Z0-819 OCP Course - Part 2
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.4 (493)
Introduction to Continuous Integration & Continuous Delivery
Tim Buchalka, Tim Buchalka's Learn Programming Academy, Eduardo Rosas
4.3 (1,209)

Courses by Tim Buchalka