# Learn To Write Java With Java Code Examples

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.

Last Updated November 2022

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 CourseThis 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.

## Recommended Articles

### Top courses in Java

### 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 Business.