Java Program to Synchronize an ArrayList

Java Program to Synchronize an ArrayList

In this article, we will learn how to synchronize an ArrayList in Java.

Java Program to Synchronize an ArrayList

We know, ArrayList is non-synchronized which means accessing an ArrayList instance from multiple threads is not safe.

There are two ways to synchronize explicitly:

Method-1: Java Program to Synchronize an ArrayList By Using Collections.synchronizedList() Method

Approach:

  • Create a String List say syncAl and add elements into it.
  • Create a synchronized block with unsynchronized list as parameter
  • Within the block create Iterator class to iterate over the syncAl
  • Display the synchronized arraylist.

Program:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Collections;

public class Main 
{

   public static void main(String args[])
   {

       // String ArrayList 
       List<String> syncAl = Collections.synchronizedList(new ArrayList<String>());

       //Adding elements to synchronized ArrayList
       syncAl.add("One");
       syncAl.add("Two");
       syncAl.add("Three");
     

      // System.out.println("Traversing unsynchronized ArrayList:" + syncAl);

       System.out.println("Traversing synchronized ArrayList:");

       // Synchronized block is required here
       synchronized(syncAl) {
       Iterator<String> iterator = syncAl.iterator(); 
       while (iterator.hasNext())
          System.out.println(iterator.next());
       }
   }
}
Output:

Traversing synchronized ArrayList:
One
Two
Three

Method-2: Java Program to Synchronize an ArrayList By Using Thread-Safe Variant of ArrayList: CopyOnWriteArrayList

This is a thread-safe variant of ArrayList. It is found in java.util.concurrent  package. It is a data structure created to be used in a concurrent environment.

Approach:

  • Create a CopyOnWriteArrayList class say syncAl and add elements into it.
  • Use Iterator class to iterate over the syncAl
  • Display the synchronized arraylist.

Program:

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.Iterator;

public class Main 
{
 public static void main(String args[])
 {
    // String CopyOnWriteArrayList
    CopyOnWriteArrayList<String> syncAl = new CopyOnWriteArrayList<String>();

    //Adding elements to synchronized ArrayList
    syncAl.add("One");
    syncAl.add("Two");
    syncAl.add("Three");

    System.out.println("Displaying synchronized ArrayList Elements:");

    //Here Synchronized block is not required in this method
    Iterator<String> iterator = syncAl.iterator(); 
    while (iterator.hasNext())
       System.out.println(iterator.next());
  }
}
Displaying synchronized ArrayList Elements:
One
Two
Three

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

Java Program to Remove Specified Element From ArrayList

In this article, we will learn how to remove a specified element from an ArrayList in Java.

Java Program to Remove Specified Element From ArrayList

This can be done by using a simple built-in method remove(Object obj) of the ArrayList class.

Syntax:

public boolean remove(Object obj)

Parameters

  1. Particular element to be removed

Let’s see the program to understand it more clearly.

Method: Java Program to Remove Specified Element From ArrayList By Using remove() Method

Approach:

  1. Create an ArrayList say al and add elements into it using add() method.
  2. Use the remove(Object obj) method defined above for different test cases (element in the list) as given in the below code.
  3. Display the updated ArrayList

Note:

  1. If the specified element which needs to be removed from ArrayList is not present then the method will return false.
  2. When there are duplicate elements, then first occurrence of specified element is removed from the ArrayList.

Program:

import java.util.ArrayList;
public class Main 
{
   public static void main(String args[]) 
   {

       //String ArrayList
       ArrayList<String> al = new ArrayList<String>();
       //Adding elements
       al.add("P");
       al.add("Q");
       al.add("R");
       al.add("X");
       al.add("S");
       al.add("T");

       // Displaying before removing element
       System.out.println("ArrayList before removal :");
       for(String ele: al)
       {
            System.out.println(ele);
       }
       
       //Removing P (Index - 0)
       al.remove("P");

       //Removing X (Index - 3) from the remaining list
       al.remove("X");

        // Displaying Remaining elements of ArrayList
         System.out.println("ArrayList After removal:");
       for(String ele: al)
       {
             System.out.println(ele);
       }
    }
}
Output:

ArrayList before removal :
P
Q
R
X
S
T
ArrayList After removal:
Q
R
S
T

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

Java Program to Find Area of a Circumscribed Circle of a Square

Java Program to Find Area of a Circumscribed Circle of a Square

In the previous article, we have seen Java Program to Check if a Given Circle Lies Completely Inside the Ring Formed by Two Concentric Circle

In this article we will discuss about how to Find Area of a Circumscribed Circle of a Square using Java programming language.

Java Program to Find Area of a Circumscribed Circle of a Square

Before jumping into the program directly, let’s first know how we can Find Area of a Circumscribed Circle of a Square.

Explanation:

Formula to Find Area of a Circumscribed Circle of a Square: (pi*side*side)/2

Example:

When side=2

Area = (pi*side*side)/2

= (3.14*2*2)/2

= 6.28

Let’s see different ways to Find Area of a Circumscribed Circle of a Square.

Method-1: Java Program to Find Area of a Circumscribed Circle of a Square By Using Static Value

Approach:

  • Declare the value for side of the square.
  • Use the formula (pi*side*side)/2 to calculate the area.
  • Then print the result.

Program:

import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
        // Static initialization of side of the square
        double pi = 3.14;
        double side = 60;
        // Prints result of the square
        System.out.println("Area of the square "+(pi*side*side/2));
    }
}
Output:

Area of the square 5652.0

Method-2: Java Program to Find Area of a Circumscribed Circle of a Square By User Input Value

Approach:

  • Take user input the value side of the square.
  • Use the formula (pi*side*side)/2 to calculate the area.
  • Then print the result.

Program:

import java.awt.Point; 
import java.util.Scanner;
import static java.lang.Math.*;

public class Main
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        // Asking the user to input the side of the square
        System.out.println("Enter the side of the square");
        double pi = 3.14;
        double side = scan.nextInt();
        // Prints result of the square
        System.out.println("Area of the square "+(pi*side*side/2));
    }
}
Output:

Enter the side of the square
6
Area of the square 56.519999999999996

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

Related Java Articles:

Java Program to Check if a Given Circle Lies Completely Inside the Ring Formed by Two Concentric Circle

Java Program to Check if a Given Circle Lies Completely Inside the Ring Formed by Two Concentric Circle

In the previous article, we have seen Java Program to Check if a Line Touches or Intersects a Circle

In this article we will discuss about how to check if a given circle lies completely inside the ring formed by two concentric circle using Java programming language.

Java Program to Check if a Given Circle Lies Completely Inside the Ring Formed by Two Concentric Circle

Before jumping into the program directly, let’s first know how can we Check if a Given Circle Lies Completely Inside the Ring Formed by Two Concentric Circle

Explanation:

r = radius of smaller concentric circle

R = radius of Bigger concentric circle

r1 = radius of the circle to be checked

dist = distance between the origin and center of the circle

Note: The concentric circles are at coordinate(0,0).

If (dist+r1 = R) and (dist-r1 = r) then the circle lies inside the ring.

Example:

When r=4, R=8 and r1=2, Center(6,0)

Distance = sqrt(x*x+y*y)

= sqrt(36+0)

=6

6-2 = 4(r) and 6+2 = 8(R)

Hence it lies inside the ring.

Let’s see different ways to check if a given circle lies completely inside the ring.

Method-1: Java Program to Check if a Given Circle Lies Completely Inside the Ring Formed by Two Concentric Circle By Using Static Value

Approach:

  • Declare the value for all three radiuses and the coordinate of the center.
  • Then call the checkCircle() user defined method by passing all the values as parameter.
  • In this method the it checks if the distance of the center from the origin and compares it with the radius of the concentric circles.
  • Then print the result.

Program:

import java.util.Scanner;
import java.awt.Point;
import static java.lang.Math.*;

public class Main
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        //Static initialization
        int r = 4, R = 8, r1 = 2;
        Point circle = new Point(6,0);
        // Prints the result
        if(circleCheck(r,R,r1,circle))
            System.out.println("The circle is inside the ring");
        else
            System.out.println("The circle is outside the ring");
    }

    //circleCheck() method
    public static boolean circleCheck(int r, int R, int r1, Point circle)
    {
        // Uses pythagoras theorem to calculate the distance of the circle from origin
        int distance = (int)Math.sqrt(circle.x*circle.x + circle.y*circle.y); 
        // Checks the condition and returns true or false
        return (distance - r1 >= r && distance + r1 <= R);
    }
}
Output:

The circle is inside the ring

Method-2: Java Program to Check if a Given Circle Lies Completely Inside the Ring Formed by Two Concentric Circle By User Input Value

Approach:

  1. Take user input for all three radiuses and the coordinate of the center.
  2. Then call the checkCircle() user defined method by passing all the values as parameter.
  3. In this method the it checks if the distance of the center from the origin and compares it with the radius of the concentric circles.
  4. Then print the result.

Program:

import java.awt.Point; 
import java.util.Scanner;
import static java.lang.Math.*;

public class Main
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        //Asking the user for input
        System.out.println("Enter the radiuses of the small, big and the circle to be checked");
        int r = scan.nextInt(), R = scan.nextInt(), r1 = scan.nextInt();
        System.out.println("Enter the coordinates of the center of the circle to be checked");
        Point circle = new Point(scan.nextInt(),scan.nextInt());
        // Prints the result
        if(circleCheck(r,R,r1,circle))
            System.out.println("The circle is inside the ring");
        else
            System.out.println("The circle is outside the ring");
    }
    
    //circleCheck() method
    public static boolean circleCheck(int r, int R, int r1, Point circle)
    {
        // Uses pythagoras theorem to calculate the distance of the circle from origin
        int distance = (int)Math.sqrt(circle.x*circle.x + circle.y*circle.y); 
        // Checks the condition and returns true or false
        return (distance - r1 >= r && distance + r1 <= R); 
    }
}
Output:

Case-1
Enter the radiuses of the small, big and the circle to be checked
4 8 2
Enter the coordinates of the center of the circle to be checked
5 0
The circle is outside the ring

Case-2
Enter the radiuses of the small, big and the circle to be checked
4 8 2
Enter the coordinates of the center of the circle to be checked
6 0
The circle is inside the ring

Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Related Java Articles:

Java Program to Remove Element at Particular Index of ArrayList

Java Program to Remove Element at Particular Index of ArrayList

In this article, we will learn how to remove an element of an ArrayList from a specified Index by using Java programming language.

Java Program to Remove Element at Particular Index of ArrayList

This can be done by using a simple built-in method remove().

Syntax:

public Object remove(int index)

Parameters:

  1. Particular Index from which element to be removed.

Let’s see the program to remove element at particular index of ArrayList.

Method-1: Java Program to Remove Element at Particular Index of ArrayList By Using remove() Method

Approach:

  1. Create an ArrayList say al and add elements into it using add() method.
  2. Use the remove(int index) method defined above for different test cases (indexes) as given in the below code.
  3. Display the updated ArrayList.

Program:

import java.util.ArrayList;
public class Main 
{
   public static void main(String args[]) 
   {

       //String ArrayList
       ArrayList<String> al = new ArrayList<String>();
       al.add("P");
       al.add("Q");
       al.add("R");
       al.add("X");
       al.add("S");
       al.add("T");

       // Displaying before removing element
       System.out.println("ArrayList before removal :");

       for(String ele: al)
       {
            System.out.println(ele);
       }
       //Removing P (Index - 0)
       al.remove(0);
       //Removing X (Index - 2) from the remaining list
       al.remove(2);

        // Displaying Remaining elements of ArrayList
       System.out.println("ArrayList After remove:");
       for(String ele: al)
       {
             System.out.println(ele);
       }
    }
}

Output:

ArrayList before removal :
P
Q
R
X
S
T
ArrayList After remove:
Q
R
S
T

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.

Java Program to Add Element at Particular Index of ArrayList

In this article, we will learn how to add an element to a particular Index of ArrayList in Java programming language.

Java Program to Add Element at Particular Index of ArrayList

This can be done by using a simple built-in method add().

It can be used in two variants

  1. When we have to simply add an element at the end of ArrayList.
  2. When we have to add an element at the specified index.

Syntax:

public void add(int index,Object element)

Parameters:

  1. Particular Index at which element to be added.
  2. The element that should be added.

Let’s see the program to understand it clearly.

Method: Java Program to Add Element at Particular Index of ArrayList By Using add() Method

Approach –

  1. Create an ArrayList say al and add elements into it using add() method.
  2. Use the add() method for both the variants as given below.
  3. Display the updated ArrayList.

Program:

import java.util.ArrayList;
public class Main 
{
   public static void main(String[] args) 
   {

       // ArrayList of String type
       ArrayList<String> al = new ArrayList<String>();

       // simply add() methods that adds elements at the end
       al.add("This");
       al.add("is");
       al.add("a");
       al.add("Sentence");
        
        //printing arraylist before adding any new element at any index
       System.out.println("Elements before adding at Particular Index:"+ al);
       //Now, add an element to any position say 1 (position not Index)
       //So, 1st position = 0 index as indexing starts from 0
       al.add(0,"Hello");

       System.out.println("Elements after adding at Particular Index:"+ al);
       
       //again add an element to any position say 6 = 5th Index
       al.add(5, "Okay");

       //Print
       System.out.println("Elements after adding Program string :"+ al);
   }
}
Output:

Elements before adding at Particular Index:[This, is, a, Sentence]
Elements after adding at Particular Index:[Hello, This, is, a, Sentence]
Elements after adding Program string :[Hello, This, is, a, Sentence, Okay]

Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Java Program to Add All Elements of List to ArrayList

Java Program to Add All Elements of List to ArrayList

In this article, we will learn how to add all the elements of List to ArrayList.

Java Program to Add All Elements of List to ArrayList

This can be done using an addAll() built-in method of the ArrayList class.

Syntax:

public boolean addAll(Collection c)

Parameter – ArrayList in which elements to be added

Let’s see the program to add all elements of list to ArrayList

Method: Java Program to Add All Elements of List to ArrayList By Using addAll() Method

Approach –

  1. Create a String ArrayList say basketArraylist and add elements into it using add() method.
  2. Create a String List say basketList and add elements into it.
  3. Then add all elements of the list to ArrayList using the addAll()
  4. Display the updated ArrayList.

 Program:

import java.util.ArrayList;
import java.util.List;

public class Main 
{

   public static void main(String a[])
   {

      // Declared Arraylist of String
      ArrayList<String> basketArraylist = new ArrayList<String>();

      //Adding elements to the ArrayList
      basketArraylist.add("Apple");
      basketArraylist.add("Mango");
      basketArraylist.add("Orange");

      System.out.println("ArrayList Elements are: "+ basketArraylist);

      //Adding elements to a List
      List<String> basketList = new ArrayList<String>();
      basketList.add("Tomato");
      basketList.add("Onion");
      basketList.add("Potato");

      //Adding all elements of list to ArrayList using addAll
      basketArraylist.addAll(basketList);

      // Updated ArrayList
      System.out.println("Updated ArrayList Elements are: "+ basketArraylist);
   }
}
Output:

ArrayList Elements are: [Apple, Mango, Orange]
Updated ArrayList Elements are: [Apple, Mango, Orange, Tomato, Onion, Potato]

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

Java Program to Iterate an ArrayList

Java Program to Iterate an ArrayList

In this article, we will see how to iterate an ArrayList in Java programming language.

Java Program to Iterate an ArrayList

We can iterate an ArrayList by different ways. Let’s see one by one.

Method-1: Java Program to Iterate an ArrayList By Using ForEach Loop

Approach:

  1. Create a String ArrayList say  list and add elements into it.
  2. Traverse the list using ForEach Loop and print the elements one by one.

Program:

import java.util.*;  
  public class Main 
  {  
   public static void main(String args[])
   {  

   // Creating String ArrayList 
  ArrayList<String> list=new ArrayList<String>(); 

  // Adding elements into the list
  list.add("Queen");   
  list.add("King");    
  list.add("Ace");    
  list.add("Joker");  
  
  //Traversing list through for-each loop  
    System.out.println("Cards in the list are :");   
  for(String cards:list)  
  {  
    System.out.println(cards);
  }
  
 }  
} 
  
Output:

Cards in the list are :
Queen
King
Ace
Joker

Method-2: Java Program to Iterate an ArrayList By Using For Loop

Approach:

  1. Create a String ArrayList say  list and add elements into it.
  2. Traverse the list using For Loop and print the elements one by one.

Program:

import java.util.*;  
  public class Main 
  {  
    public static void main(String args[])
    {  

    // Creating String ArrayList 
    ArrayList<String> list=new ArrayList<String>(); 

      // Adding elements into the list
      list.add("Queen");   
      list.add("King");    
      list.add("Ace");    
      list.add("Joker");  
      
      //Traversing list through for loop  
      System.out.println("Cards in the list are :");   
      for (int i = 0; i< list.size();i++)
      {  
        System.out.println(list.get(i));
      }
    }  
} 
  
Output:

Cards in the list are :
Queen
King
Ace
Joker

Method-3: Java Program to Iterate an ArrayList By Using While Loop

Approach:

  1. Create a String ArrayList say  list and add elements into it.
  2. Traverse the list using While Loop and print the elements one by one.

Program:

import java.util.*;  
  public class Main 
  {  
    public static void main(String args[])
    {  

      // Creating String ArrayList 
      ArrayList<String> list=new ArrayList<String>(); 

      // Adding elements into the list
      list.add("Queen");   
      list.add("King");    
      list.add("Ace");    
      list.add("Joker");  
      
      //Traversing list through while loop  
      System.out.println("Cards in the list are :");   
      int items = 0;
      while (items < list.size()) 
        {
        System.out.println(list.get(items));
        items++;
        }

    }  
} 
  
Output:

Cards in the list are :
Queen
King
Ace
Joker

Method-4: Java Program to Iterate an ArrayList By Using Iterator Loop

Approach:

  1. Create a String ArrayList say  list and add elements into it.
  2. Traverse the list using iterator  and print the elements one by one.

Program:

import java.util.*;  
  public class Main 
  {  
    public static void main(String args[])
    {  

      // Creating String ArrayList 
      ArrayList<String> list=new ArrayList<String>(); 

      // Adding elements into the list
      list.add("Queen");   
      list.add("King");    
      list.add("Ace");    
      list.add("Joker");  
      
      //Traversing list through iterator loop  
      System.out.println("Cards in the list are :");   
      Iterator iterator = list.iterator();
      while (iterator.hasNext()) 
      {
         System.out.println(iterator.next());
      }
    }  
} 
  
Output:

Cards in the list are :
Queen
King
Ace
Joker

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

Java Program to Form Two Numbers (of 2 digits) with Maximum Sum Using Array Elements

Java Program to Form Two Numbers (2 digit) with Maximum Sum Using Array Elements

In the previous article, we have seen Java Program to Find All the Elements in an Array that are Greater than All Elements to Their Right

In this article, we will see how to form two numbers of 2 digits with maximum sum using array elements in Java programming language.

Java Program to Form Two Numbers (of 2 digits) with Maximum Sum Using Array Elements

Prerequisite: 

See below articles to know more about Array in Java, array declaration, array instantiation and array initialization.

Base Condition:

  1. The number is a 2 digited number (Ex-54, 89, 71 etc.)
  2. We have to form 2 numbers using array elements.
  3. All the array elements need to be single digited only.

Let’s see different ways to form two numbers of 2 digits with maximum sum.

Method-1: Java Program to Form Two Numbers (of 2 digits) with Maximum Sum Using Array Elements By Using Sorting

Approach:

  • Declare an array and with single digit numbers as array elements.
  • Call the user defined method findMaximum().
  • Inside method, sort the array in descending order.
  • So first element of array is biggest element in array and elements are ordered in decreasing order.
  • So combine index-0 and index-1 element which is the 1st biggest number that can be formed using array elements.
  • Next combine index-0 and index-2 element which is the 2nd biggest number that can be formed using array elements.
  • As we have two largest numbers so sum will be maximum.
  • So, return those two numbers.

Program:

import java.util.Arrays;
import java.util.Comparator;
 
class Main
{
    // Find two numbers with a maximum sum formed by digits of an array
    public static void findMaximum(Integer[] input)
    {
 
        // sort the array in descending order
        Arrays.sort(input, Comparator.reverseOrder());
 
        //find first number 
        int x = 0;
        x = x * 10 + input[0];
        x = x * 10 + input[1];
        
 
        //find second number
        int y=0;
        y = y * 10 + input[0];
        y = y * 10 + input[2];
       
        // print `x` and `y`
        System.out.println("The two numbers formed by using array elements with maximum sum are " + x + " and " + y);
        int sum=x+y;
        System.out.println("And the maximum sum is "+sum);        
    }
 
    public static void main(String[] args)
    {
        Integer[] input = { 1,5,3,4,5 };
 
        findMaximum(input);
    }
}
Output:

The two numbers formed by using array elements with maximum sum are 55 and 54
And the maximum sum is 109

Method-2: Java Program to Form Two Numbers (of 2 digits) with Maximum Sum Using Array Elements By Finding 1st, 2nd and 3rd Big Element from Array

Approach:

  • Take user input of length of array.
  • Take input of array elements (only single digits)
  • Call the user defined method findBiggest() to find 3 big elements in the array say firstNumber, secondNumber and thirdNumber.
  • After getting 3 big elements in the array, inside that findBiggest() method, call findMaxNumber() method.
  • Inside findMaxNumber() method combine firstNumber and secondNumber element which is the 1st biggest number that can be formed using array elements.
  • Next combine firstNumber and thirdNumber element which is the 2nd biggest number that can be formed using array elements.
  • As we have two largest numbers so sum will be maximum.
  • So, return those two numbers.

Program:

import java.util.Scanner;

public class Main 
{
     public static void main(String args[]) 
    {
        int length = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of elements in array: ");
        //array length taken as input
        length = sc.nextInt();
        //array declared
        int[] arr = new int[length];
        
        //take input of single digited number as array element
        System.out.println("Enter elements into array: ");
        //taking input of array elements
        for (int i = 0; i < length; i++) 
        {
            arr[i] = sc.nextInt();
        }

        System.out.println("First 3 biggest numbers in array : ");
        //calling findBiggest() method
        findBiggest(arr);
    }
    
    //user defined method to find first 3 biggest element
    private static void findBiggest(int[] arr) 
    {
        int firstNumber = 0;
        int secondNumber = 0;
        int thirdNumber = 0;

        for (int i = 0; i < arr.length; i++) 
        { 
            if (arr[i] > firstNumber) 
            {
                thirdNumber = secondNumber;
                secondNumber = firstNumber;
                firstNumber = arr[i];
            } 
            else if (arr[i] > secondNumber) 
            {
                thirdNumber = secondNumber;
                secondNumber = arr[i];
            }
            else if (arr[i] > thirdNumber) 
            {
                thirdNumber = arr[i];
            }
        }

        System.out.println("First biggest number : " + firstNumber);
        System.out.println("Second biggest number : " + secondNumber);
        System.out.println("Third biggest number : " + thirdNumber);
        
        //calling findMaxNumber() method
        findMaxNumber(firstNumber,secondNumber,thirdNumber);
    }
    
    //findMaxNumber() user defined method to form two numbers whose sumis maximum
    public static void findMaxNumber(int firstNumber,int secondNumber,int thirdNumber)
    {
        //find first number 
        int x = 0; 
        x = x * 10 + firstNumber; 
        x = x * 10 + secondNumber;
        
        //find second number 
        int y = 0; 
        y = y * 10 + firstNumber; 
        y = y * 10 + thirdNumber;
        
        // print `x` and `y` 
        System.out.println("The two numbers formed by using array elements with maximum sum are " + x + " and " + y); 
        int sum=x+y; 
        System.out.println("And the maximum sum is "+sum);
    }
}
Output:

Enter number of elements in array: 
6
Enter elements into array: 
5 1 6 4 2 3 
First 3 biggest numbers in array : 
First biggest number : 6
Second biggest number : 5
Third biggest number : 4
The two numbers formed by using array elements with maximum sum are 65 and 64
And the maximum sum is 129

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 Articles:

Java Program to Insert an Element in an Unsorted Array

Java Program to Insert an Element in an Unsorted Array

In the previous article, we have seen Java Program to Insert an Element in a Sorted Array

In this article, we will learn how to enter an element at a specified position in an unsorted array by using Java Programming language.

Java Program to Insert an Element in an Unsorted Array

Prerequisite: 

See below articles to know more about Array, array declaration, array instantiation and array initialization.

In an unsorted array Initially, we have to search for the specified position then we can directly insert the element into that position. Here we need not check any condition before inserting.

Let’s see the program to understand it more clearly.

Method: Java Program to Insert an Element in an Unsorted Array By Manually Right Shifting

Approach:

  1. In the user defined insert() method, traverse the array starting from the end to the specified position.
  2. Shift the current element one position ahead or to the right then when we reached the position insert the key to the specified position.
  3. After insertion, return the updated size of the array.
  4. In the main() method, call insert() method to get an updated array as output.

Program:

public class Main 
{
    //main() method
    public static void main(String[] args)
    {
        //array declared with array size as 20
        int arr[] = new int[20];
        arr[0] = 7;
        arr[1] = 2;
        arr[2] = 9;
        arr[3] = 23;
        arr[4] = 6;
       
        int size = 5;
        int key = 42;
 
        System.out.print("Before Insertion: ");
        for (int i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
            
        //System.out.println(size);
 
        // Inserting key (method call)
        size = insert(arr, key);
        
       // System.out.println(size);
 
        System.out.print("\nAfter Insertion: ");
        for (int i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
    }
    // This function returns size+1 if insertion
    // is successful, else size (size of a given array).
    public static int insert(int arr[], int key)
    {
        int size = 5;
        // position  = index + 1
        int position = 2;
        int i;
        
       //Start traversing the array from end using for loop
       for(i=size-1; i >= position; i--)
       {
            // shift elements to the right 
            arr[i + 1] = arr[i];
        }

       // At last insert the key to its position
        arr[position] = key;
         
        // return updated size of array
        return (size + 1);
    }
}
Output:

Before Insertion: 7 2 9 23 6 
After Insertion: 7 2 42 9 23 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 Articles: