Basic Java Code Examples for Beginners

java code examplesJava 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:

 

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

 

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 Java Calculator");

System.out.println("===========================");

 

System.out.print("Enter First Number:");

int num1 = userinput.nextInt();

 

System.out.print("Enter 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 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:

 

import java.util.Scanner;

 

public class MyClass {

public int fact(int n)

{

if (n==1)

{

return n;

}

else

{

n = n * fact(n-1);

return n;

}

}

 

public static void main(String[] args) {

MyClass test = new MyClass();

Scanner userinput = new Scanner(System.in);

System.out.print("Enter the number to find factorial: ");

int num = 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:

import java.util.Scanner;

 

public class MyClass {

public boolean numberIsPrime(int n)

{

for(int i = 2; i<n; i++)

{

if ( n%i == 0)

returnfalse;

}

returntrue;

}

 

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