Java Recursion

A method can call itself to perform similar operation on remaining elements of a set or resultants operation in current method call. This process is called recursion and java also support recursion. Java recursion is a tricky way to divide a larger problem into smaller tasks and solve them one by one.

Java recursion example

Multiplication of two numbers is an easy task but multiplication of a range of number is a complex one. We can use recursion to divide this task into small pieces and solve. In following example we will do simple multiplication of of two numbers but with an additional trick that the resultant number will be passed to next call of same method as follows:


public class RecursionExample {
public static void main(String[] args) {
int result = multiply(1,10);
System.out.println(result);
}
public static int multiply(int first, int last) {
if (last >=first) {
int result = last * multiply(first, last-1);
return result;
} else {
return 1;
}
}
}

multiply() function multiply a ranges of numbers starting from first number to last number. It takes two parameters, firs and last. last number is multiplied by resultant of another function call multiply() with difference that it is passed first number as it is but last number decremented by one. multiply() will be called recursively until the next recursive call of multiply() is passed same number as first and last number. Understanding of recurstion is still a bit complex therefore it is suggested to place a debugging point in some advance java IDE like Netbeans and debug the file instead of simply running the file, execute the code line by line and check the value of result variable in multiply() function.

Note: There must be a stopping / halting condition in recursive function otherwise the function will behave like an infinite loop and will never end. In above example we are checking that first is greater than last only then next recursive call is issued otherwise a value is simply returned (1 in this case).

Scope of Variables in Java

Area of a java program where a variable is accessible is called scope of that variable.
Following are important levels of java variable scope:

  1. Method Level Scope
  2. Block Level Scope
  3. Class Level Scope

Method Level Scope

Variable defined in a function can be accessible within that function only. It cannot be called or accessed from outside of that function.

Block Level Scope

Variable defined within a block of curly braces can only be accessed from within this block. It cannot be accessed from outside of that block. However variable defined in a function can be be accessed from any block of a curly braces present in that function provided the block of curly braces is defined after definition of variable. Following example shows an example of block level scope variable:


public class Main {
void display_numbers() {
int size = 50 ;
for( int index = 1; index< size ; index++){
// size is visible here
}
// index is not visible here
// size is visible here
}
}

A block cab of a function, an if statement, else part of if statement, a switch statement, a for loop , a while or do-while loop.

Class Level Scope

Variables declared inside a class but outside of class functions are accessible in class function and outside of class depending access specifier of variable. We will discuss class level scope in detail in later section of this tutorial.

Java function overloading

In java we can define multiple methods with same name but different parameters. When we want to perform same operation on data of different data types then function overloading can be used.

Function overloading with different data types

Following examples shows two different function with same name but different data types:

public class Main {
int calculate_square(int num1) {
int square = num1 * num1 ;
System.out.println("Square of given integer: " + square);
}
float calculate_square(float num1) {
float square = num1 * num1 ;
System.out.println("Square of given floating point number: " + square);
}
public static void main(String[] args) {
Main obj = new Main();
// calling overloaded function for an integer
obj.calculate_square(80);
//calling overloading function for a floating point number
obj.calculate_square(53.25);
}
}

Java function overloading with different number of parameters

 

Following example shows two different functions with same name but different number of parameters:


public class Main {
int add(int num1, int num2) {
int sum = num1 + num1 ;
System.out.println("Sum of given numbers: " + sum);
}
int add(int num1, int num2,int num2) {
int sum = num1 + num1 + num2 ;
System.out.println("Sum of given numbers: " + sum);
}
public static void main(String[] args) {
Main obj = new Main();
// calling overloaded function for two parameters
obj.sum(52,63);
//calling overloading function for three parameters
obj.sum(53, 25, 86);
}
}

Java Functions Parameters and Arguments

We can pass data to java functions using parameters. Parameters are list of coma separated variables provided to a function in the parentheses. We can provide as many parameters as we need. In java programming language parameter name must follow data type of parameter.

Example

Following example shows a function with two parameters of type integers. The value in parameters is added and returned.


public class Main {
void add(int num1, int num2) {
int sum = num1 + num2 ;
System.out.println("Sum of numbers: " + sum);
}
}

Java function Arguments

Function parameters act variables in the body of function. Arguments are values or variables passed to function when function is called. Following example displays arguments of a function:


public class Main {
void add(int num1, int num2) {
int sum = num1 + num2 ;
System.out.println("Sum of numbers: " + sum);
}
public static void main(String[] args) {
Main obj = new Main();
obj.add(800,40);
}
}

800 and 40 are arguments in above example.

Java Functions

Java function also called java method is a group of java statements which is used multiple times when needed.
Why we use functions? to write a piece of for a certain task which we need to perform again and again. Instead of writing simple java statements to perform a task we write a function once and use it whenever we need to perform this task.

  • Java Functions usage is called function call.
  • We can pass some data to java functions.
  • Data is passed to java functions by java parameters.

How to create a Java function?

Java is a purely Object Oriented Programming language therefore java functions are created within java classes. Java function definition statrs with access specifier (i.e public, private, protected) followed by the data type function returns followed by function name which is followed by parentheses().

Here is an example of java function definition:


public class MyClass{
public int addInteger(int num1, int num2){
int sum = num1 + num2 ;
return sum ;
}
}

public is access specifier which indicates that this function can be called by functions of other classes. int is data type of value which function returns.

How to call a java function

Java functions are cannot be called directly. To call a java function either we need an object of class in which java function is defined or the function should be declared static to call function using name of class of function. Following is an example of function call using an object of class:


public class MyClass{
public void addInteger(int num1, int num2){
int sum = num1 + num2 ;
System.out.println("Sum of given numbers is: " + sum) ;
}
public static void main (String[] args){
// creating an object of MyClass.
MyClass obj = new MyClass();
// calling the function using created object.
obj.addInteger(100,200);
// calling the method again and again.
obj.addInteger(200,200);
obj.addInteger(300,200);
obj.addInteger(400,200);
}
}

Java Arrays

Java Arrays are data structures which can store multiple values or objects of same data type. In case of variables we need to declare a variable for each value or object. Java Arrays can be one dimensional or multi-dimensional.
A one-dimensional array can be declared in multiple ways as follows:

Datatype [] arrayName ;
Datytype[] arrayName ;
Datatype arrayName[] ;

When an array is declared, only a reference of array is created. To actually create or assign memory to array, we need to instantiate array as follows:

int arrayName[] ; // declaration of array
arrayName = new int [10] ; // allocation of memory to array

The above statements will create reference of array named arrayName of type integer. It will also assign 10 memoray locations to arrayName of type integer. Now we can store ten integers at that locations using the reference arrayName.
Now we can assign values to this array as follows:

arrayName[0]=10;
arrayName[1]=20;
.
.
.
.
.
arrayName [9]=100;

We can create and assigned values to arrays as follows:

int[] numbers = {1,3,4,6,8} ;
String[] vehicles= {"Car", "Truck", "Jeep", "Bus"};

Loop Through an Array with For loop.

We can loop through the array elements using the for loop, and length property to specify how many times the loop should run.

Example

Following example prints all elements of a string array:

String[] vehicles= {"Car", "Truck", "Jeep", "Bus"};
for (int i = 0; i < vehicles.length; i++) {
System.out.println(vehicles[i]);
}

Array and for-each loop

For-each loop iterates each element of array without using index of array. Following is an example of looping through an array using for-each loop:

String[] vehicles= {"Car", "Truck", "Jeep", "Bus"};
for (String vehicle : vehicles) {
System.out.println( vehicle );
}

Java Break and Continue

Java Break

We have already discussed break in switch statement topic. In switch statement break is used to stop execution of switch statement and to shift the execution control to next statement to switch.
break keyword is also used to stop execution of a loop.

Java break Example

Following example stops the loop when the value of i becomes equal to 5:


for (int i = 0; i < 6; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}

Java Continue

The break keyword break the complete execution of loop or switch statement while continue keyword skips remaining statements of loop within the curently executing iteration.

Java continue Example

Following example will skip the print statement when value of i equals 5:

for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
System.out.println(i);
}

break and continue can also be used in while and do/while loop as we have used in for loop.

Java while break example

Following example will stop the execution of while loop when the value of i becomes 10:

int i = 0;
while (i < 20) {
System.out.println(i);
i++;
if (i == 10) {
break;
}
}

Java while continue example

Following example will skip the print statement when the value of i becomes 10:


int i = 0;
while (i < 20) {
if (i == 10) {
i++;
continue;
}
System.out.println(i);
i++;
}

Java For-Each Loop

When we need to iterate through elements / objects stored in an array or collections (e.g ArrayList) we can use java for-each loop.

Java for-each Loop Syntax

Following is the syntax of for-each loop in java:

for( dataType object : arrayName){
// statements to be executed
}

Explanation

arrayName – an array or a collection
object – each item of array/collection is assigned to this variable
dataType – the data type of the array/collection

Example


String[] vehicles= {"Car", "Truck", "Jeep", "Bus"};
for (String vehicle : vehicles) {
System.out.println(vehicle);
}

Limitations of Java for-each loop

  1. Elements / Objects stored in array cannot be modified.
  2. For-each loop do not keep track of index. So we can not obtain array index using For-Each loop
  3. For-each only iterates forward over the array / collection in single steps

Java do-while loop

Java do while loop executes block of code at least once i.e. it will not check the condition in first iteration. After first iteration it repeats the block of code until the condition remains true.

Syntax


do {
// block of code to be executed
}while (condition);

Example

Following is an example of do while loop. The code block will be executed at least once irrespective of condition is true or false be the code block is executed before testing of condition.


int index = 1;
do {
System.out.println("Value of index is :"+index);
index++;
}while (index < 10);

Important: Loop will never terminate if variable used in condition remains constant. Therefore it should be incremented / decremented according to situation.

Java For Loop

When we know that how many times a block of code to be executed the java for loop will be the choice.
When we do not know the exact number of iteration then while / do-while can be used.

Syntax


for (initialization; condition check; increment/decrement) {
// statements to be executed
}

Initialization is done one time before starting the loop.
Condition is checked before every iteration of loop.
Increment / Decrement is done after every iteration of loop.

Example

Following example will print values from 1 to 15 integers:


for (int i = 1; i < 15; i++) {
System.out.println(i);
}

Explanation:

First statement (int i) creates a variable i of type integer and sets its value to 1 before starting the loop.
Second statement (i < 15;) checks the condition before each execution of loop. If the condition is true the code block will be executed other wise loop will be terminated and control will go to the statement after for loop.
Third statement (i++) increments the variable after each iteration of loop.

Increment / Decrement by a value other than 1

We can increment / decrement the index variable by any arbitrary number. In following example the index variable will be incremented by 3 after each iteration of loop.

for (int i = 0; i <= 10; i = i + 3) {
System.out.println(i);
}