Java Program to Implement Binary Search Using Recursion

In this article we are going to see how we can implement a binary search using recursion by Java programming language.

Java Program to Implement Binary Search Using Recursion

The recursive search implementation uses recursion to break the sorted array into two parts and so on, breaking until the element is found( or we reach the end).

Let’s see the program to understand it clearly.

Method-1: Java Program to Implement Binary Search Using Recursion By Using Static Input Value

Approach:

  • Create an sorted array of integers.
  • Create a variable and store the item to search.
  • Pass the array and the search item to our user defined function and store the returned index.
  • The user defined function takes the array, left and right indices and the search item as parameter. Then compare the middle element with the item. If the item is smaller, take the left part of the array, else the right part of the array and call the function on it.
  • Print the result.

Program:

import java.util.*;
// Main class
public class Main
{
   // Recursive Binary Search
   public static int binarySearch(int arr[], int left, int right, int item)
   {
       // Check for overflow first
       if (right >= left && left <= arr.length - 1) 
       {
           // Mid is the value located in the middle
           // between the left and right indices
           int mid = left + (right - left) / 2;
           // Check if the item is at middle position
           if (arr[mid] == item)
               return mid;
           // If the item is smaller than mid
           if (arr[mid] > item)
               return binarySearch(arr, left, mid - 1, item);
           // Else if the item is larger than mid
           return binarySearch(arr, mid + 1, right, item);
        }
       // If the element is not found
       return -1;
   }

   public static void main(String[] args)
   {
       // Array to search from
       int arr[] = {10,20,25,30,40,50};
       // Item to check for in the array
       int item = 25;
       // res stores the index returned from the recursive method
       int res = binarySearch(arr,0,arr.length-1,item);
       // Print the result
       if(res == -1)
           System.out.println("The element is not found");
       else
           System.out.println("The element is at index "+res);
    }
}
Output:

The element is at index 2

Method-2: Java Program to Implement Binary Search Using Recursion By Using User Input Value

Approach:

  • Ask the user to enter the number of elements and insert the elements next.
  • Then ask the user to search for an item inside.
  • Pass the array and the search item to our user defined function and store the returned index.
  • The user defined function takes the array, left and right indices and the search item as parameter. Then compare the middle element with the item. If the item is smaller, take the left part of the array, else the right part of the array and call the function on it.
  • Print the result.

Program:

import java.util.*;
// Main class
public class Main
{
   // Recursive Binary Search
   public static int binarySearch(int arr[], int left, int right, int item)
   {
       // Check for overflow first
       if (right >= left && left <= arr.length - 1)
       {
           // Mid is the value located in the middle
           // between the left and right indices
           int mid = left + (right - left) / 2;
           // Check if the item is at middle position
           if (arr[mid] == item)
               return mid;
           // If the item is smaller than mid
           if (arr[mid] > item)
               return binarySearch(arr, left, mid - 1, item);
           // Else if the item is larger than mid
           return binarySearch(arr, mid + 1, right, item);
        }
       // If the element is not found
       return -1;
    }

   public static void main(String[] args)
   {
       // Take user input
       Scanner sc = new Scanner(System.in);
       // Ask the user to enter array size
       System.out.print("Enter array size - ");
       int n = sc.nextInt();
       int arr[] = new int[n];
       // Ask the user to enter the array elements
       System.out.print("Enter the array elements - ");
       for(int i =0;i<n;i++)
           arr[i] = sc.nextInt();
       // Ask the user to enter an element to search
       System.out.println("Enter element to search for");
       int item = sc.nextInt();
       // res stores the index returned from the recursive method
       int res = binarySearch(arr,0,n-1,item);
       // Print the result
       if(res == -1)
           System.out.println("The element is not found");
       else
           System.out.println("The element is at index "+res);
    }
}
Output:

Enter array size - 5
Enter the array elements - 10 20 30 40 50
Enter element to search for
55
The element is not found

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Create a Thread using Class in Python

Creating a Thread using Class in Python

In this article, we will discuss how we can create thread in python by extending class from Thread class or calling a member function of the class.

Python provides a threading module to create and manage threads.

Extend Thread class to create Threads :

Let’s create a FileLoadTh class by extending Thread class provided by the threading module where it mimics functionality of a File loader and it’s run() method sleeps for sometime.

When we start thread by calling start() function, it will invoke run() method of Thread class and overriden run() method will be executed which may contain any custom implementation.

It is better to wait for other threads to finish calling join() method on FileLoaderTh class object before returning from main thread.

from threading import Thread
import time
# FileLoadTh extending Thread class
class FileLoaderTh(Thread):
   def __init__(self, fileName, encryptionType):
       # Calling Thread class's init() function
       Thread.__init__(self)
       self.fileName = fileName
       self.encryptionType = encryptionType
   # Overriding run() of Thread class
   def run(self):
       print('Loading started from file : ', self.fileName)
       print('Encryption Type : ', self.encryptionType)
       for i in range(5):
           print('Please wait loading... ')
           time.sleep(3)
       print('Loading finished from file : ', self.fileName)
def main():
   # Create an object of Thread
   th = FileLoaderTh('threadDemo.csv','DOC')
   # calling Thread class start() to start the thread
   th.start()
   for i in range(5):
       print('Inside main function-------')
       time.sleep(3)
   # Wait for thread to finish
   th.join()
if __name__ == '__main__':
   main()
Output :
Loading started from file :  threadDemo.csv
Inside main function-------
Encryption Type :  DOC
Please wait loading...
Inside main function-------
Please wait loading...
Inside main function-------
Please wait loading...
Please wait loading...
Inside main function-------
Please wait loading...
Inside main function-------
Loading finished from file :  threadDemo.csv

Create a Thread from a member function of a class :

Now let’s create a thread that executes loadcont() memeber function of FileLoadTh class. For that we can create a object and then pass the function with object to target argument of Thread class constructor.

So both main() function and loadcont() member function will run in parallel and at the end main() function will wait for other threads calling join() function on the same object.

import threading
import time
class FileLoaderTh():
   def __init__(self):
       pass
   
   def loadcont(self, fileName, encryptionType):
       print('Loading started from file : ', fileName)
       print('Encryption Type : ', encryptionType)
       for i in range(5):
           print('Loading ... ')
           time.sleep(3)
       print('Loading finished from file : ', fileName)
def main():
   # Creating object of FileLoaderTh class
   fileLoader = FileLoaderTh()
   # Create a thread using member function of FileHolderTh class
   th = threading.Thread(target=fileLoader.loadcont, args=('threadDemo.csv','DOC', ))
   # Start a thread
   th.start()
   # Print some logs in main thread
   for i in range(5):
       print('Inside main Function')
       time.sleep(3)
   # Wait for thread to finish
   th.join()
if __name__ == '__main__':
   main()
Output :
Loading started from file :  threadDemo.csv
Encryption Type :  DOC
Inside main Function
Loading ...
Inside main Function
Loading ...
Inside main Function
Loading ...
Inside main Function
Loading ...
Loading ...
Inside main Function
Loading finished from file :  threadDemo.csv

 

Pandas : Change data type of single or multiple columns of Dataframe in Python

Changeing data type of single or multiple columns of Dataframe in Python

In this article we will see how we can change the data type of a single or multiple column of Dataframe in Python.

Change Data Type of a Single Column :

We will use series.astype() to change the data type of columns

Syntax:- Series.astype(self, dtype, copy=True, errors='raise', **kwargs)

where Arguments:

  • dtype : It is python type to which whole series object will get converted.
  • errors : It is a way of handling errors, which can be ignore/ raise and default value is ‘raised’. (raise- Raise exception in case of invalid parsing , ignore- Return the input as original in case of invalid parsing
  • copy : bool (Default value is True) (If False- Will make change in current object , If True- Return a copy)

Returns: If copy argument is true, new Series object with updated type is returned.

import pandas as sc
# List of Tuples
students = [('Rohit', 34, 'Swimming', 155) ,
        ('Ritik', 25, 'Cricket' , 179) ,
        ('Salim', 26, 'Music', 187) ,
        ('Rani', 29,'Sleeping' , 154) ,
        ('Sonu', 17, 'Singing' , 184) ,
        ('Madhu', 20, 'Travelling', 165 ),
        ('Devi', 22, 'Art', 141)
        ]
# Create a DataFrame object with different data type of column
studObj = sc.DataFrame(students, columns=['Name', 'Age', 'Hobby', 'Height'])
print(studObj)
print(studObj.dtypes)
Output :
Name        Age       Hobby         Height
0  Rohit      34        Swimming     155
1  Ritik        25        Cricket          179
2  Salim      26        Music            187
3   Rani       29       Sleeping         154
4   Sonu      17       Singing          184
5  Madhu    20       Travelling       165
6   Devi       22        Art                141

Name      object
Age          int64
Hobby     object
Height     int64
dtype:      object

Change data type of a column from int64 to float64 :

We can change data type of a column a column e.g.  Let’s try changing data type of ‘Age’ column from int64 to float64. For this we have to write Float64 in astype() which will get reflected in dataframe.

import pandas as sc
# List of Tuples
students = [('Rohit', 34, 'Swimming', 155) ,
        ('Ritik', 25, 'Cricket' , 179) ,
        ('Salim', 26, 'Music', 187) ,
        ('Rani', 29,'Sleeping' , 154) ,
        ('Sonu', 17, 'Singing' , 184) ,
        ('Madhu', 20, 'Travelling', 165 ),
        ('Devi', 22, 'Art', 141)
        ]
# Create a DataFrame object with different datatype of column
studObj = sc.DataFrame(students, columns=['Name', 'Age', 'Hobby', 'Height'])
# Change data type of column 'Age' to float64
studObj['Age'] = studObj['Age'].astype('float64')
print(studObj)
print(studObj.dtypes)
Output :
Name   Age       Hobby  Height
0  Rohit  34.0    Swimming     155
1  Ritik  25.0     Cricket     179
2  Salim  26.0       Music     187
3   Rani  29.0    Sleeping     154
4   Sonu  17.0     Singing     184
5  Madhu  20.0  Travelling     165
6   Devi  22.0         Art     141
Name       object
Age           float64
Hobby      object
Height      int64
dtype: object

Change data type of a column from int64 to string :

Let’s try to change the data type of ‘Height’ column to string i.e. Object type. As we know by default value of astype() was True, so it returns a copy of passed series with changed Data type which will be assigned to studObj['Height'].

import pandas as sc
# List of Tuples
students = [('Rohit', 34, 'Swimming', 155) ,
        ('Ritik', 25, 'Cricket' , 179) ,
        ('Salim', 26, 'Music', 187) ,
        ('Rani', 29,'Sleeping' , 154) ,
        ('Sonu', 17, 'Singing' , 184) ,
        ('Madhu', 20, 'Travelling', 165 ),
        ('Devi', 22, 'Art', 141)
        ]
studObj = sc.DataFrame(students, columns=['Name', 'Age', 'Hobby', 'Height'])
# Change data type of column 'Marks' from int64 to float64
studObj['Age'] = studObj['Age'].astype('float64')
# Change data type of column 'Marks' from int64 to Object type or string
studObj['Height'] = studObj['Height'].astype('object')
print(studObj)
print(studObj.dtypes)
Output :
Name   Age       Hobby Height
0  Rohit  34.0    Swimming    155
1  Ritik  25.0     Cricket    179
2  Salim  26.0       Music    187
3   Rani  29.0    Sleeping    154
4   Sonu  17.0     Singing    184
5  Madhu  20.0  Travelling    165
6   Devi  22.0         Art    141
Name       object
Age           float64
Hobby      object
Height     object
dtype: object

Change Data Type of Multiple Columns in Dataframe :

To change the datatype of multiple column in Dataframe we will use DataFeame.astype() which can be applied for whole dataframe or selected columns.

Synatx:- DataFrame.astype(self, dtype, copy=True, errors='raise', **kwargs)

Arguments:

  • dtype : It is python type to which whole series object will get converted. (Dictionary of column names and data types where given colum will be converted to corrresponding types.)
  • errors : It is a way of handling errors, which can be ignore/ raise and default value is ‘raised’.
  • raise : Raise exception in case of invalid parsing
  • ignore : Return the input as original in case of invalid parsing
  • copy : bool (Default value is True) (If False- Will make change in current object , If True- Return a copy)

Returns: If copy argument is true, new Series object with updated type is returned.

Change Data Type of two Columns at same time :

Let’s try to convert columns ‘Age’ & ‘Height of int64 data type to float64 & string respectively. We will pass a Dictionary to Dataframe.astype() where it contain column name as keys and new data type as values.

import pandas as sc
# List of Tuples
students = [('Rohit', 34, 'Swimming', 155) ,
        ('Ritik', 25, 'Cricket' , 179) ,
        ('Salim', 26, 'Music', 187) ,
        ('Rani', 29,'Sleeping' , 154) ,
        ('Sonu', 17, 'Singing' , 184) ,
        ('Madhu', 20, 'Travelling', 165 ),
        ('Devi', 22, 'Art', 141)
        ]
# Create a DataFrame object with different datatype of column
studObj = sc.DataFrame(students, columns=['Name', 'Age', 'Hobby', 'Height'])
# Convert the data type of column Age to float64 & column Marks to string
studObj = studObj.astype({'Age': 'float64', 'Height': 'object'})
print(studObj)
print(studObj.dtypes)
Output :
Name   Age       Hobby Height
0  Rohit  34.0    Swimming    155
1  Ritik  25.0     Cricket    179
2  Salim  26.0       Music    187
3   Rani  29.0    Sleeping    154
4   Sonu  17.0     Singing    184
5  Madhu  20.0  Travelling    165
6   Devi  22.0         Art    141
Name       object
Age           float64
Hobby      object
Height     object
dtype: object

Handle errors while converting Data Types of Columns :

Using astype() to convert either a column or multiple column we can’t pass the content which can’t be typecasted. Otherwise error will be produced.

import pandas as sc
# List of Tuples
students = [('Rohit', 34, 'Swimming', 155) ,
        ('Ritik', 25, 'Cricket' , 179) ,
        ('Salim', 26, 'Music', 187) ,
        ('Rani', 29,'Sleeping' , 154) ,
        ('Sonu', 17, 'Singing' , 184) ,
        ('Madhu', 20, 'Travelling', 165 ),
        ('Devi', 22, 'Art', 141)
        ]
# Create a DataFrame object with different datatype of column
studObj = sc.DataFrame(students, columns=['Name', 'Age', 'Hobby', 'Height'])
# Trying to change dataype of a column with unknown dataype
try:
        studObj['Name'] = studObj['Name'].astype('xyz')
except TypeError as ex:
        print(ex)

Output :
data type "xyz" not understood

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Read more Articles on Python Data Analysis Using Padas – Modify a Dataframe

Java Program to Find HCF of Two Numbers Using Recursion

In this article we are going to see how we can find HCF of two numbers using recursion by Java programming language.

Java Program to Find HCF of Two Numbers Using Recursion

HCF: 

HCF refers to the Highest Common Factor which refers to the largest common factor between 2 or more numbers.

It is also called Greatest Common Factor (GCF) or Greatest Common Divisor (GCD).

For example-

Two numbers are 2 and 4. Then the HCF is 2.
Two numbers are 30 and 42. Then the HCF is 6.

Let’s see the program to understand it clearly.

Method-1: Java Program to Find HCF of Two Numbers Using Recursion By Using Static Input Value

Approach:

  • Store two numbers in two integer variables.
  • Call the user defined method hcfCalculator( ) to find the product and store it. The method checks if either the numbers are zeroes or are equal to each other then it calculates hcf by taking modulus of the larger number and calling the method again.
  • Print the result.

Program:

import java.util.*;
// Main class
public class Main
{
    // Recursive method to find hcf of two numbers
    public static int hcfCalculator(int num1, int num2)
    {
        // cHecks if num1 and num2 are same numbers
        if (num1 == num2) 
        {
            return num1;
        // Checks if wither of the numbers are zeroes
        } 
        else if (num1 == 0) 
        {
            return num2;
        } 
        else if (num2 == 0) 
        {
            return num1;
        // Finds the hcf using recursin
        } 
        else if (num1 > num2) 
        {
            return hcfCalculator(num1 % num2, num2);
        } 
        else 
        {
            return hcfCalculator(num1, num2 % num1);
        }
    }
    
    public static void main(String[] args)
    {
        int num1 = 39, num2 = 62;
        // Call the method and store the result
        int hcf = hcfCalculator(num1,num2);
        // Print the result
        System.out.println("The hcf of "+num1+" and "+num2+" is "+hcf);
    }
}

Output:

The hcf of 39 and 62 is 1

Method-2: Java Program to Find HCF of Two Numbers Using Recursion By Using User Input Value

Approach:

  • Ask the user to enter two numbers in order.
  • Store two numbers in two integer variables.
  • Call the user defined method hcfCalculator( ) to find the product and store it. The method checks if either the numbers are zeroes or are equal to each other then it calculates hcf by taking modulus of the larger number and calling the method again.
  • Print the result.

Program:

import java.util.*;
// Main class
public class Main
{
    // Recursive method to find hcf of two numbers
    public static int hcfCalculator(int num1, int num2)
    {
        // cHecks if num1 and num2 are same numbers
        if (num1 == num2) 
        {
            return num1;
        // Checks if wither of the numbers are zeroes
        }
        else if (num1 == 0) 
        {
            return num2;
        }
        else if (num2 == 0) 
        {
            return num1;
        // Finds the hcf using recursin
        } 
        else if (num1 > num2) 
        {
            return hcfCalculator(num1 % num2, num2);
        } 
        else 
        {
            return hcfCalculator(num1, num2 % num1);
        }
    }
    
    public static void main(String[] args)
    {
        // Taking user input
        Scanner sc = new Scanner(System.in);
        // Ask the user to enter two numbers
        System.out.print("Enter two numbers to find HCF ");
        int num1 = sc.nextInt(), num2 = sc.nextInt();
        // Call the method and store the result
        int hcf = hcfCalculator(num1,num2);
        // Print the result
        System.out.println("The hcf of "+num1+" and "+num2+" is "+hcf);
    }
}

Output:

Enter two numbers to find HCF 10 5
The hcf of 10 and 5 is 5

Provided list of Simple Java Programs is specially designed for freshers and beginners to get familiarize with the concepts of Java programming language and become pro in coding.

Java Program to Count the Digits of a Number Using Recursion

In this article we are going to see how we can count the digits of a number using recursion by Java programming language.

Java Program to Count the Digits of a Number Using Recursion

Let’s see the program.

Method-1: Java Program to Count the Digits of a Number Using Recursion By Using Static Input Value

Approach:

  • Create a static integer variable ‘ctr’ and store any number in it.
  • Call the user defined method calcDigits( ) and store the result in an integer  variable ‘digits
  • So calcDigits( ) is an user-defined method that increments the counter and calls the method by dividing the digits by 10.
  • Print the result.

Program:

import java.util.*;
// Main class
public class Main
{
    // counter to store the count
    static int ctr=0;
    // Method to count the number of digits in a number using recursion
    public static int calcDigits(int num)
    {
        // Till number is greater than zero keep on incrementing the counter
        if(num!=0)
        {
            ctr++;
            // Divides the number by 10 and recursively calls the method
            calcDigits(num/10);
        }
        return ctr;
    }
    
    public static void main(String[] args)
    {
        int num = 3962;
        // Call the method and store the result
        int digits = calcDigits(num);
        // Print the result
        System.out.println("The number of digits in "+num+" is "+digits);
    }
}
Output:

The number of digits in 3962 is 4

Method-2: Java Program to Count the Digits of a Number Using Recursion By Using User Input Value

Approach:

  • Create a static integer variable ‘ctr
  • Ask the user to enter a number and store it in an integer variable ‘num
  • Call the user defined method calcDigits( )and store the result in an integer  variable ‘digits
  • So calcDigits( ) is an user-defined method that increments the counter and calls the method by dividing the digits by 10.
  • Print the result.

Program:

import java.util.*;
// Main class
public class Main
{
    // counter to store the count
    static int ctr=0;
    // Method to count the number of digits in a number using recursion
    public static int calcDigits(int num)
    {
        // Till number is greater than zero keep on incrementing the counter
        if(num!=0)
        {
            ctr++;
            // Divides the number by 10 and recursively calls the method
            calcDigits(num/10);
        }
        return ctr;
    }
    
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number to calculate its digits - ");
        int num = sc.nextInt();
        // Call the method and store the result
        int digits = calcDigits(num);
        // Print the result
        System.out.println("The number of digits in "+num+" is "+digits);
    }
}
Output:

Enter the number to calculate its digits - 965
The number of digits in 965 is 3

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Java Program to Multiply Two Numbers Using Recursion

In this article we are going to see how we can multiply two numbers using recursion by Java programming language.

Java Program to Multiply Two Numbers Using Recursion

Multiplying two numbers means finding the product of two numbers.

Let’s see the program how we you multiply two numbers using recursion.

Method-1:  Java Program to Multiply Two Numbers Using Recursion By Using Static Input Value

Approach:

  • Store two numbers in two variables.
  • Call the user defined method mulProd( ) to find the product and store it. The method prod() ensures that num1>num2 else swaps them. Then when num2 is greater than zero it calls mulProd( ) on num1 and decremented num2 then adds the result with num1.
  • Print the result.

Program:

import java.util.*;
// Main class
public class Main
{
    // Recursive method to multiply two numbers
    public static int mulProd(int num1, int num2)
    {
        // If num2 is greater than num1 swap them and call the function
        if (num1 < num2) 
        {
            return mulProd(num2, num1);
        }
        // If num2 is greater than 0 then call the function by decrementing num2 by 1 and add the current num1 value to the result.
        else if (num2 != 0)
        {
            return (num1 + mulProd(num1, num2 - 1));
        }
        else 
        {
            return 0;
        }
    }
    
    public static void main(String[] args)
    {
        int num1 = 29, num2 = 10;
        // Call the method and store the result
        int prod = mulProd(num1,num2);
        // Print the result
        System.out.println("The product of "+num1+" and "+num2+" is "+prod);
    }
}

Output:

The product of 29 and 10 is 290

Method-2: Java Program to Multiply Two Numbers Using Recursion By Using User Input Value

Approach:

  • Ask the user to enter two numbers in order.
  • Store two numbers in two variables.
  • Call the user defined method mulProd( ) to find the product and store it. The method prod() ensures that num1>num2 else swaps them. Then when num2 is greater than zero it calls mulProd( ) on num1 and decremented num2 then adds the result with num1.
  • Print the result.

Program:

import java.util.*;
// Main class
public class Main
{
    // Recursive method to multiply two numbers
    public static int mulProd(int num1, int num2)
    {
        // If num2 is greater than num1 swap them and call the function
        if (num1 < num2) 
        {
            return mulProd(num2, num1);
        }
        // If num2 is greater than 0 then call the function by decrementing num2 by 1 and add the current num1 value to the result.
        else if (num2 != 0) 
        {
            return (num1 + mulProd(num1, num2 - 1));
        }
        else 
        {
            return 0;
        }
    }
    
    public static void main(String[] args)
    {
        // Taking user input
        Scanner sc = new Scanner(System.in);
        // Ask the user to enter two numbers
        System.out.print("Enter two numbers to multiply ");
        int num1 = sc.nextInt(), num2 = sc.nextInt();
        // Call the method and store the result
        int prod = mulProd(num1,num2);
        // Print the result
        System.out.println("The product of "+num1+" and "+num2+" is "+prod);
    }
}
Output:

Enter two numbers to multiply 15 50
The product of 15 and 50 is 750

Access the Simple Java program for Interview examples with output from our page and impress your interviewer panel with your coding skills.

Java Program to Subtract Two Numbers Using Recursion

In this article we are going to see how we can subtract two numbers using recursion by Java programming language.

Java Program to Subtract Two Numbers Using Recursion

Method-1: Java Program to Subtract Two Numbers Using Recursion By Using Static Input Value

Approach:

  • Store two numbers in two variables.
  • Call the user defined method sub( ) to find the difference and store it. The method sub() decrements both the numbers by 1 using recursion until the smaller one reaches 0. Then it returns the other number.
  • Print the result.

Program:

import java.util.*;
// Main class
public class Main
{
    // Recursive method to subtract two numbers
    public static int sub(int num1, int num2)
    {
        // Returns the difference when num2 reaches zero
        if(num2==0)
            return num1;
        else
            // calls the function by decrementing both numbers by 1
            return sub((num1-1),(num2-1));
    }
    
    public static void main(String[] args)
    {
        int num1 = 29, num2 = 15;
        // Call the method and store the result
        int dif = sub(num1,num2);
        // Print the result
        System.out.println("The difference between "+num1+" and "+num2+" is "+dif);
    }
}
Output:

The difference between 29 and 15 is 14

Method-2: Java Program to Subtract Two Numbers Using Recursion By Using User Input Value

Approach:

  • Ask the user to enter two numbers in order.
  • Store two numbers in two variables.
  • Call the user defined method sub( ) to find the difference and store it. The method sub() decrements both the numbers by 1 using recursion until the smaller one reaches 0. Then it returns the other number.
  • Print the result.

Program:

import java.util.*;
// Main class
public class Main
{
    // Recursive method to subtract two numbers
    public static int sub(int num1, int num2)
    {
        // Returns the difference when num2 reaches zero
        if(num2==0)
            return num1;
        else
        // calls the function by decrementing both numbers by 1
            return sub((num1-1),(num2-1));
    }
    
    public static void main(String[] args)
    {
        // Taking user input
        Scanner sc = new Scanner(System.in);
        // Ask the user to enter two numbers
        System.out.print("Enter two numbers to subtract ");
        int num1 = sc.nextInt(), num2 = sc.nextInt();
        // Call the method and store the result
        int dif = sub(num1,num2);
        // Print the result
        System.out.println("The difference between "+num1+" and "+num2+" is "+dif);
    }
}
Output:

Enter two numbers to subtract 10 5
The difference between 10 and 5 is 5

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Java Program to Find the Length of a String Using Recursion

In this article we are going to see how we can find the length of a string using recursion by Java programming language.

Java Program to Find the Length of a String Using Recursion

The length of the string refers to the total number of characters present in that.

For example-

A string is "BtechGeeks"
Then in this string there are 10 characters. So length of string is 10.

Let’s see the program to find the length of a string using recursion.

Method-1: Java Program to Find the Length of a String Using Recursion By Using Static Input Value

Approach:

  • Store a string.
  • Store the string and call the user-defined method strLen( ) passing the string as parameter.
  • The user defined method checks if we have reached the end, else it recursively calls itself on the same string without the current character and adds 1 to the result.
  • Print the result.

Program:

import java.util.*;
// Main class
public class Main
{
    // Recursive method to calculate string length
    public static int strLen(String s)
    {
        // Checks if we have reached the end of the string
        if (s.equals(""))
            return 0;
        else
            // Calls function on a substring not including the current character
            return strLen(s.substring(1)) + 1;
    }
    
    public static void main(String[] args)
    {
        String s = "Hi!!!";
        // Call the method and store the length
        int length = strLen(s);
        // Print the result
        System.out.println("The number of characters in the string "+s+" is "+length);
    }
}
Output:

The number of characters in the string Hi!!! is 5

Method-2: Java Program to Find the Length of a String Using Recursion By Using User Input Value

Approach:

  • Ask the user to input a string.
  • Store the string and call the user-defined method strLen( ) passing the string as parameter.
  • The user defined method checks if we have reached the end, else it recursively calls itself on the same string without the current character and adds 1 to the result.
  • Print the result.

Program:

import java.util.*;
// Main class
public class Main
{
    // Recursive method to calculate string length
    public static int strLen(String s)
    {
        // Checks if we have reached the end of the string
        if (s.equals(""))
            return 0;
        else
            // Calls function on a substring not including the current character
            return strLen(s.substring(1)) + 1;
    }
    
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        // Ask the user to input the string
        System.out.print("Enter the string - ");
        String s = sc.nextLine();
        // Call the method and store the length
        int length = strLen(s);
        // Print the result
        System.out.println("The number of characters in the string "+s+" is "+length);
    }
}
Output:

Enter the string - helloworld!
The number of characters in the string helloworld! is 11

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language.

Java Program to Check If a Number is Prime or Not Using Recursion

In this article we are going to see how we can check if a number is prime or not using recursion by Java programming language.

Java Program to Check If a Number is Prime or Not Using Recursion

A number is said to be prime number if it has only 2 factors i.e. 1 and the number itself. Means other than 1 and itself it is not divisible by any other numbers.

For example- 7, 13, 19, 29 etc.

Here you have to write the program check if a number is prime or not using recursion.

Method-1: Java Program to Check If a Number is Prime or Not Using Recursion By Using Static Input Value

Approach:

  • Declare an Integer variable ‘num’ and initialize with 59.
  • Call the user defined method checkPrime( ) by passing the ‘num’ and its half.
  • The user-defined method takes a ‘num’ and its half as input. Then keeps on decrementing the half until it divides the ‘num‘ or it reaches 1 using recursion.
  • Print the result.

Program:

import java.util.*;
// Main class
public class Main
{
    // Recursive method to check for prime
    public static int checkPrime(int num, int i)
    {
        if (i != 1) 
        {
            // checks if the number is divisible
            if (num % i != 0) 
            {
                // Decrements the divisor by 1 every call
                return checkPrime(num, i - 1);
            }
            else 
            {
                return 0;
            }
        }
        else 
        {
            return 1;
        }
    }
    
    public static void main(String[] args)
    {
        int num = 59;
        // Call the method and store the result
        int res = checkPrime(num,num/2);
        // Print the result
        if(res==1)
            System.out.println(num+" is prime.");
        else
            System.out.println(num+" is not prime.");
    }
}
Output:

59 is prime.

Method-2: Java Program to Check If a Number is Prime or Not Using Recursion By Using User Input Value

Approach:

  • Ask the user to enter a number and store it in ‘num‘ variable.
  • Call the user defined method checkPrime( ) by passing the ‘num‘ and its half.
  • The user-defined method takes a ‘num‘ and its half as input . Then keeps on decrementing the half until it divides the ‘num‘ or it reaches 1 using recursion.
  • Print the result.

Program:

import java.util.*;
// Main class
public class Main
{
    // Recursive method to check for prime
    public static int checkPrime(int num, int i)
    {
        if (i != 1) 
        {
            // checks if the number is divisible
            if (num % i != 0) 
            {
                // Decrements the divisor by 1 every call
                return checkPrime(num, i - 1);
            }
            else 
            {
                return 0;
            }
        }
        else 
        {
            return 1;
        }
    }
    
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        // Asks the user for input
        System.out.println("Enter a number");
        int num = sc.nextInt();
        // Call the method and store the result
        int res = checkPrime(num,num/2);
        // Print the result
        if(res==1)
            System.out.println(num+" is prime.");
        else
            System.out.println(num+" is not prime.");
    }
}
Output:

Enter a number
153
153 is not prime.

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output.

Java LocalDate getDayOfMonth() Method with Examples

In this article we are going to see the use of Java LocalDate class getDayOfMonth() method with suitable examples.

Java LocalDate getDayOfMonth() Method with Examples

Explanation:

This java.time.LocalDate.getDayOfMonth() method is used to get the day of the month which date is given by the user. It returns the day of the month which is from 1 to 31.

Syntax:

public int getDayOfMonth()

Let’s see some example programs to understand it more clearly.

Approach:

  • Create an object of localDate class.
  • Then use the getDayOfMonth() method for this particular date to extract the day of that month.
  • Print the final result.

Example-1:

import java.time.LocalDate;
public class Main
{
    public static void main(String[] args)
    {
        //Create an object of LocalDate class and assign a date to it
        //here it parses the local date
        LocalDate date = LocalDate.parse("2022-05-11");
        //use the getDayOfMonth() method and print the result
      	System.out.println("Day-of-the-month: "+date.getDayOfMonth()); 
    }
}
Output:

Day-of-the-month: 11

Example-2:

import java.time.LocalDate;
public class Main
{
    public static void main(String[] args)
    {
        //Create an object of LocalDate class and assign a date to it
        //here it parses the local date
        LocalDate date = LocalDate.parse("2022-05-29");
        //use the getDayOfMonth() method and print the result
          System.out.println("Day-of-the-month: "+date.getDayOfMonth()); 
    }
}
Output:

Day-of-the-month: 29

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.