# Basic Java Code Examples for Beginners

Java is an object-oriented language used to develop variety of applications ranging from simple desktop address books, enterprise level ERP systems, and complex dynamic websites to mobile based applications for android. Learning Java is essential for stepping up in the path of software development owing to its major market share. Java is portable and can run on variety of platforms including Linux, Windows and Mac. Developed on the principle of Write Once Run Anywhere (WORA), Java is often considered the best place to jump into the exciting world of programming. This article contains some basic and interesting Java code examples for beginners. These examples are good enough to understand the basic feature of any Java application.

For in-depth Java tutorials, take a course at Udemy.com.

**1- ****A Basic Java Calculator**

The following code example is a simple calculator application in Java that takes input from a user through console along with one of the four mathematical operations i.e. Add, Subtract, Multiple and Divide and then display the output on the console.

The application makes use of a Maths class which contains four functions that perform four mathematical operations and return the result to the calling function. The definition of the Maths class looks like this:

publicclassMaths {publicintAdd (intnum1,intnum2) {returnnum1 + num2; }publicintSubtract (intnum1,intnum2) {returnnum1 - num2; }publicintMultiply (intnum1,intnum2) {returnnum1 * num2; }publicintDivide (intnum1,intnum2) {returnnum1 / num2; } }

You can see from the above code that all the methods in the above code return integer values and all of them take two integer type parameters. To make use of the Maths class for performing mathematical function, its object has to be created and then the methods can be called from that object. The following code snippet demonstrates that how a calculator application actually performs.

importjava.util.Scanner;publicclassMyClass {publicstaticvoidmain(String[] args) { Maths math =newMaths(); Scanner userinput =newScanner(System.in); System.out.println("Welcome to Java Calculator"); System.out.println("==========================="); System.out.print("Enter First Number:");intnum1 = userinput.nextInt(); System.out.print("Enter Second Number:");intnum2= userinput.nextInt(); System.out.print("Enter operation to perform (+,-,x,/):"); String operation= userinput.next();if(operation.equals("+")) System.out.println(math.Add(num1, num2));elseif(operation.equals("-")) System.out.println(math.Subtract(num1, num2));elseif(operation.equals("x")) System.out.println(math.Multiply(num1, num2));elseif(operation.equals("/")) System.out.println(math.Divide(num1, num2));elseSystem.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 console input. 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 has been obtained from the user. Finally, the string comparison of the operation has been performed using equals method. This is to decide which method of the Maths class has to be called. If the matched string is “+”, the Add method of the Maths class would be called. The numbers taken as input from the users will be passed to this method. One instance of the output of the above code is as follows:

Welcome to Java Calculator

===========================

Enter First Number:500

Enter Second Number:10

Enter operation to perform (+,-,x,/):/

50

The division of 500 by 10 yields 50 that have been displayed on the console output.

To learn Java concepts in detail, take a course at Udemy.com.

**2- ****Calculating Factorial using recursive functions in Java**

The second code example demonstrates that how factorial of any number can be calculated via recursive functions in Java. A recursive function in Java is a function that keeps calling itself until a particular condition becomes valid in which case, the function executes. The following code snipped demonstrates the usage of recursive function for calculating factorial of a number:

importjava.util.Scanner;publicclassMyClass {publicintfact(intn) {if(n==1) {returnn; }else{ n = n * fact(n-1);returnn; } }

publicstaticvoidmain(String[] args) { MyClass test =newMyClass(); Scanner userinput =newScanner(System.in); System.out.print("Enter the number to find factorial: ");intnum = userinput.nextInt(); System.out.println("The factorial of " +num+" is: "+test.fact(num)); } }

In the above code, the fact function in class MyClass is the recursive function that keeps on calling itself. The terminating condition in the fact function is that when the passed parameter which is integer type n, becomes 1. In that case, the function executes. The output instance of the above code is as follows:

Enter the number to find factorial: 6

The factorial of 6 is: 720

**3- ****Displaying first ‘n’ Prime Numbers**

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

importjava.util.Scanner;publicclassMyClass {publicbooleannumberIsPrime(intn) {for(inti = 2; i<n; i++) {if( n%i == 0)returnfalse; }returntrue; }publicstaticvoidmain(String[] args) { MyClass test =newMyClass(); Scanner userinput =newScanner(System.in); System.out.print("Enter the number of primes to be displayed: ");intnum = userinput.nextInt();intcount = 0;for(inti =2; i>0; i++) {if(test.numberIsPrime(i) && count<num) { System.out.print(i +" "); count++; } } } }

A method named numberIsPrime has been defined which takes an integer type number and checks if it is prime or not. If the number is note prime, it returns false and if number is prime, it returns true. In the main function, a number is obtained from the user and every time a prime number is displayed another variable count is incremented. The numbers are displayed until count is becomes equal to the number specified by the user. The output of the above application is as follows:

Enter the number of primes to be displayed: 5

2 3 5 7 11

For more detailed Java tutorials, take a course at Udemy.com.

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