Array Concept in Java, Array in Java, What is Array? Jagged Array, Multidimensional array in java?

What is an Array:-

It is a collection of elements of similar data type, array store element using proper sequence, base index of the array will be started from 0 to size-1.
The array is also called the primary data structure of Java, Array is used to provide data arrangement using the linear data structure.
Syntax of Array:-
Datatype arrayname[] = new Datatype[size]
Datatype [] arrayname = new Datatype[size]
Datatype arrayname[] = {value1,value2,value,....}
int arr[] = new int[5];
int [] arr = new int[5];
Array basic program to fixed elements size?
1)  Integer Type Array:-
class ArrExample
{
   public static void main(String args[])
   {
       int [] arr = {12,23,34,11,67};
       for(int i=0;i<arr.length;i++)
       {
           System.out.println(arr[i]);
       }  
       }
}
2)  Char Type Array:-
class ArrExample
{
   public static void main(String args[])
   {
       char [] arr = {'1','A','@','$','_'};
       for(int i=0;i<arr.length;i++)
       {
           System.out.println(arr[i]);
       }  
       }
}
User Input 
import java.util.Scanner;
class DynamicArray
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter size of array");
        int num;
        num = sc.nextInt();
        char arr[] = new char[num];
        for(int i=0;i<num;i++)
        {
            System.out.println("Enter element for "+i+ " index");
            arr[i]=sc.next().charAt(0); 
        }
        System.out.println("Array elements are");
        for(int i=0;i<num;i++)
        {
            System.out.println(arr[i]);
              }
            }
}
3) String type Array
class ArrExample
{
   public static void main(String args[])
   {
       String [] arr = {"C","Java","PHP","iOS","Android"};
       for(int i=0;i<arr.length;i++)
       {
           System.out.println(arr[i]);
       }      
   }
}
With User Input
import java.util.Scanner;
class DynamicArray
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter size of array");
        int num;
        num = sc.nextInt();
        String arr[] = new String[num];
        for(int i=0;i<num;i++)
        {
            System.out.println("Enter element for "+i+ " index");
            arr[i]=sc.next(); 
        }
        System.out.println("Array elements are");
        for(int i=0;i<num;i++)
        {
            System.out.println(arr[i]);
            }        
    }
}
4)  Object type Array Example in Java:-
class ArrExample
{
   public static void main(String args[])
   {
        Object [] arr = {"C",1,true,12.0,1.2F};
       for(int i=0;i<arr.length;i++)
       {
           System.out.println(arr[i]);
       }  
       }
}
Advantage of the array:-
1) We can easily search and sort the elements of the array because the array stores data using the proper sequence.
2)  Array provides contiguous memory allocation hence we can reduce the extra memory gap.
3)  We can store multiple elements using a single array variable which reduces the extra business code of an application.

The disadvantage of the array:-
1)  Array size is fixed
2)  we can not add, and destroy array elements dynamically.
these limitation has been solved by the Collection Framework.
Type of array:-
1 Single Dimension:-    
We can store elements using rows, the base index of the array element will be started from 0 to size-1.
Datatype arrayname[] = new Datatype[];
Datatype [] arrayname = new Datatype[];
Program of Array:-;
Question WAP to store and display elements into the array?
Answer:-
import java.util.Scanner;
class ArrDemo
{
   public static void main(String args[])
   {
        Scanner sc = new Scanner(System.in);
        int size;
        System.out.println("Enter size of array");
        size=sc.nextInt();
        int arr[] = new int[size];
        for(int i=0;i<size;i++)
        {
          System.out.println("enter element for "+i+" index");
          arr[i]=sc.nextInt();
        }
        for(int i=0;i<size;i++)
        {
          System.out.println(arr[i]);
                 }
   }
WAP to calculate the sum of array elements?
import java.util.Scanner;
class ArrExample
{
    public static void main(String args[])
    {
          int size;
          int sum=0;
          System.out.println("Enter size");
          Scanner sc = new Scanner(System.in);
          size=sc.nextInt();
          int arr[] = new int[size];
          for(int i=0;i<size;i++)
          {
               System.out.println("Enter element for "+i+" index");
               arr[i]=sc.nextInt();
          }
          
          for(int i=0;i<size;i++)
          {
               sum=sum+arr[i];
               System.out.println(arr[i]);
          } 
          System.out.println(sum);
     }
}
ASSIGNMENT:-

1) WAP to sort the elements of the array in ascending order?

class SortArr
{

    public static void main(String args[])
    {
        int [] arr = {12,23,45,10,11,89,21};
        int num;
        for(int i=0;i<arr.length;i++)
        {
            for(int j=i+1;j<arr.length;j++)
            {
                    if(arr[i]>arr[j])
                    {
                       num = arr[i];
                       arr[i]=arr[j];
                       arr[j] = num;
                        
                    }
            }
            System.out.println(arr[i]);   
        } 
    }
}
2)  WAP to find the max and second max element in an array?
3)  WAP to merge two arrays in one array?
4)  WAP to display duplicate elements in an array?
1,1,2,3,4,5,2,7,11
class UniqueArr
{
public static void main(String args[])
{
int arr[] = {1, 2, 1, 2,1, 3, 4, 5, 2, 5, 2};

for(int i=0;i<arr.length-1;i++)
{
   int c=0;
   for(int k=0;k<i;k++)
   {
       if(arr[i]==arr[k])
       {
        c++;
        break;
       } 
   }
   if(c==0)
   {
   for(int j=i+1;j<arr.length;j++)
   {
      if(arr[i]==arr[j] )
      {
          
           System.out.println(arr[i]);
           break;
                  
      } 
    }
   }
   }
}
}
1 2
5) WAP to display unique elements in an array?
2 3 4 5 7 11 11 2 5    o/p   3 4 7
6) WAP to display prime elements in the array?
The solution to this program:-
import java.util.Scanner;
class ArrDemo
{
   public static void main(String args[])
   {
       int size;
       Scanner sc = new Scanner(System.in);
       System.out.println("Enter size");
       size=sc.nextInt();
       int arr[] = new int[size];
       for(int i=0;i<size;i++)
       {
            System.out.println("Enter elements ");
            arr[i]=sc.nextInt();
       }
               for(int i=0;i<size;i++)
       {
            int c=0;
           for(int j=1;j<=arr[i];j++)
           {
                if(arr[i]%j==0)
                  c++;
           } 
          if(c==2)
          System.out.println(arr[i]);
              }
  }
}
Optimize program of Prime Number?
import java.util.Scanner;
class ArrDemo
{
   public static void main(String args[])
   {
       int size,i,j;
       Scanner sc = new Scanner(System.in);
       System.out.println("Enter size");
       size=sc.nextInt();
       int arr[] = new int[size];
       for(i=0;i<size;i++)
       {
            System.out.println("Enter elements ");
           arr[i]=sc.nextInt();
       }       
        for(i=0;i<size;i++)
       {
          for(j=2;j<arr[i]/2;j++)
           {
                if(arr[i]%j==0)
                  break;
           } 
          if(j==(int)(arr[i]/2))
          System.out.println(arr[i]);
            }
  }
}
2)Multi-Dimension:-  
using this array we can store elements using rows and columns, it provides a matrix pattern to display elements.
It will be used to arrange data based on rows and columns, for example, if we have 3 different sections and we want to evaluate the marks of students for each section then we prefer a multidimensional array.
Syntax of MultiDimension Array;-
Datatype arrayname[][] = new Datatype[row][col];
int arr[][] = new int[3][2];
Program Explanation of multidimensional array;-

With user input:-
import java.util.Scanner;
class ArrDemo
{
   public static void main(String args[])
   {
        Scanner sc = new Scanner(System.in);
        int r,c;
        System.out.println("Enter size of row");
        r=sc.nextInt();
        System.out.println("Enter size of column");
        c=sc.nextInt();
        int arr[][] = new int[r][c];
        for(int i=0;i<r;i++)
        {
            for(int j=0;j<c;j++)
            {
             System.out.println("enter element for "+i+j+" index");
             arr[i][j]=sc.nextInt();
            }
        }
        for(int i=0;i<r;i++)
        {
            for(int j=0;j<c;j++)
            {
             System.out.print(arr[i][j]+" ");
              }
           System.out.println();
        }
   }
}
Without user input:-
class Matrix
{
    public static void main(String args[])
    {
           int arr[][] = {{1,2},{3,5}};
           for(int i=0;i<2;i++)
           {
               for(int j=0;j<2;j++)
               {
                  System.out.print(arr[i][j]);
               }
               System.out.println();
          }
   }
}
Program of MultiDimenion Array;-
1)  WAP to perform multiplication of the matrix?
2)  WAP to count the total prime element in the matrix?
3)  WAP to find the max element of each row of the matrix?
The solution of max element for each row in the matrix:-
package oops;
import java.util.Scanner;
public class ArrayExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r,c;
System.out.println("Enter rows");
r = sc.nextInt();
System.out.println("Enter column");
c=sc.nextInt();
int arr[][] = new int[r][c];
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.println("Enter element for "+i+j+ "index");
arr[i][j] = sc.nextInt();
}
}
System.out.println("Matrix elements is");
for(int i=0;i<r;i++)
{
int max=0;
for(int j=0;j<c;j++)
{
if(max<arr[i][j])
{
max=arr[i][j];
}
System.out.print(arr[i][j]);
}
System.out.println("maximum elements is "+max);
System.out.println();
}
}
}
Limitation of Multi dimension array:-
The number of row elements and column elements will be equal to the matrix. if we want to store a dissimilar number of elements for each row then a multi-dimension array will be failed the problem will solve by a Jagged Array.
3  Jagged Array:-
Jagged is the collection of heterogeneous rows, we can provide a different number of column elements in the jagged row.
Java provides a Jagged array Structure similar to a multidimensional array but Jagged array contains a different number of column elements for each row but multi-dimension array contains the same number of column elements for each row.
Example  of a jagged array
1
2 3 4
2 3
5 6 7 8
in this example, a Jagged array contains four rows and for the first row one element, the second row three elements, the third row only two elements, and the fourth row contain four elements.
Syntax of Jagged Array:-
Datatype arrayname[][] = new Datatype[row][];
int arr[][] = new int[4][];
arr[0] = new int[1];
arr[1] = new int[3];
arr[2]= new int[2];
arr[3]= new int[4];
Normal Jagged Array Example:-
Example of Jagged Array:-
import java.util.Scanner;
class JaggedArr
{
   public static void main(String args[])
   {
        int r,c;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of rows");
        r=sc.nextInt();
        int arr[][] = new int[r][];
        for(int i=0;i<r;i++)
        { 
            System.out.println("enter number of column elements for row "+i);
            c=sc.nextInt();
            arr[i]=new int[c];
            for(int j=0;j<c;j++)
            {
                System.out.println("enter element for "+i+j+" index");
                arr[i][j]=sc.nextInt();
            }
        }

        for(int i=0;i<r;i++)
        {         
            for(int j=0;j<arr[i].length;j++)
            {
                System.out.print(arr[i][j]+" ");
               
            }
            System.out.println();
        }
   }
}
4 Object Array:-
The object is the superclass in java hence it can contain all data type elements using proper sequence.
It is the collection of heterogeneous elements using this array we can store dissimilar types of elements 
Object arrayname [] = {value1,value2,value3,....}
Object arr[] = {12,"hello",12.34,true};
class ObjectArr
{
   public static void main(String args[])
   {
     Object arr[] = {1001,"manish","CS",45000};
     for(int i=0;i<arr.length;i++)
     {
        System.out.println(arr[i]);
     }
     for(Object o:arr)
     {
          System.out.println(o);
     }
   }
}
Multidimensional Array:-
class ObjectArr
{
   public static void  main(String args[])
   {
         Object arr[][] = {{true,12,12.34},{12.34F,"Abc",'a'}};
         for(int i=0;i<2;i++)
         {
              for(int j=0;j<3;j++)
              {
                 System.out.print(arr[i][j] + " ");
              }
              System.out.println();
         }  
   }
}
Foreach Loop in Java:-
Note:-  for each is used to display the elements of array and collection only .it is the modified form of for loop.
for(normalvar : arrayvariable)
{
   System.out.println(normalvar);
}
array value will be copied to a variable.
for each loop aways will be used to display the element of array and collection. it is also called modified for a loop.
Example of Foreach Loop:-
class ObjectArr
{
   public static void  main(String args[])
   {
       int arr[] = {1,34,45,56,67,89,11};
       for(int k:arr)
       {
            System.out.println(k);
       } 
         Object arr1[][] = {{true,12,12.34},{12.34F,"Abc",'a'}};
         for(Object k[]:arr1)
         {
              for(Object l:k)
              {
                 System.out.print(l + " ");
              }
              System.out.println();
         } 
   }
}
Array Practice Program?
Q1)  WAP to find max and second max char in String?
     String s = "hello";   output o is the max char and l is the second max
Q2)  WAP to find second max prime elements in the jagged array?
Q3)   WAP to sort only odd elements in an array?
      12 21 34 56 67 89 3 88 7
  o/p    12 3  34 56 7  21 67 88
MOST Important Array Interview Questions for Interview?
Check if a key is present in every segment of size k in an array
Find the minimum and maximum element in an array
Write a program to reverse the array
Write a program to sort the given array
Find the Kth largest and Kth smallest number in an array
Find the occurrence of an integer in the array
Sort the array of 0s, 1s, and 2s
Range and Coefficient of array
Move all the negative elements to one side of the array
Find the Union and Intersection of the two sorted arrays
Level 2
Write a program to cyclically rotate an array by one
Find the missing integer
Count Pairs with given sum
Find duplicates in an array
Sort an Array using the Quicksort algorithm
Find common elements in three sorted arrays
Find the first repeating element in an array of integers
Find the first non-repeating element in a given array of integers
Find the largest three elements in an array Time
Rearrange the array in alternating positive and negative items
Find if there is any subarray with sum equal to zero
Find Largest sum contiguous Subarray
Find the factorial of a large number
Find Maximum Product Subarray
Find longest consecutive subsequence
Find the minimum element in a rotated and sorted array
Find all elements that appear more than N/K times
GCD of given index ranges in an array
Minimize the maximum difference between the heights
Minimum number of jumps to reach the end
Find the two repetitive elements in a given array
Find a triplet that sums to a given value
Construct a N*M matrix from the user input
Find the row with the maximum number of 1’s
Print the matrix in a Spiral manner
Find whether an array is a subset of another array
Implement two Stacks in an array
Majority Element
Wave Array
Trapping Rainwater
Level 3
Maximum Index
Max sum path in two arrays
Find Missing And Repeating
Stock buy and sell Problem
Pair with given sum in a sorted array
Chocolate Distribution Problem
Longest Consecutive Subsequence
Print all possible combinations of r elements in a given array