Java Program to Replace Each Element of the Array with Sum of All Other Elements of the Array

Java Program to Replace Each Element of the Array with Sum of All Other Elements of the Array

In the previous article, we have seen Java Program to Replace Each Element of the Array with Product of All Other Elements of the Array

In this article we are going to see how we can replace the elements of an array with the sum of all other elements using Java programming language.

Java Program to Replace Each Element of the Array with Sum of All Other Elements of the 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

Method-1: Java Program to Replace Each Element of the Array with Sum of All Other Elements of the Array By Static Initialization of Array Elements

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Find the sum of all elements by iterating using a for loop.
  • Then subtract the current element from the sum and replace itself with the result, do it for each element of the array.
  • Print the new array.

Program:

import java.util.Arrays;
public class array
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {1,2,3,4};

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        // Stores the sum of all elements in the array
        int sum = 0;        
        for(int i:arr)
        {
            sum+=i;
        }

        // Subtract the current element from the sum and replace itself with the result
        for(int i=0;i<arr.length;i++)
        {
            arr[i] = sum-arr[i];
        }

        System.out.println("The array elements after replacement"+Arrays.toString(arr));
    }
}
Output:

The array elements are[1, 2, 3, 4]
The array elements after replacement[9, 8, 7, 6]

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.

Related Java Programs:

Java Program to Find the Frequency of Each Element of an Array

Java Program to Find the Frequency of Each Element of an Array

In this article we are going to see how to find out the frequency of each element in an array in Java.

Java Program to Find the Frequency of Each Element 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

Let’s see different ways to find out the frequency of each element in an array.

Method-: Java Program to Find the Frequency of Each Element of an Array By Static Initialization of Array Elements and User Defined Method

Approach:

  • Create an array with elements, and another blank array of same size called freq.
  • Set all the elements in the blank array to -1 using fill( ) library function.
  • Display the array elements to the user.
  • Pass both the arrays into an user function frequency ( ) that finds and stores the number of occurrence of elements.
  • Use a counter variable to count the number of times the element occurs inside the array.
  • Store it in the freq array at same location as the element.
  • Print the elements from the main array where the freq is greater than equals to 1 with the frequency.

Program:

import java.util.*;
import java.util.Scanner;
public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12, 22, 34, 22, 54, 6, 52, 8, 9, 34, 54, 68,10,20,30,20,30,50,10,50,30,20};
        int freq[] = new int[arr.length];
        // Sets all elements in the array to -1
        Arrays.fill(freq, -1);
        // Prints the array elements
        System.out.println("The array elements are "+Arrays.toString(arr));
        
       frequency(arr,freq);

    }
    
    // Function that counts the frequency of elements
    static void frequency (int arr[], int freq[])
    {
        int count;

        for(int i = 0; i<arr.length; i++)
        {
            // Resets count to 1 after each element
            count=1;
            for(int j = i + 1; j<arr.length;j++)
            {
                // If another occurence of the current element is found 
                // in the array then increments the counter
                if(arr[i]==arr[j])
                {
                    count++;
                    freq[j] = 0;
                }
            }
            // Stores the frequency of each element
            if(freq[i]!=0)
            {
                freq[i] = count;
            }
        }
        
        // Prints the elements with their occurences
        System.out.println("The elements and their occurences are");
        for(int i = 0; i<arr.length;i++)
        {
            if(freq[i]>=1)
                System.out.println("Element "+arr[i]+" has occured "+freq[i]+" times.");
        }
    }
}
Output:

The array elements are [12, 22, 34, 22, 54, 6, 52, 8, 9, 34, 54, 68, 10, 20, 30, 20, 30, 50, 10, 50, 30, 20]
The elements and their occurences are
Element 12 has occured 1 times.
Element 22 has occured 2 times.
Element 34 has occured 2 times.
Element 54 has occured 2 times.
Element 6 has occured 1 times.
Element 52 has occured 1 times.
Element 8 has occured 1 times.
Element 9 has occured 1 times.
Element 68 has occured 1 times.
Element 10 has occured 2 times.
Element 20 has occured 3 times.
Element 30 has occured 3 times.
Element 50 has occured 2 times.

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.

Java Program to Find the Product of Middle Row and Middle Column of a Matrix

Java Program to Find the Product of Middle Row and Middle Column of a Matrix

In the previous article, we have seen Java Program to Find the Sum of Middle Row and Middle Column of a Matrix

In this article we are going to see how we can write a program how to calculate product of Middle row and column.

Java Program to Find the Product of Middle Row and Middle Column of a Matrix

A 3*3 Matrix is having 3 rows and 3 columns where this 3*3 represents the dimension of the matrix. Means there are 3*3 i.e. total 9 elements in a 3*3 Matrix.

Let’s understand it in more simpler way.

                   | A00   A01   A02 |
Matrix A =  | A10   A11   A12 |
                   | A20   A21   A22 | 3*3
  • Matrix A represents a 3*3 matrix.
  • A‘ represents the matrix element.
  • Aij‘ represents the matrix element at it’s matrix position/index.
  • i‘ represents the row index.
  • j‘ represents the column index
  • Means A00=Aij  where i=0 and j=0,  A01=aij where i=0 and j=1 and like this.
  • Here we have started row value from 0 and column value from 0.

Let’s see different ways to calculate Product of Middle row and Column.

Method-1: Java Program to Find the Product of Middle Row and Middle Column of a Matrix

Approach:

  • Initialize and declare a matrix.
  • Take a for loop to calculate product of middle row value . for each iteration calculate Pro_row += mat[3 / 2][i]
  • Take a for loop to calculate product of middle column value . for each iteration calculate Pro_col += mat[i][3 / 2]
  • Print the  results .

Program:

import java.util.*;
public class Main 
{
   public static void main(String args[])
   {
       // Initializing the 3X3 matrix i.e. 2D array 
        int mat[][]={{1,2,3},{4,5,6},{7,8,9}};
        int row, col, Pro_row=1,Pro_col=1 ;

        for (int i = 0; i < 3; i++) 
                 Pro_row *= mat[3 / 2][i];
        for (int i = 0; i < 3; i++) 
                 Pro_col *= mat[i][3 / 2];
        int res= Pro_row*Pro_col;
        System.out.println("Product of middle row is : " + Pro_row);
        System.out.println("Product of middle Column is : " + Pro_col);
        System.out.println("Product of middle Row and Column is : " + res);
   }
}

Output:

Product of middle row is : 120
Product of middle Column is : 80
Product of middle Row and Column is : 9600

Method-2:Java Program to Find the Product of Middle Row and Middle Column of a Matrix

Approach :

  • Take input of a matrix.
  • Take a for loop to calculate product of middle row value . for each iteration calculate Pro_row += mat[3 / 2][i]
  • Take a for loop to calculate product of middle column value . for each iteration calculate Pro_col += mat[i][3 / 2]
  • Print the results.

Program :

import java.util.*;
public class Main 
{
   public static void main(String args[])
   {
       Scanner s = new Scanner(System.in);
        // Initializing the 3X3 matrix i.e. 2D array
        int mat[][] = new int[3][3];
        int row, col, Pro_row=1,Pro_col=1 ;
        // Taking matrix input
        System.out.println("Enter matrix elements");
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
                mat[row][col] = s.nextInt();
        for (int i = 0; i < 3; i++) 
                 Pro_row *= mat[3 / 2][i];
        for (int i = 0; i < 3; i++) 
                 Pro_col *= mat[i][3 / 2];
        int res= Pro_row*Pro_col;
        System.out.println("Product of middle row is : " + Pro_row);
        System.out.println("Product of middle Column is : " + Pro_col);
        System.out.println("Product of middle Row and Column is : " + res);
   }
}

Output:

Enter matrix elements 1 2 3 4 5 6 7 8 9
Sum of middle row is : 120
Sum of middle Column is : 80
Sum of middle Row and Column is : 9600

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

Related Java Programs:

Java Program to Find the Sum of Middle Row and Middle Column of a Matrix

Java Program to Find the Sum of Middle Row and Middle Column of a Matrix

In the previous article, we have seen Java Program to Print the elements of the Matrix in Spiral Form

In this article we are going to see how we can write a program how to calculate Sum of Middle row and column.

Java Program to Find the Sum of Middle Row and Middle Column of a Matrix

A 3*3 Matrix is having 3 rows and 3 columns where this 3*3 represents the dimension of the matrix. Means there are 3*3 i.e. total 9 elements in a 3*3 Matrix.

Let’s understand it in more simpler way.

                   | A00   A01   A02 |
Matrix A =  | A10   A11   A12 |
                   | A20   A21   A22 | 3*3
  • Matrix A represents a 3*3 matrix.
  • A‘ represents the matrix element.
  • Aij‘ represents the matrix element at it’s matrix position/index.
  • i‘ represents the row index.
  • j‘ represents the column index
  • Means A00=Aij  where i=0 and j=0,  A01=aij where i=0 and j=1 and like this.
  • Here we have started row value from 0 and column value from 0.

Let’s see different ways to calculate Sum of Middle row and Column.

Method-1: Java Program to Find the Sum of Middle Row and Middle Column of a Matrix By Static Initialization of Array Elements

Approach:

  • Initialize and declare a matrix.
  • Take a for loop to calculate sum of middle row value . for each iteration calculate Sum_row += mat[3 / 2][i]
  • Take a for loop to calculate sum of middle column value . for each iteration calculate Sum_col += mat[i][3 / 2]
  • Print 2 results .

Program:

import java.util.*;
public class Main 
{
   public static void main(String args[])
   {
        Scanner s = new Scanner(System.in);
       
        // Initializing the 3X3 matrix i.e. 2D array
        int mat[][]={{10,20,30},{40,50,60},{70,80,90}};
        int Sum_row=0,Sum_col=0 ;
        for (int i = 0; i < 3; i++) 
                 Sum_row += mat[3 / 2][i];
        for (int i = 0; i < 3; i++) 
                 Sum_col += mat[i][3 / 2];
        System.out.println("Sum of middle row is : " + Sum_row);
        System.out.println("Sum of middle Column is : " + Sum_col);
        int res = Sum_row+Sum_col;
        System.out.println("Sum of middle row and Column is : " + res);
   }
}
Output:

Sum of middle row is : 150
Sum of middle Column is : 150
Sum of middle row and Column is : 300

Method-2: Java Program to Find the Sum of Middle Row and Middle Column of a Matrix By Dynamic Initialization of Array Elements

Approach :

  • Take input of a matrix.
  • Take a for loop to calculate sum of middle row value . for each iteration calculate Sum_row += mat[3 / 2][i]
  • Take a for loop to calculate sum of middle column value . for each iteration calculate Sum_col += mat[i][3 / 2]
  • Print 2 results .

Program :

import java.util.*;
public class Main 
{
   public static void main(String args[])
   {
       Scanner s = new Scanner(System.in);
        // Initializing the 3X3 matrix i.e. 2D array
        int mat[][] = new int[3][3];
        int row, col, Sum_row=0,Sum_col=0 ;
        // Taking matrix input
        System.out.println("\nEnter matrix elements");
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
                mat[row][col] = s.nextInt();
        for (int i = 0; i < 3; i++) 
                 Sum_row += mat[3 / 2][i];
        for (int i = 0; i < 3; i++) 
                 Sum_col += mat[i][3 / 2];
        int res= Sum_row+Sum_col;
        System.out.println("Sum of middle row is : " + Sum_row);
        System.out.println("Sum of middle Column is : " + Sum_col);
        System.out.println("Sum of middle Row and Column is : " + res);
   }
}

Output:

Enter matrix elements 1 2 3 4 5 6 7 8 9
Sum of middle row is : 15
Sum of middle Column is : 15
Sum of middle Row and Column is : 30

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

Related Java Programs:

Java Program to Find the Number of Even and Odd Integers in an Array of Integers

Java Program to Find the Number of Even and Odd Integers in an Array of Integers

In the previous article, we have seen Java Program to Separate Odd and Even Integers in Separate Arrays

In this article we are going to see how to find number of odd and even integers in separate arrays in Java.

Java Program to Find the Number of Even and Odd Integers in an 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

Let’s see different ways to find number of odd and even integers in separate arrays.

Method-1: Java Program to Find Number of Even and Odd Integers in an Array of Integers By Static Initialization of Array Elements

Approach:

  • Create an array with elements.
  • Display the array elements to the user.
  • Pass both the arrays into an user function segregate() that segregates the elements by traversing through the array and storing odd and even elements at their respective arrays.
  • Print count of even and odd elements.

Program:

import java.util.*;

public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {2,3,4,5,6,7,8,9};
        // Prints the array elements
        System.out.println("The array elements are "+ Arrays.toString(arr));
        
        segregate(arr);

    }
    
    // Function that segregates the array into two arrays
    static void segregate(int arr[])
    {
        int oddCount = 0, evenCount = 0;
        // Segregating the array into two smaall arrays odd and even
        for(int i:arr)
        {
            if(i%2==0)
                evenCount+=1;
            else
                oddCount+=1;
        }

        System.out.print("\nThe number of odd elements are : "+oddCount);
        
        System.out.print("\nThe number of even elements are : "+evenCount);
    }
}
Output: 

The array elements are [2, 3, 4, 5, 6, 7, 8, 9]

The number of odd elements are : 4
The number of even elements are : 4

Method-2: Java Program Separate the Number of Even and Odd Integers in an Array of Integers By Dynamic Initialization of Array Elements

Approach:

  • Create an array by taking array elements as input.
  • Display the array elements to the user.
  • Pass both the arrays into an user function segregate() that segregates the elements by traversing through the array and storing odd and even elements at their respective arrays.
  • Print count of even and odd elements.

Program:

import java.util.*;

public class Main
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        
        // Taking size as input from the user
        System.out.println("Enter the array size :");
        int size = scan.nextInt();
        
        // Creating the array
        int arr[] = new int[size];
        
        // Entering the array elements
        System.out.println("Enter array elements : ");
        for(int i=0;i<size;i++)
        {
            arr[i] = scan.nextInt();
        }
        
        // Prints the array elements
        System.out.println("The array elements are "+ Arrays.toString(arr));
        
        segregate(arr);

    }
    
    // Function that segregates the array into two arrays
    static void segregate(int arr[])
    {
        int oddCount = 0, evenCount = 0;
        // Segregating the array into two smaall arrays odd and even
        for(int i:arr)
        {
            if(i%2==0)
                evenCount+=1;
            else
                oddCount+=1;
        }

        System.out.print("\nThe number of odd array elements are : "+oddCount);
        
        System.out.print("\nThe number of even array elements are : "+evenCount);

    }
}
Output:

Enter the array size :
Enter array elements : 
The array elements are [1, 2, 3, 4, 5]

The number of odd array elements are : 3
The number of even array elements are : 2

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 Elements from an Array which are Greater than a Given Number

Java Program to Find the Elements from an Array which are Greater than a Given Number

In the previous article, we have seen Java Program to Separate Positive Negative and Zero elements from Array and Store in Separate arrays

In this article we are going to see how to Find the Elements from an Array which are Greater than a Given Number.

Java Program to Find the Elements from an Array which are Greater than a Given Number

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 Elements from an Array which are Greater than a Given Number.

Method-1: Java Program to Find the Elements from an Array which are Greater than a Given Number By Static Initialization of Array Elements

Approach:

  1. Iterate over the array.
  2. Check if any element is greater than the given number then print.

Program:

public class Main
{
    public static void main(String[] args) 
    {
        // initialize the array
        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int num = 5;

        // call the method
        System.out.print("Elements Greater than " + num + " are: ");
        findGreater(arr, num);
    }

    public static void findGreater(int[] arr, int num) 
    {
        for (int i : arr) 
        {
            if (i > num) 
            {
                System.out.print(i + " ");
            }

        }
    }
}

Output:

Elements Greater than 5 are: 6 7 8 9 10

Method-2: Java Program to Find the Elements from an Array which are Greater than a Given Number By Dynamic Initialization of Array Elements

Approach:

  1. Create scanner class object.
  2. Ask use length of the array.
  3. Initialize the array with given size.
  4. Ask the user for array elements.
  5. Iterate over the array.
  6. Check if any element is greater than the given number then print

Program:

import java.util.Scanner;

public class Main
{
    public static void main(String[] args) 
    {
        // initialize the array
        // 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();
        }
        // take input from user for element to be searched
        System.out.print("Enter the number: ");
        int num = sc.nextInt();

        // call the method
        System.out.print("Elements Greater than " + num + " are: ");
        findGreater(arr, num);
    }

    public static void findGreater(int[] arr, int num) 
    {
        // comapare each element of array with num
        for (int i : arr) 
        {
            if (i > num) 
            {
                System.out.print(i + " ");
            }

        }
    }
}

Output:

Enter the size of array: 5
Enter array elements: 1 5 3 2 4
Enter the number: 3
Elements Greater than 3 are: 5 4

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

Related Java Programs:

Java Program to Find Continuous Sub array Whose Sum is Equal to a Given Number

Java Program to Find Continuous Sub array Whose Sum is Equal to a Given Number

In the previous article, we have seen Java Program to Count Strings and Integers from an Array

In this article we are going to see how to find continuous sub array whose sum is equal to given number.

Java Program to Find Continuous Sub array Whose Sum is Equal to a Given Number

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 continuous sub array whose sum is equal to given number.

Method-1: Java Program to Find Continuous Sub array Whose Sum is Equal to a Given Number By Static Initialization of Array Elements

Approach:

  1. Initialize the sum to first element of the inputArray.
  2. Starting from the second element, go on adding each element of inputArray to sum one by one.
  3. If the sum exceeds the requiredSum then we remove starting elements from the sum until sum becomes either smaller than or equal to the requiredSum.
  4. If sum becomes equal to requiredSum then print that sub array.
  5. If sum becomes smaller than requiredSum, then we continue the execution of loop.

Program:

import java.util.Arrays;

public class Main
{
    public static void main(String[] args) 
    {
        int[] arr = { 27, 5, 3, 80, 7, 9, 12 };
        int requiredSum = 95;
        findSubArray(arr, requiredSum);

    }

    static void findSubArray(int[] arr, int requiredSum) 
    {
        // Initializing sum with the first element of the inputArray
        int sum = arr[0], start = 0;
        // Iterating through inputArray starting from second element
        for (int i = 1; i < arr.length; i++) 
        {

            // Adding inputArray[i] to the current 'sum'
            if (sum == requiredSum) {
                System.out.print("Continuous sub array of " + Arrays.toString(arr) + " whose sum is "
                        + requiredSum + " is [ ");
                for (int j = start; j < i; j++) 
                {
                    // If 'sum' is equal to 'requiedSum' then printing the sub array
                    System.out.print(arr[j] + " ");
                }
                System.out.println("]");
            }
            sum = sum + arr[i];

            // If sum is greater than requiedSum then following loop is executed until
            // sum becomes either smaller than or equal to requiedSum
            while (sum > requiredSum && start <= i - 1) 
            {
                // Removing starting elements from the 'sum'
                sum = sum - arr[start];
                // Incrementing start by 1
                start++;
            }

        }
    }
}

Output:

Continuous sub array of [27, 5, 3, 80, 7, 9, 12] whose sum is 95 is [ 5 3 80 7 ]

Method-2: Java Program to Find Continuous Sub array Whose Sum is Equal to a Given Number By Dynamic Initialization of Array Elements

Approach:

  • Create scanner class object.
  • Ask use length of the array.
  • Initialize the array with given size.
  • Ask the user for array elements.
  • Initialize sum variable with arr[0].
  • Run two nested loops and try out every possible continuous subarray.
  • Inside the inner loop(counter j) increment sum by the jth element of the array.
  • Check if the sum==requiredSum.
  • If yes, print the subarray.
  • If it’s greater then break the inner loop and if less then continue the current execution.

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.print("Enter the required sum: ");
        int requiredSum = sc.nextInt();
        findSubArray(arr, requiredSum);

    }

    static void findSubArray(int[] arr, int requiredSum) 
    {
        // Initializing 'sum' to 0

        int sum = 0;

        // Iterating through 'inputArray'

        for (int i = 0; i < arr.length; i++) 
        {
            // Assigning inputArray[i] to 'sum'

            sum = arr[i];

            for (int j = i + 1; j < arr.length; j++) 
            {
                // Adding inputArray[j] to 'sum'

                sum = sum + arr[j];

                // If 'sum' is equal to 'inputNumber' then printing the sub array

                if (sum == requiredSum) 
                {
                    System.out.print("Continuous sub array of " + Arrays.toString(arr) + " whose sum is "
                            + requiredSum + " is [ ");

                    for (int k = i; k <= j; k++) 
                    {
                        System.out.print(arr[k] + " ");
                    }

                    System.out.println("]");
                }

                // if 'sum' is smaller than 'inputNumber', continue the loop

                else if (sum < requiredSum) 
                {
                    continue;
                }

                // if 'sum' is greater than 'inputNumber', then break the loop

                else if (sum > requiredSum) 
                {
                    break;
                }
            }
        }
    }

}

Output:

Enter the size of array: 6
Enter array elements: 7 2 5 3 1 4
Enter the required sum: 9
Continuous sub array of [7, 2, 5, 3, 1, 4] whose sum is 9 is [ 7 2 ]
Continuous sub array of [7, 2, 5, 3, 1, 4] whose sum is 9 is [ 5 3 1 ]

Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

Related Java Programs:

Java Program to Find the Intersection of Two Arrays of String

Java Program to Find the Intersection of Two Arrays of String

In the previous article, we have seen  Java Program to Find Continuous Sub array Whose Sum is Equal to a Given Number

In this article we are going to see how to find the intersection of two arrays of String.

Java Program to Find the Intersection of Two Arrays of String

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 intersection of two arrays of String.

Method-1: Java Program to Find the Intersection of Two Arrays of String By Using  retainAll() method

Approach:

  1. Create two HashSets using given two arrays.
  2. then use retainAll() method of HashSet to retain only common elements from the two sets.

Program:

import java.util.Arrays;
import java.util.HashSet;

public class Main 
{
    public static void main(String[] args) 
    {
        String[] s1 = { "a", "b", "d" };
        String[] s2 = { "a", "b", "c", "d", "e" };
        print_intersection(s1, s2);

    }

    static void print_intersection(String[] s1, String[] s2) 
    {

        HashSet<String> set1 = new HashSet<>(Arrays.asList(s1));

        HashSet<String> set2 = new HashSet<>(Arrays.asList(s2));

        set1.retainAll(set2);

        System.out.println("Intersection: " + set1);
    }

}


Output:

Intersection: [a, b, d]

Method-2: Java Program to Find the Intersection of Two Arrays of String By Dynamic Initialization of Array Elements

Approach:

  1. Iterate both the given arrays.
  2. Compare each element of one array with elements of other array.
  3. If the elements are found to be equal, add that element into HashSet.

Program:

import java.util.HashSet;
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();
        // extra Scanner.nextLine() to consume the newline character due to
        // enter key else it will skip the next nextLine() inside the loop.
        sc.nextLine();
        // initialize array with size n
        String[] s1 = new String[n];
        // take input from user for array elements
        System.out.println("Enter array elements: ");
        for (int i = 0; i < n; i++) {
            s1[i] = sc.nextLine();
        }
        System.out.print("Enter the size of array: ");
        int m = sc.nextInt();
        // extra Scanner.nextLine() to consume the newline character due to
        // enter key else it will skip the next nextLine() inside the loop.
        sc.nextLine();
        // initialize array with size m
        String[] s2 = new String[m];
        // take input from user for array elements
        System.out.println("Enter array elements: ");
        for (int i = 0; i < m; i++) {
            s2[i] = sc.nextLine();
        }
        print_intersection_iterative(s1, s2);

    }

    static void print_intersection_iterative(String[] s1, String[] s2) 
    {
        HashSet<String> set = new HashSet<String>();

        for (int i = 0; i < s1.length; i++)
        {
            for (int j = 0; j < s2.length; j++)
            {
                if(s1[i].equals(s2[j]))
                {
                    set.add(s1[i]);
                }
            }
        }

        System.out.println("Intersection: " + set);
    }

}

Output:

Enter the size of array: 4
Enter array elements: 
a
b
c
d
Enter the size of array: 3
Enter array elements: 
a
f
d
Intersection: [a, d]

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

Related Java Programs:

Java Program to Arrange the Elements of a Given Array of Integers Where All Negative Integers Appear Before All the Positive Integers

Java Program to Arrange the Elements of a Given Array of Integers Where All Negative Integers Appear Before All the Positive Integers

In the previous article, we have seen Java Program to Cyclically Rotate a Given Array Clockwise by One

In this article we are going to see how to arrange the elements of a given array of integers where all negative integers appear before all the positive integers using Java programming language.

Java Program to Arrange the Elements of a Given Array of Integers Where All Negative Integers Appear Before All the Positive 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

Let’s see different ways to arrange the elements of a given array of integers where all negative integers appear before all the positive integers.

Method-1: Java Program to Arrange the Elements of a Given Array of Integers Where All Negative Integers Appear Before All the Positive Integers By Static Initialization of Array Elements

Approach:

  • Declare and initialize an array.
  • Initialize two pointers, i=0, j=arr.length–1.
  • While i<=j, if the element at i is negative, increment i.
  • If the element at j is positive, decrement j.
  • Now at index i, there is a positive element and at index j, there is negative element, so swap these two.

Program:

public class Main
{
    public static void main(String[] args) 
    {
        // initialize the array
        int[] arr = { -1, 2, -3, 4, -5, 6, 7, -8, 9, -10 };
        System.out.println("The array is : ");
        //calling printArray() method
        printArray(arr);
        
        // calling the method
        modifyMethod(arr);
        
        // printing the array
       System.out.println("The modified array is : ");
       //calling printArray() method
        printArray(arr);

    }

    //modifyMethod() method to bring all negative numbers first 
    //then positive elements in array
    static void modifyMethod(int[] arr) 
    {
        // initialize two pointers
        int i = 0;
        int j = arr.length - 1;
        while (i <= j) {
            // if the element at i is negative, increment i
            if (arr[i] < 0 )
            i++;
            // if the element at j is positive, decrement j
            if (arr[j] > 0)
                j--;
            // swap the elements
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }

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

Output:

The array is : 
-1 2 -3 4 -5 6 7 -8 9 -10 
The modified array is : 
-1 -10 -3 -8 6 -5 7 4 9 2

Method-2: Java Program to Arrange the Elements of a Given Array of Integers Where All Negative Integers Appear Before All the Positive Integers By Dynamic Initialization of Array Elements

Approach:

  • Ask use length of the array.
  • Initialize the array with given size.
  • Ask the user for array elements.
  • Initialize two pointers, i=0, j=arr.length–1.
  • While i<=j, if the element at i is negative, increment i.
  • If the element at j is positive, decrement j.
  • Now at index i, there is a positive element and at index j, there is negative element, so swap these two.

Program:

import java.util.Scanner;

public class Main
{
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        // asking user to enter the number of elements
        System.out.println("Enter number of elements in the array: ");
        int n = sc.nextInt();
        // initializing the array
        int[] arr = new int[n];
        // asking user to enter the elements
        System.out.println("Enter elements of the array: ");
        for (int i = 0; i < n; i++) 
        {
            arr[i] = sc.nextInt();
        }
        
         System.out.println("The array is : ");
         printArray(arr);
        
        
         // calling the method
         modifyMethod(arr);
        
         System.out.println("The modified array is : ");
         printArray(arr);

    }

    static void modifyMethod(int[] arr) 
    {
        // initialize two pointers
        int i = 0;
        int j = arr.length - 1;
        while (i <= j) {
            // if the element at i is negative, increment i
            if (arr[i] < 0 )
            i++;
            // if the element at j is positive, increment j
            if (arr[j] > 0)
                j--;
            // swap the elements
            if (i <= j) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
                j--;
            }
        }
    }
    
    //printArray() method to print the array 
    static void printArray(int[] arr) 
    { 
        // printing array 
        for (int i=0; i<arr.length; i++) 
        { 
            System.out.print(arr[i] + " "); 
        } 
        System.out.println("");
    }
}
Output:

Enter number of elements in the array: 5
Enter elements of the array: 2 3 -1 -8 -4
The array is : 
2 3 -1 -8 -4 
The modified array is : 
-4 -8 -1 3 2

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.

Related Java Programs:

Java Program to Cyclically Rotate a Given Array Clockwise by One

Java Program to Cyclically Rotate a Given Array Clockwise by One

In the previous article, we have seen Java Program to Find all the Combination of Four Elements Where Sum of All the Four Elements are Equal to a Specified Number

In this article we are going to see how to cyclically rotate an array clockwise by one using Java Programming Language.

Java Program to Cyclically Rotate a Given Array Clockwise by One

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  cyclically rotate an array clockwise by one.

Method-1: Java Program to Cyclically Rotate a Given Array Clockwise by One By Static Initialization of Array Elements

Approach:

  • Declare and initialize an array.
  • Store the last element of the array in a temp variable.
  • Iterate over the array and shift the elements by one place to the right.
  • Store the temp variable at the 0th index.

Program:

public class Main 
{
    public static void main(String[] args) 
    {
        // initializing array
        int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
        System.out.println("The array is : ");
        printArray(arr);
        
        // calling the function
        rotate_by_one(arr);
        
        System.out.println("After rotation the array is : ");
        printArray(arr);
    }

    static void rotate_by_one(int arr[]) 
    {
        // initializing variables
        int temp = arr[arr.length - 1];
        // looping through the array shifting the elements
        for (int i = arr.length - 1; i > 0; i--) 
        {
            arr[i] = arr[i - 1];
        }
        //Storing tempvalue at 0th index of array.
        arr[0] = temp;
    }
    
    //printArray() method to print the array 
    static void printArray(int[] arr) 
    { 
        // printing array 
        for (int i=0; i<arr.length; i++) 
        { 
            System.out.print(arr[i] + " "); 
        } 
        System.out.println("");
    }
}

Output:

The array is : 
1 2 3 4 5 6 7 
After rotation the array is : 
7 1 2 3 4 5 6

Method-2: Java Program to Cyclically Rotate a Given Array Clockwise by One By Dynamic Initialization of Array Elements

Approach:

  • Ask use length of the array.
  • Initialize the array with given size.
  • Ask the user for array elements.
  • Store the last element of the array in a temp variable.
  • Iterate over the array and shift the elements by one place to the right.
  • Store the temp variable at the 0th index

Program:

import java.util.*;

public class Main 
{
    public static void main(String[] args) 
    {
        //Scanner class object created
        Scanner sc = new Scanner(System.in);
        
        // asking user to enter the number of elements
        System.out.println("Enter number of elements in the array : ");
        int n = sc.nextInt();
        
        // initializing the array
        int[] arr = new int[n];
        
        // asking user to enter the elements
        System.out.println("Enter elements of the array : ");
        for (int i = 0; i < n; i++) 
        {
            arr[i] = sc.nextInt();
        }

        System.out.println("The array is : ");
        printArray(arr);
        
        // calling the function
        rotate_by_one(arr);
        
        System.out.println("After rotation the array is : ");
        printArray(arr);
    }

    static void rotate_by_one(int arr[]) 
    {
        // initializing variables
        int temp = arr[arr.length - 1];
        // looping through the array shifting the elements
        for (int i = arr.length - 1; i > 0; i--) 
        {
            arr[i] = arr[i - 1];
        }
        //Storing tempvalue at 0th index of array.
        arr[0] = temp;
    }
    
    //printArray() method to print the array 
    static void printArray(int[] arr) 
    { 
        // printing array 
        for (int i=0; i<arr.length; i++) 
        { 
            System.out.print(arr[i] + " "); 
        } 
        System.out.println("");
    }
}

Output:

Enter number of elements in the array : 
Enter elements of the array : 
The array is : 
1 2 3 4 5 
After rotation the array is : 
5 1 2 3 4

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: