Java Program to Reverse Words of a Sentence

Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.

Java Program to Reverse Words of a Sentence

  • Java program to reverse a sentence.
  • Write a java program to reverse words of a sentence.

Given a sentence, we have to reverse the sequence of words in given sentences. Words of the given sentence are separated by one or multiple space characters.

For Example,
Input Sentence : I love Java Programming
Output Sentence : Programming Java love I

To split a string to multiple words separated by spaces, we will call split() method.
public String[] split(String regex);
split() method returns an array of Strings, after splitting string based of given regex(delimiters).

Java program to reverse words of a sentence

Java program to reverse words of a sentence

package com.tcc.java.programs;
 
import java.util.Scanner;
 
/**
 * Java Program to
 */
public class ReverseSentence {
    public static void main(String[] args) {
        String input;
        String[] words;
        int i;
        Scanner scanner = new Scanner(System.in);
 
        System.out.println("Enter a Sentence");
        input = scanner.nextLine();
        // Split sentence into words using split method of String
        words = input.split(" ");
        // Now, Print the sentence in reverse order
        System.out.println("Reversed Sentence");
        for (i = words.length - 1; i >= 0; i--) {
            System.out.print(words[i] + " ");
        }
    }
}

Output

Enter a Sentence
I love Java Programming
Reversed Sentence
Programming Java love I

Java Program to Count Words in a Sentence

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 Program to Count Words in a Sentence

  • Java program to count words in a sentence using split method.

To count the number of words in a sentence, we first take a sentence as input from user and store it in a String object. Words in a sentence are separated by space character(” “), hence we can use space as a delimiter to split given sentence into words. To split a string to multiple words separated by spaces, we will call split() method.

public String[] split(String regex);
split() method returns an array of Strings, after splitting string based of given regex(delimiters). To fine the count of words in sentence, we will find the length of String array returned by split method.

Java program to find the count of words in a sentence

Java program to find the count of words in a sentence

package com.tcc.java.programs;
 
import java.util.Scanner;
 
/**
 * Java Program to Count Words in Sentence
 */
public class WordCount {
    public static void main(String args[]) {
        String str;
        Scanner scanner = new Scanner(System.in);
 
        System.out.println("Enter a Sentence");
        str = scanner.nextLine();
 
        // Printing number of words in given sentence
        System.out.println("Number of Words = " + str.split(" ").length);
    }
}

Output

Enter a Sentence
I Love Java Programming
Number of Words = 4

Java Program to Delete All Space Characters from a String

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

Java Program to Delete All Space Characters from a String

  • Java program to remove all space characters from a string using replaceAll() method.

In this java program, we have to delete all occurrences of space characters from a given string and then print it on screen.

For Example,
Input String : BTechGeeks
Output String : BTechGeeks

Java program to remove all spaces from string using replaceAll method

In this java program, we will first take a string as input from user and store it in a String object “str”. To delete all space characters from str, we will call replaceAll() method of String class. This method replaces any occurrence of space characters(including multiple adjacent space characters) with “”. We are using “[ ]” regular expression, which matches with any space character.

Java program to remove all spaces from string using replaceAll method

package com.tcc.java.programs;
 
import java.util.Scanner;
 
/**
 * Java Program to remove all spaces from String
 */
public class DeleteSpaces {
    public static void main(String args[]) {
        String str, output;
        Scanner scanner = new Scanner(System.in);
 
        System.out.println("Enter a String");
        str = scanner.nextLine();
 
        // Deleting all space characters from given string
        // usnig replaceAll method
        output = str.replaceAll("[ ]", "");
 
        System.out.println("Output String\n" + output);
    }
}

Output

Enter a String
I love  Java  Programming
Output String
IloveJavaProgramming
Enter a String
Java Programm     to remove spaces
Output String
JavaProgrammtoremovespaces

Java Program to Calculate Arithmetic Mean of N Numbers

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 Calculate Arithmetic Mean of N Numbers

  • Write a java program to find average of N numbers using for loop.

Given a set of N numbers, we have to calculate and print the arithmetic mean of given N numbers. Arithmetic mean is also known as average.

For Example,
Input Numbers : 12 7 9 10 3 15 16 2
Arithmetic Mean : 9.25
In this java program, we first ask user to enter the number of elements as store it in an integer variable “count”. Then we take “count” numbers as input from user using for loop and add them in variable “sum”. At the end of for loop, “sum” will contain the total sum of all input numbers. Now, to calculate arithmetic mean we will divide and “sum” by “count”.

Java program to calculate the average of N numbers

Java program to calculate the average of N numbers

package com.tcc.java.programs;
 
import java.util.Scanner;
 
/**
 * Java Program to find mean of N numbers
 */
public class MeanNumber {
    public static void main(String[] args) {
        int count, i;
        float sum = 0, mean;
        Scanner scanner;
        scanner = new Scanner(System.in);
 
        System.out.println("Enter Number of Elements");
        count = scanner.nextInt();
 
        System.out.println("Enter " + count + " Elements");
        for (i = 0; i < count; i++) {
            sum += scanner.nextInt();
        }
        // Mean or Average = Sum/Count
        mean = sum / count;
 
        System.out.println("Mean : " + mean);
    }
}

Output

Enter Number of Elements
6
Enter 6 Elements
10 9 15 20 30 22
Mean : 17.666666

Java Program to Add an Element to Every Other Elements of the Array

Java Program to Add an Element to Every Other Elements of the Array

In the previous article, we have seen Java Program to Divide an Element to Every Other Elements of the Array

In this article we are going to see how we can add an element to every other elements of the array except itself by using Java Language.

Java Program to Add an Element to Every 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

Let’s see different ways to add an element to every other elements of the array except itself.

Method-1: Java Program to Add an Element to Every Element of the Array By Static Initialization of Array Elements

Approach:

  • Declare and initialize an array.
  • Enter the index of array element to find that specific element.
  • This array element  will be added with other array elements.
  • Iterate each element of the array and add that specific array element with others elements except self.

Program:

public class Main
{

    public static void main(String[] args) 
    {
        //array initialized
        int arr[] = {10,20,30,40,50,60};
        // creating new array with size of actual array 
        int result[]= new int[arr.length];
        
        System.out.println("Array length is : "+arr.length);
        
        //declaring arrauy index of the specified number 
        //which will be added with other array elements
        int num  = 2;
        
        //if the entered index(means specified number) exists in the array 
        //then only the specifed array element can be added with other array elements 
        if(num<arr.length)
        {
            //iterating the array
           for(int i=0;i<arr.length;i++)
           {
               // checking condition 
               // if array element is not the specified number 
               // then it will enter into the if block 
               // and the number will be added with other elements except itself 
               if(arr[i]!=arr[num])
               {
                    // adding the specifed array element with other array elements
                    result[i] = arr[i]+arr[num];
               }
           }
        }
        
        //assigning the specified number to the same index of result array
        //as the specified number will be same 
        result[num]=arr[num];
        
        //printing the result array 
        System.out.println("New array after addition of array with a specific array element : ");
        for(int i=0;i<result.length;i++)
        {
            System.out.print(result[i]+" ");
        }    
   }
}
Output:
Array length is : 6
New array after addition of array with a specific array element : 
40 50 30 70 80 90

Method-2: Java Program to Add an Element to Every Element of the Array By Dynamic Initialization of Array Elements

Approach:

  • Take the array size as user input.
  • Then take array elements as user input.
  • Enter the index of array element to find that specific element.
  • This array element  will be added with other array elements.
  • Iterate each element of the array and add that specific array element with others elements except self.

Program:

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];
        // creating new array with size of actual array 
        int result[]= new int[arr.length];
        
        // 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("Array length is : "+arr.length);
        
        //taking input of array index
        System.out.print("Enter index of the element to be added : ");
        int num  = sc.nextInt();
        
        //if the entered index(means specified number) exists in the array 
        //then only the specifed array element can be added with other array elements 
        if(num<arr.length)
        {
            //iterating the array
           for(int i=0;i<arr.length;i++)
           {
               // checking condition 
               // if array element is not the specified number 
               // then it will enter into the if block 
               // and the number will be added with other elements except itself
               if(arr[i]!=arr[num])
               {
                    // adding the speciifed array element with other array elements
                    result[i] = arr[i]+arr[num];
               }
           }
        }
        
        //assigning the specified number to the same index of result array
        //as the specified number will be same 
        result[num]=arr[num];
        
        //printing the result array 
        System.out.println("New array after addition of array with a specific array element : ");
        for(int i=0;i<result.length;i++)
        {
            System.out.print(result[i]+" ");
        }    
   }
}
Output:

Enter the size of array: 10
Enter array elements: 10 200 30 400 50 600 70 800 90 1000
Array length is : 10
Enter index of the element to be added : 3
New array after addition of array with a specific array element : 
410 600 430 400 450 1000 470 1200 490 1400

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 Divide an Element to Every Other Elements of the Array

Java Program to Divide an Element to Every Other Elements of the Array

In the previous article, we have seen Java Program to Multiply an Element to Every Other Elements of the Array

In this article we are going to see how we can divide an element to every other elements of the array except itself by using Java Language.

Java Program to Divide an Element to Every 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

Let’s see different ways to divide an element to every other elements of the array except itself.

Method-1: Java Program to Divide an Element to Every Element of the Array By Static Initialization of Array Elements

Approach:

  • Declare and initialize an array.
  • Enter the index of array element to find that specific element.
  • This array element  will be divided with other array elements.
  • Iterate each element of the array and divide that specific array element with others elements except self.

Program:

public class Main
{

    public static void main(String[] args) 
    {
        //array initialized
        int arr[] = {10,20,30,40,50,60};
        // creating new array with size of actual array 
        int result[]= new int[arr.length];
        
        System.out.println("Array length is : "+arr.length);
        
        //declaring array index of the specified number 
        //which will be divided with other array elelments
        int num  = 2;
        
        //if the entered index(means specified number) exists in the array 
        //then only the specified array element can be divided with other array elements 
        if(num<arr.length)
        {
            //iterating the array
           for(int i=0;i<arr.length;i++)
           {
               // checking condition 
               // if array element is not the specified number 
               // then it will enter into the if block 
               // and the number will be divided with other elements except itself 
               if(arr[i]!=arr[num])
               {
                    // dividing the specified array element with other array elements
                    result[i] = arr[i]/arr[num];
               }
           }
        }
        
        //assigning the specified number to the same index of result array
        //as the specified number will be same 
        result[num]=arr[num];
        
        //printing the result array 
        System.out.println("New array after divide of array with a specific array element : ");
        for(int i=0;i<result.length;i++)
        {
            System.out.print(result[i]+" ");
        }    
   }
}
Output:
Array length is : 6
New array after divide of array with a specific array element : 
0 0 30 1 1 2

Method-2: Java Program to Divide an Element to Every Element of the Array By Dynamic Initialization of Array Elements

Approach:

  • Take the array size as user input.
  • Then take array elements as user input.
  • Enter the index of array element to find that specific element.
  • This array element  will be divided with other array elements.
  • Iterate each element of the array and divide that specific array element with others elements except self.

Program:

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];
        // creating new array with size of actual array 
        int result[]= new int[arr.length];
        
        // 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("Array length is : "+arr.length);
        
        //talking input of array index
        System.out.print("Enter index of the element to be divided : ");
        int num  = sc.nextInt();
        
        //if the entered index(means specified number) exists in the array 
        //then only the specified array element can be divided with other array elements 
        if(num<arr.length)
        {
            //iterating the array
           for(int i=0;i<arr.length;i++)
           {
               // checking condition 
               // if array element is not the specified number 
               // then it will enter into the if block 
               // and the number will be divided with other elements except itself
               if(arr[i]!=arr[num])
               {
                    // dividing the specified array element with other array elements
                    result[i] = arr[i]/arr[num];
               }
           }
        }
        
        //assigning the specified number to the same index of result array
        //as the specified number will be same 
        result[num]=arr[num];
        
        //printing the result array 
        System.out.println("New array after divide of array with a specific array element : ");
        for(int i=0;i<result.length;i++)
        {
            System.out.print(result[i]+" ");
        }    
   }
}
Output:

Enter the size of array: 5
Enter array elements: 10 20 30 40 50
Array length is : 5
Enter index of the element to be divided : 0
New array after divide of array with a specific array element : 
10 2 3 4 5

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 Print Common Elements in all Rows of a Matrix

Java Program to Print Common Elements in all Rows of a Matrix

In the previous article, we have seen Java Program to Check Diagonally Dominant Matrix

In this article we are going to see how we can write a program to find common element in all row of a given matrix.

Java Program to Print Common Elements in all Rows 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 common element in all row  of a given matrix.

Method-1: Java Program to Print Common Elements in all Rows of a Matrix By Static Initialization of Array Elements

Approach :

  • Declare and Initialize a matrix.
  • Define ele with elements as keys and their count as values.
  • Insert all elements of first row into ele with 1 as their values.
  • For remaining rows, check presence of each element in ele.
  • If element is present in ele and its count is equal to ‘x’, then increment its count by 1.
  • Print ele having common elements.

Program :

import java.util.*;
import java.util.Map.Entry;

public class Main 
{
   public static void main(String args[])
   {
      int mat[][] = { { 1, 2, 3 },{ 4, 3, 1 },{ 1, 0, 3 } }; 
      
        //Define ele with elements as keys and their count as values
        HashMap<Integer, Integer> ele = new HashMap<>();
        
        //Insert all elements of first row into ele with 1 as their values
        for (int y = 0; y < 3; y++)
            ele.put(mat[0][y], 1);
            
        //For remaining rows, check presence of each element in ele
        for (int x = 1; x < 3; x++) 
            for (int y = 0; y < 3 ; y++) 
                //If element is present in ele and it's count is equal to 'x',
                //then increment its count by 1
                if(ele.containsKey(mat[x][y]) && ele.get(mat[x][y]) == x)
                        ele.put(mat[x][y], x+1);
                        
        //Printing ele having common elements
        Set<Entry<Integer, Integer>> en = ele.entrySet();
        System.out.println("Common Elements In All Rows : ");
        for (Entry<Integer, Integer> e : en) 
            if (e.getValue() == 3) 
                System.out.print(e.getKey() + " ");
    } 
}
Output:

Common Elements In All Rows : 
1 3

Method-2: Java Program to Print Common Elements in all Rows of a Matrix By Dynamic Initialization of Array Elements

Approach:

  • Take user input of a matrix.
  • Define ele with elements as keys and their count as values.
  • Insert all elements of first row into ele with 1 as their values.
  • For remaining rows, check presence of each element in ele.
  • If element is present in ele and its count is equal to ‘x’, then increment its count by 1.
  • Print ele having common elements.

Program:

import java.util.*;
import java.util.Map.Entry;
public class Main 
{
   public static void main(String args[])
   {
       Scanner sc = new Scanner(System.in);
       
        // Initializing the 3X3 matrix i.e. 2D array
        int mat[][] = new int[3][3];
        int row, col ;
        
        // Taking matrix input
        System.out.println("\nEnter matrix elements");
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
                mat[row][col] = sc.nextInt();
                
        //Define ele with elements as keys and their count as values
        HashMap<Integer, Integer> ele = new HashMap<>();
        
        //Insert all elements of first row into ele with 1 as their values
        for (int y = 0; y < 3; y++)
            ele.put(mat[0][y], 1);
            
        //For remaining rows, check presence of each element in ele
        for (int x = 1; x < 3; x++) 
            for (int y = 0; y < 3 ; y++) 
                //If element is present in ele and it's count is equal to 'x',
                //then increment its count by 1
                if(ele.containsKey(mat[x][y]) && ele.get(mat[x][y]) == x)
                        ele.put(mat[x][y], x+1);
                        
        //Printing ele having common elements
        Set<Entry<Integer, Integer>> en = ele.entrySet();
        System.out.println("Common Elements In All Rows : ");
        for (Entry<Integer, Integer> e : en) 
            if (e.getValue() == 3) 
                System.out.print(e.getKey() + " ");
    } 
}

Output:

Enter matrix elements
Common Elements In All Rows : 
1 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.

Related Java Programs:

Java Program to Check Involutory Matrix

Java Program to Check Involutory Matrix

In the previous article, we have seen Java Program to Check Idempotent Matrix

In this article we are going to see  how we can write a program to check whether matrix is Involutory Matrix or not.

Java Program to Check Involutory 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.

Note: A matrix whose product of matrix is inverse  to itself is  to that matrix is called Involutory matrix .

Let’s see different ways to check whether matrix is Involutory matrix or not.

Method-1: Java Program to Check Involutory Matrix By Static Initialization of Array Elements

Approach:

  • Declare and initialize a matrix.
  • Calculate the product to itself .
  • Check the product of the matrix is inverse to the entered matrix or not .

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[][]={{1,0,0},{0,1,0},{0,0,1}};
        int res[][]=new int[3][3];;
        for (int i = 0; i < 3; i++) 
            { 
                for (int j = 0; j < 3; j++) 
                    { 
                        res[i][j] = 0; 
                        for (int k = 0; k < 3; k++) 
                            res[i][j] += mat[i][k] * mat[k][j]; 
                    } 
            } 
        for (int i = 0; i < 3; i++) 
        { 
            for (int j = 0; j < 3; j++)
            { 
                if (i == j && res[i][j] != 1) 
                    {
                        System.out.println("Not a Involutory Matrix"); 
                        System.exit(0);  
                    }
                if (i != j && res[i][j] != 0) 
                    {
                        System.out.println("Not a Involutory Matrix"); 
                        System.exit(0);  
                    }
            } 
        } 
        System.out.println("Involutory Matrix"); 
    } 
}
Output:

Involutory Matrix

Method-2: Java Program to Check Involutory Matrix By Dynamic Initialization of Array Elements

Approach:

  • Take user input of a matrix.
  • Calculate the product to itself .
  • Check the product of the matrix is inverse to the entered matrix or not .

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 ;
        // 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();
        int res[][]=new int[3][3];
        for (int i = 0; i < 3; i++) 
            { 
                for (int j = 0; j < 3; j++) 
                    { 
                        res[i][j] = 0; 
                        for (int k = 0; k < 3; k++) 
                            res[i][j] += mat[i][k] * mat[k][j]; 
                    } 
            } 
        for (int i = 0; i < 3; i++) 
        { 
            for (int j = 0; j < 3; j++)
            { 
                if (i == j && res[i][j] != 1) 
                    {
                        System.out.println("Not a Involutory Matrix"); 
                        System.exit(0);  
                    }
                if (i != j && res[i][j] != 0) 
                    {
                        System.out.println("Not a Involutory Matrix"); 
                        System.exit(0);  
                    }
            } 
        } 
        System.out.println("Involutory Matrix"); 
    } 
}
Output:

Enter matrix elements

1 0 0
0 1 0
0 0 1
Involutory Matrix

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

Related Java Programs:

Java Program to Find Maximum Product of Two Integers in an Array of Integers

Java Program to Find Maximum Product of Two Integers in an Array of Integers

In the previous article, we have seen Java Program to Check if a Sub Array is Formed by Consecutive Integers from a Given Array of Integers

In this article we are going to see how to Find Maximum Product of Two Integers in an Array of Integers.

Java Program to Find Maximum Product of Two 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 Maximum Product of Two Integers in an Array of Integers.

Method-1: Java Program to Find Maximum Product of Two Integers in an Array of Integers By Static Initialization of Array Elements

Approach:

  • Create two integer variable as max1 and max2 and assign value as -1.
  • Iterate the array.
  • If current value is more than max1, put current value in max1 and max1 value in max2.
  • Else if current value is more than max2, put current value in max2

Program:

public class Main
{
    public static void main(String[] args) 
    {
        int[] nums = { 3, 2, 7, -1, -4, 9, 5 };
        //calling the maxProduct() method
        maxProduct(nums);
    }

    //maxProduct() method to find maximum product of two array elements 
    public static void maxProduct(int[] nums) 
    {
        int max1 = -1;
        int max2 = -1;
        for (int i : nums) 
        {
            if (i > max1) 
            {
                max2 = max1;
                max1 = i;
            } 
            else if (i > max2) 
            {
                max2 = i;
            }
        }
        System.out.println("Maximum product is: " + max1 + " * " + max2 + " = " + max1 * max2);
    }
}

Output:

Maximum product is: 9 * 7 = 63

Method-2: Java Program to Find Maximum Product of Two Integers in an Array of Integers 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. Create two integer variable as max1 and max2 and assign value as -1.
  6. Iterate array.
  7. If current value is more than max1, put current value in max1 and max1 value in max2.
  8. Else if current value is more than max2, put current value in max2

Program:

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();
        }
        
        //calling maxProduct() method
        maxProduct(arr);
    }
    //maxProduct() method to find maximum product of two array elements 
    public static void maxProduct(int[] nums) 
    {
        int max1 = -1;
        int max2 = -1;
        for (int i : nums) 
        {
            if (i > max1) 
            {
                max2 = max1;
                max1 = i;
            } else if (i > max2) 
            {
                max2 = i;
            }
        }
        System.out.println("Maximum product is: " + max1 + " * " + max2 + " = " + max1 * max2);
    }
}

Output:

Enter the size of array: 9
Enter array elements: 1 2 3 4 5 6 7 8 9
Maximum product is: 9 * 8 = 72

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:

Java Program to Find Maximum Sum of Two Integers in an Array of Integers

Java Program to Find Maximum Sum of Two Integers in an Array of Integers

In the previous article, we have seen Java Program to Find Maximum Product of Two Integers in an Array of Integers

In this article we are going to see how to Find Maximum Sum of Two Integers in an Array of Integers.

Java Program to Find Maximum Sum of Two 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 Maximum Sum of Two Integers in an Array of Integers.

Method-1: Java Program to Find Maximum Sum of Two Integers in an Array of Integers By Static Initialization of Array Elements

Approach:

  • Create two integer variable as max1 and max2 and assign value as 0.
  • Iterate the array.
  • If current value is more than max1, put current value in max1 and max1 value in max2.
  • Else if current value is more than max2, put current value in max2
  • Then get the result by adding max1 and max2.

Program:

public class Main
{
    public static void main(String[] args) 
    {
        int[] nums = { 3, 2, 7, -1, -4, 9, 5 };
        //calling the maxSum() method
        maxSum(nums);
    }

    //maxSum() method to find maximum sum of two array elements 
    public static void maxSum(int[] nums) 
    {
        int max1 = 0;
        int max2 = 0;
        for (int i : nums) 
        {
            if (i > max1) 
            {
                max2 = max1;
                max1 = i;
            } 
            else if (i > max2) 
            {
                max2 = i;
            }
        }
        int res=max1+max2;
        System.out.println("Maximum Sum is: " + max1 + " + " + max2 + " = " + res);
    }
}
Output:

Maximum Sum is: 9 + 7 = 16

Method-2: Java Program to Find Maximum Sum of Two Integers in an Array of Integers 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. Create two integer variable as max1 and max2 and assign value as 0.
  6. Iterate array.
  7. If current value is more than max1, put current value in max1 and max1 value in max2.
  8. Else if current value is more than max2, put current value in max2.
  9. Then get the result by adding max1 and max2.

Program:

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();
        }
        
        //calling maxSum() method
        maxSum(arr);
    }
    //maxSum() method to find maximum sum of two array elements 
    public static void maxSum(int[] nums) 
    {
        int max1 = -1;
        int max2 = -1;
        for (int i : nums) 
        {
            if (i > max1) 
            {
                max2 = max1;
                max1 = i;
            } else if (i > max2) 
            {
                max2 = i;
            }
        }
        int res=max1+max2;
        System.out.println("Maximum sum is: " + max1 + " + " + max2 + " = " + res);
    }
}

Output:

Enter the size of array: 9
Enter array elements: 1 2 3 4 5 6 7 8 9
Maximum product is: 9 + 8 = 17

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: