Java Program to Replace Every Array Element by Multiplication with its Next Element

Java Program to Replace Each Element of the Array by the Product of its Next Element

In the previous article, we have seen Java Program to Replace Every Array Element by Multiplication of Previous and Next Element

In this article we are going to see how to replace every array element by multiplication with its next element using Java programming language.

Java Program to Replace Every Array Element by Multiplication with its Next Element

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to replace every array element by multiplication with its next element.

Method-1: Java Program to Replace Every Array Element by Multiplication with its Next Element By Using An Extra Array

Approach:

  • Declare and initialize the original array.
  • Create another array of the size of the original array.
  • Print the original array.
  • Iterate over the array.
  • At each index, except 0th and last, update the element with the product of current and next element in the original array. And store it new array.
  • Print the new array.

Program:

import java.util.Arrays;
import java.util.Scanner;

public class Main 
{

    public static void main(String[] args) 
    {
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user for array size
        System.out.print("Enter the size of array: ");
        int n = sc.nextInt();
        // initialize array with size n
        int[] arr = new int[n];
        // take input from user for array elements
        System.out.print("Enter array elements: ");
        for (int i = 0; i < n; i++) 
        {
            arr[i] = sc.nextInt();
        }
        System.out.println("Before rearranging: " + Arrays.toString(arr));
        rearrange(arr);
    }

    public static void rearrange(int[] arr) 
    {
        int[] temp = new int[arr.length];
        for (int i = 0; i < temp.length - 1; i++) 
        {
            temp[i] = arr[i] * arr[i + 1];
        }
        temp[temp.length - 1] = arr[arr.length - 1];
        System.out.println("After rearranging: " + Arrays.toString(temp));
    }
}
Output:

Enter the size of array: 5
Enter array elements: 1 2 3 4 5
Before rearranging: [1, 2, 3, 4, 5]
After rearranging: [2, 6, 12, 20, 5]

Method-2: Java Program to Replace Every Array Element by Multiplication with its Next Element Without Using an Extra Array

Approach:

  • Ask the user to enter the array size and store it.
  • Create an empty array of the specified size.
  • Ask the user to enter the elements.
  • Print the array elements.
  • Iterate over the array.
  • At each index, except 0th and last, update the element with the product of current and next element in the original array and replace that new value in the original array.
  • Print the array.

Program:

import java.util.Arrays;
import java.util.Scanner;

public class Main
{

    public static void main(String[] args) 
    {
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user for array size
        System.out.print("Enter the size of array: ");
        int n = sc.nextInt();
        // initialize array with size n
        int[] arr = new int[n];
        // take input from user for array elements
        System.out.print("Enter array elements: ");
        for (int i = 0; i < n; i++) 
        {
            arr[i] = sc.nextInt();
        }
        System.out.println("Before rearranging: " + Arrays.toString(arr));
        rearrange(arr);
    }

    public static void rearrange(int[] arr) 
    {
        for (int i = 0; i < arr.length - 1; i++) 
        {
            arr[i] = arr[i] * arr[i + 1];
        }

        System.out.println("After rearranging: " + Arrays.toString(arr));
    }
}
Output:

Enter the size of array: 5
Enter array elements: 1 2 3 4 5
Before rearranging: [1, 2, 3, 4, 5]
After rearranging: [2, 6, 12, 20, 5]

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs:

Java Program to Find the Single Digit Array Elements

Java Program to Find the Single Digit Array Elements

In the previous article, we have seen Java Program to Replace Each Element of the Array by the Product of its Next Element

In this article we are going to see how to find the single digit array elements using Java programming language.

Java Program to Find the Single Digit Array Elements

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to find the single digit array elements.

Method-1: Java Program to Find the Single Digit Array Elements By Using Division By 10

Approach:

Any single digit variable of int data type would give 0 as result on performing a division with 10.

  • Create scanner class object.
  • Ask user for the length of the array.
  • Initialize the array with given size.
  • Ask the user for array elements.
  • Iterate over the array.
  • If arr[i] / 10 == 0, print the element.

Program:

import java.util.*;

public class Main
{

    public static void main(String[] args) 
    {
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user for array size
        System.out.print("Enter the size of array: ");
        int n = sc.nextInt();
        // initialize array with size n
        int[] arr = new int[n];
        // take input from user for array elements
        System.out.print("Enter array elements: ");
        for (int i = 0; i < n; i++) 
        {
            arr[i] = sc.nextInt();
        }
        //calling the method findSingleDigitElement()
        findSingleDigitElements(arr);
    }

    //findSingleDigitElement() method to find all the single digit elemnt in the array
    public static void findSingleDigitElements(int[] arr) 
    {
        System.out.println("Single digit elements are: ");
        // iterate through the array
        for (int i = 0; i < arr.length; i++) 
        {
            // check if the element is single digit
            if (arr[i] / 10 == 0) 
            {
                System.out.print(arr[i] + " ");
            }
        }
    }

}
Output:

Enter the size of array: 8
Enter array elements: 56 9 1213 3 34 5 8 345
Single digit elements are: 
9 3 5 8

Method-2: Java Program to Find the Single Digit Array Elements By Checking -9 to 9

Approach:

  • Create scanner class object.
  • Ask user for the length of the array.
  • Initialize the array with given size.
  • Ask the user for array elements.
  • Iterate over the array.
  • If the element lies in between -9 to 9 then print it as it is single digit element.

Program:

import java.util.*;

public class Main
{

    public static void main(String[] args) 
    {
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user for array size
        System.out.print("Enter the size of array: ");
        int n = sc.nextInt();
        // initialize array with size n
        int[] arr = new int[n];
        // take input from user for array elements
        System.out.print("Enter array elements: ");
        for (int i = 0; i < n; i++) 
        {
            arr[i] = sc.nextInt();
        }
        //calling the method findSingleDigitElement()
        findSingleDigitElements(arr);
    }

    //findSingleDigitElement() method to find all the single digit elemnt in the array
    public static void findSingleDigitElements(int[] arr) 
    {
        System.out.println("Single digit elements are: ");
        // iterate through the array
        for (int i = 0; i < arr.length; i++) 
        {
            // check if the element is single digit
            if (arr[i] >= -9 && arr[i] <= 9) 
            {
                System.out.print(arr[i] + " ");
            }
        }
    }

}
Output:

Enter the size of array: 10
Enter array elements: 78 -5 342 -4 8 22 890 4 9 4567
Single digit elements are: 
-5 -4 8 4 9

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Related Java Programs:

Java Program to Left Rotate the Elements of an Array

Java Program to Left Rotate the Elements of an Array

In the previous article, we have seen Java Program to Find Sum of Two Arrays Elements

In this article we will see how to left rotate all the elements of an array using Java.

Java Program to Left Rotate the Elements of an Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Approach:

  • Create an array.
  • Display it to the user.
  • Store the first element of the array in a temp variable.
  • Traverse through the array and store each element at its previous index.
  • Set the last index to the value store in our temp variable.
  • Print the array.

Program:

import java.util.*;
public class Main
{    
    public static void main(String args[])
    {
        // Crating an array
        int arr[] = {10,30,50,70,90};
        // Displaying the array
        System.out.print("Array : ");
        printArray(arr);
        // Left rotation
        leftRotation(arr);
        System.out.print("After left rotation, Array : ");
        printArray(arr);

    }

    // Function to print the array
    static void printArray(int arr[])
    {
        for(int i = 0; i < arr.length ; i++)
            System.out.print(arr[i]+" ");
        System.out.println();
    }
    // Function to rotate the array
    public static void leftRotation(int arr[])
    {  
        // Holder for first element
        int temp = arr[0];
        // For loop to swap elements
        for (int i=1; i<arr.length; i++)
        {
            arr[i-1]=arr[i];
        }
        // Setting the last element
        arr[arr.length-1]=temp;
    }  
}

Output:

Array : 10 30 50 70 90 
After left rotation, Array : 30 50 70 90 10

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs:

Java Program to Find the Common Elements between Two Integer Arrays

Java Program to Find the Common Elements between Two Integer Arrays

In the previous article, we have seen Java Program to Find the Index of an Array Element

In this article we are going to find common element between two integer arrays in Java.

Java Program to Find the Common Elements between Two Integer Arrays

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Now let’s see the solution to the problem.

Approach:

  • Create two arrays.
  • Display both of them to the user.
  • Use two for loops to iterate both arrays.
  • Print common elements between them.

Program:

import java.util.*;
public class Main
{    
    public static void main(String args[])
    {
        // Crating an array
        int arr1[] = {10,30,50,70,90};
        int arr2[] = {10,20,30,40,50};
        // Displaying the array
        System.out.print("Array 1 : ");
        printArray(arr1);
        System.out.print("Array 2 : ");
        printArray(arr2);
        System.out.print("The common elements are : ");
        // Print common elements
        printCommon(arr1,arr2);
    }

    // Function to print the array
    static void printArray(int arr[])
    {
        for(int i = 0; i < arr.length ; i++)
            System.out.print(arr[i]+" ");
        System.out.println();
    }
    
    public static void printCommon(int arr1[], int arr2[])
    {  
        // Checks for common elements
        for (int i=0; i<arr1.length; i++){
            for(int j=0;j<arr2.length;j++)
                if (arr1[i]==arr2[j]){
                    System.out.print(arr1[i]+" "); 
            }  
        }
    }  
}

Output:

Array 1 : 10 30 50 70 90 
Array 2 : 10 20 30 40 50 
The common elements are : 10 30 50

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs:

Java Program to Find the Common Strings in Two String Arrays

Java Program to Find the Common Strings in Two String Arrays

In the previous article, we have seen Java Program to Find the Common Elements between Two Integer Arrays

In this article we are going to find common strings between two string arrays in Java.

Java Program to Find the Common Strings in Two String Arrays

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Now let’s see the solution to the problem.

Approach:

  • Create two arrays.
  • Display both of them to the user.
  • Use two for loops to iterate both arrays.
  • Print common elements between them.

Program:

import java.util.*;
public class Main
{    
    public static void main(String args[])
    {
        // Crating an array
        String arr1[] = {"cat", "dog", "mouse"};
        String arr2[] = {"elephant", "cat", "mouse", "lion", "zebra"};
        // Displaying the array
        System.out.print("Array 1 : ");
        printArray(arr1);
        System.out.print("Array 2 : ");
        printArray(arr2);
        System.out.print("The common elements are : ");
        // Print common elements
        printCommon(arr1,arr2);
    }

    // Function to print the array
    static void printArray(String arr[])
    {
        for(int i = 0; i < arr.length ; i++)
            System.out.print(arr[i]+" ");
        System.out.println();
    }
    
    public static void printCommon(String arr1[], String arr2[])
    {  
        // Checks for common elements
        for (int i=0; i<arr1.length; i++){
            for(int j=0;j<arr2.length;j++)
                if (arr1[i].equals(arr2[j])){
                    System.out.print(arr1[i]+" "); 
            }  
        }
    }  
}

Output:

Array 1 : cat dog mouse 
Array 2 : elephant cat mouse lion zebra 
The common elements are : cat mouse

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs:

Java Program to Print the Array Element Address When Base Address and Element Size is Given

Java Program to Print the Array Element Address When Base Address and Element Size is Given

In the previous article, we have seen Java Program to Convert Linked List to Array

In this article we will see how we can find the array element address while the base address and array element size is given using java programming language.

Java Program to Print the Array Element Address When Base Address and Element Size is Given

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see the solution to the problem statement.

Approach:

  • Ask the user to enter base address of the array.
  • Ask the user to enter the size of the array element in bytes.
  • Ask the user to enter the index of the element of which you need address.
  • Find address by adding base address with product of element size and element index.
  • Print the array element address.

Program:

import java.io.*;
 
public class Main 
{
    public static void main(String args[]) throws Exception
    {
        //Object of BufferedReader Class is created
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        try
        {
            //Enter address greater than 0
            //Entering base address of array
            System.out.println("Enter the base address of the array : ");
            long baseAddress=Long.parseLong(br.readLine());
    
            //Entering size of array element int bytes
            //Enter size greater than 0
            System.out.println("Enter the size of the array element in bytes: ");
            long elementSize=Long.parseLong(br.readLine());
    
            System.out.println("Enter the index of the element of which you need address: ");
            long elementIndex=Long.parseLong(br.readLine());
        
    
            //checking if baseAddress or elementSize or elementIndex value is less that 0
            //then print that input is invalid
            if( baseAddress < 0 || elementSize <=0 || elementIndex < 0 )
            {
                System.out.println("Entered input is Invalid");
            }
            //else find the element address
            else
            {
                long elementAddress;
                //getting element address by adding base address 
                //with product of element size and element index
                elementAddress = baseAddress + (elementSize * elementIndex);
                System.out.println("Address of array element at index "+ elementIndex
                                                     +" is "+elementAddress);
            }
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}
Output:

Case-1

Enter the base address of the array : 
2000
Enter the size of the array element in bytes: 
2
Enter the index of the element of which you need address: 
3
Address of array element at index 3 is 2006

Case-2

Enter the base address of the array : 
-2000
Enter the size of the array element in bytes: 
2
Enter the index of the element of which you need address: 
3
Entered input is Invalid


Case-3

Enter the base address of the array : 
2000
Enter the size of the array element in bytes: 
-2
Enter the index of the element of which you need address: 
3
Entered input is Invalid

Case-4

Enter the base address of the array : 
2000
Enter the size of the array element in bytes: 
2
Enter the index of the element of which you need address: 
-3
Entered input is Invalid

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs:

Java Program to Find the Indexes of Element ‘0’ Present in Array

Java Program to Find the Indexes of Element '0' Present in Array

In the previous article, we have seen Java Program to Delete All 0 Element Values from an Array of Integers

In this article we are going to find index of an array element using Java programming language.

Java Program to Find the Indexes of Element ‘0’ Present in Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to find to find index of element 0 present in array.

Method-1: Java Program to Find the Indexes of Element ‘0’ Present in Array By Static Initialization of Array Elements

Approach:

  • Create an array with elements which is the original array i.e arr[].
  • Create another array of size as like original array to store the indices where 0 is present.
  • Take a for loop iterate the original array.
  • Check if anywhere element 0 is found then store that index in the index[] array.
  • Print the index[] array.

Program:

import java.util.*;
public class Main
{    
    public static void main(String args[])
    {
        //Array declared with array elements
       int arr[] ={1,2,3,0,4,5,0,6};
        
        System.out.print("Original Array: ");
        //printing the original array
        for(int i = 0; i < arr.length ; i++)
            System.out.print(arr[i]+" ");
        System.out.println();
        
        //declaring int varibale item and assigning value 0
        int item = 0;
        
        //Another array declared to store the indices where 0 is present
        int index[]= new int[arr.length];
        int j=0;
        // Traversinng the array looking for the element
        for(int i = 0; i<arr.length; i++)
        {
            if(arr[i]==item)
            {
                index[j] = i;
                j++;
            }

        }
        // Printing the final result
        if(j == 0)
        {
            System.out.println("Element 0 is not present in array");
        }
        else
        {
            System.out.println("Element "+item+" is present at index: ");
            //printing array containg indices of 0 in the original array
            for(int i = 0; i < j; i++)
                System.out.print(index[i]+" ");
            System.out.println();
        }
    }
}
Output:

Original Array: 1 2 3 0 4 5 0 6 
Element 0 is present at index: 
3 6

Method-2: Java Program to Find the Indexes of Element ‘0’ Present in Array By Dynamic Initialization of Array Elements

Approach:

  • Create scanner class object.
  • Ask use length of the original array i.e arr[].
  • Initialize the array with given size.
  • Ask the user for input of  array elements to the original array.
  • Create another array of size as like original array to store the indices where 0 is present.
  • Take a for loop iterate the original array.
  • Check if anywhere element 0 is found then store that index in the index[] array.
  • Print the index[] array.

Program:

import java.util.*;
public class Main
{    
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in); 
        System.out.print("Enter the number of elements in the array: "); 
        int num = sc.nextInt(); 
        int arr[] = new int[num]; 
        System.out.print("Enter the elements: ");
        //taking input of array elements
        for (int i = 0; i < num; i++) 
        { 
        arr[i] = sc.nextInt(); 
        }
        
        System.out.print("Original Array: ");
        //printing the original array
        for(int i = 0; i < arr.length ; i++)
            System.out.print(arr[i]+" ");
        System.out.println();
        
        //declaring int varibale item and assigning value 0
        int item = 0;
        
        //Another array declared to store the indices where 0 is present
        int index[]= new int[arr.length];
        int j=0;
        // Traversinng the array looking for the element
        for(int i = 0; i<arr.length; i++)
        {
            if(arr[i]==item)
            {
                index[j] = i;
                j++;
            }

        }
        // Printing the final result
        if(j == 0)
        {
            System.out.println("Element 0 is not present in array");
        }
        else
        {
            System.out.println("Element "+item+" is present at index: ");
            //printing array containg indices of 0 in the original array
            for(int i = 0; i < j; i++)
                System.out.print(index[i]+" ");
            System.out.println();
        }
    }
}
Output:

Enter the number of elements in the array: 9
Enter the elements: 2 0 7 0 3 4 0 9 6 
Original Array: 2 0 7 0 3 4 0 9 6 
Element 0 is present at index: 
1 3 6

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Related Java Programs:

Java Program to Find the Duplicate Values of an Array of String Values

Java Program to Find the Duplicate Values of an Array of String Values

In the previous article, we have seen Java Program to Remove Duplicate Elements in an Array

In this article we are going to find duplicates elements in a string array in Java.

Java Program to Find the Duplicate Values of an Array of String Values

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to find duplicate string value in a string array.

Method-1: Java Program to Find the Duplicate Values of an Array of String Values By Static Initialization of Array Elements

Approach:

  • Create a string array.
  • Display the array.
  • Traverse through the array and print all duplicate elements from the array by comparing them to the next element.

Program:

import java.util.*;
public class Main
{    
    public static void main(String args[])
    {
        // Crating an array
        String arr[] = {"cat", "dog", "mouse", "elephant", "cat", "mouse", "lion", "zebra"};
        // Displaying the array
        System.out.print("Array: ");
        printArray(arr);
        System.out.print("The duplicate elements are : ");
        // Print non duplicate elements
        printDupes(arr);
    }

    // Function to print the array
    static void printArray(String arr[])
    {
        for(int i = 0; i < arr.length ; i++)
            System.out.print(arr[i]+" ");
        System.out.println();
    }
    
    public static void printDupes(String arr[])
    {  
        // Counter
        int j = 0;
        // Checks for duplicate elements
        for (int i=0; i<arr.length-1; i++)
        {
            for(j=i+1;j<arr.length;j++)
                if (arr[i].equals(arr[j])&&i!=j)
                {
                    System.out.print(arr[j]+" "); 
            }  
        }
    }  
}


Output:

Array: cat dog mouse elephant cat mouse lion zebra 
The duplicate elements are : cat mouse

Method-2: Java Program to Find the Duplicate Values of an Array of String Values By Dynamic Initialization of Array Elements

Approach:

  • Take input of array size.
  • Then take input of string array elements.
  • Display the array.
  • Traverse through the array and print all duplicate elements from the array by comparing them to the next element.

Program:

import java.util.*;
public class Main
{    
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in); 
        System.out.print("Enter the number of elements in the array: "); 
        int num = sc.nextInt(); 
        String arr[] = new String[num]; 
        System.out.println("Enter the elements: "); 
        for (int i = 0; i <arr.length; i++) 
        { 
            arr[i] = sc.next(); 
        }
        
        // Displaying the array
        System.out.print("Array: ");
        printArray(arr);
        System.out.print("The duplicate elements are : ");
        // Print non duplicate elements
        printDupes(arr);
    }

    // Function to print the array
    static void printArray(String arr[])
    {
        for(int i = 0; i < arr.length ; i++)
            System.out.print(arr[i]+" ");
        System.out.println();
    }
    
    public static void printDupes(String arr[])
    {  
        // Counter
        int j = 0;
        // Checks for duplicate elements
        for (int i=0; i<arr.length-1; i++)
        {
            for(j=i+1;j<arr.length;j++)
                if (arr[i].equals(arr[j])&&i!=j)
                {
                    System.out.print(arr[j]+" "); 
            }  
        }
    }  
}


Output:

Enter the number of elements in the array: 5
Enter the elements: 
rat
cat
bat
rat
mat
Array: rat cat bat rat mat 
The duplicate elements are : rat

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.

Related Java Programs:

Equilibrium index java – Java Program to Find Equilibrium Indices from a Given Array of Integers

Java Program to Find Equilibrium Indices from a Given Array of Integers

Equilibrium index java: In the previous article, we have seen Java Program to Print All the Unique Elements of an Array

In this article we are going to find the equilibrium indices in an integer array in Java.

Java Program to Find Equilibrium Indices from a Given Array of Integers

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Equilibrium Index:

In an array, an equilibrium index refers to an index into the array such that the sum of elements at lower indices is equal to the sum of elements at higher indices.

For example:

A0 = -8
A1= 2 
A2 = 5  
A3 = 2 
A4 = -5  
A5 = 3
A6 = 0

Here 3 is an equilibrium index. As  A0+A1+A2 = A4+A5+A6
Also 6 is an equilibrium index. As  A0+A1+A2+A3+A4+A5+A6 = 0(sum of zero element is 0)

Let’s see different ways to find duplicate string value in a string array.

Method-1: Java Program to Find the Duplicate Values of an Array of String Values By Static Initialization of Array Elements

Approach:

  • Create an array
  • Display the array
  • Find the sum of all elements of the array and store them
  • Traverse through the array and add elements in each iteration
    • Check where the iterating sum is equal to the difference between the total sum and the iterating sum
    • Print the indices.

Program:

import java.util.*;
public class Main
{    
    public static void main(String args[])
    {
        // Crating an array
        int arr[] = {-7, 1, 5, 2, -4, 3, 0};
        // Displaying the array
        System.out.print("Array: ");
        printArray(arr);
        // Print equilibrium indices
        equIndice(arr);
    }

    // Function to print the array
    static void printArray(int arr[])
    {
        for(int i = 0; i < arr.length ; i++)
            System.out.print(arr[i]+" ");
        System.out.println();
    }
    
    static void equIndice(int[] arr)
    {
        //find sum of all elements
        int sum = 0;
        for (int i : arr) 
        {
            sum += i;
        }
        //compare current sum with total sum to find equilibrium indices
        int currentSum = 0;
        for (int i = 0; i < arr.length; i++) 
        {
            int n = arr[i];
            if (sum - currentSum - n == currentSum) 
            {
                System.out.println("Equilibrium indices found at : "+i);
            }
            currentSum += n;
        }
    }
}

Output:

Array: -7 1 5 2 -4 3 0 
Equilibrium indices found at : 3
Equilibrium indices found at : 6

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs:

Java Program to Convert an Array-List to Array

Java Program to Convert an Array-List to Array

In the previous article, we have seen Java Program to Convert an Array to Array-List

In this article we are going to see how we can convert an ArrayList into an Array in Java.

Java Program to Convert an Array-List to Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways how to convert an ArrayList into an Array.

Method-1: Java Program to Convert an Array-List to Array By Using toArray( ) function

Approach:

  • Create an arraylist.
  • Display the arraylist to the user.
  • Convert the arraylist into array by using toArray() function.
  • Display the array.

Program:

import java.util.*;
public class Main
{    
    public static void main(String args[])
    {
        // Creating an arraylist
        ArrayList<String> arrlist = new ArrayList<String>();
        // Adding elements to arraylist
        arrlist.add("Mango");
        arrlist.add("Apple");
        arrlist.add("Papaya");
        // Displaying the arraylist
        System.out.println("ArrayList: " + arrlist);
        // Creating the array and converting arraylist to array
        String[] arr = arrlist.toArray(new String[0]);
        // Displaying the array to the user
        System.out.print("Array: ");
        printArray(arr);
    }

    // Function to print the array
    static void printArray(String arr[])
    {
        for(int i = 0; i < arr.length ; i++)
            System.out.print(arr[i]+" ");
        System.out.println();
    }
}

Output:

ArrayList: [Mango, Apple, Papaya]
Array: Mango Apple Papaya

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

Related Java Programs: