An array is a collection of similar types of data in a contiguous location in memory. After Declaring an array we create and assign it a value or variable. During the assignment variable of the array things, we have to remember and have to check the below condition.
1. Element Level Promotion
Element-level promotions are not applicable at the array level. Like a character can be promoted to integer but a character array type cannot be promoted to int type array.
Example:
Java
// Java Program for entry level promotion at array import java.io.*; class GFG { public static void main(String[] args) { int [] arr = { 1 , 2 , 3 }; char [] ch = { 'a' , 'b' , 'c' }; int [] b = arr; // valid assignment int [] c = ch; // invalid assignment } } |
2. For Object Type Array
In the case of object-type arrays, child-type array variables can be assigned to parent-type array variables. That means after creating a parent-type array object we can assign a child array in this parent array.
Example:
Java
// Assigning object type child // array to parent type array import java.io.*; class GFG { public static void main(String[] args) { String[] s = { "geeks" , "geeks" }; Object[] obj = s; System.out.println(obj[ 0 ]); } } |
geeks
When we assign one array to another array internally, the internal element or value won’t be copied, only the reference variable will be assigned hence sizes are not important but the type must be matched.
Example:
Java
import java.io.*; class GFG { public static void main(String[] args) { int arr[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 }; int b[] = { 100 , 200 , 300 }; arr = b; // valid b = arr; // valid } } |
3. Dimension Matching
When we assign one array to another array in java, the dimension must be matched which means if one array is in a single dimension then another array must be in a single dimension. Samely if one array is in two dimensions another array must be in two dimensions. So, when we perform array assignment size is not important but dimension and type must be matched.
Java
// Example code for dimension mismatched import java.io.*; class GFG { public static void main(String[] args) { int arr[][] = new int [ 3 ][]; // arr[0]=new int[4][5]//invalid dimension // mismatched // arr[0]=10;// invalid dimension mismatched arr[ 0 ] = new int [ 4 ]; // valid } } |