Interesting facts about Array assignment in Java


There are many facts with respect to array assignment, and we will discuss a few of them with working examples here −

  • While creating array object type, the element that would be present inside the array can be declared as type objects or as child class’s object.

Example

 Live Demo

public class Demo{
   public static void main(String[] args){
      Number[] my_val = new Number[3];
      my_val[0] = new Integer(91);
      my_val[1] = new Double(65.963);
      my_val[2] = new Double(45.7965);
      System.out.println(my_val[0]);
      System.out.println(my_val[1]);
      System.out.println(my_val[2]);
   }
}

Output

91
65.963
45.7965

A class named ‘Demo’ contains the main function wherein a new Number instance is defined and elements are added to it. These elements are displayed on the console one by one.

  • While working with primitive types in arrays, the array elements can belong to any type which would later be implicitly incremented to the type of the array that was declared. Using different data types results in compile time error −

Example

 Live Demo

public class Demo{
   public static void main(String[] args){
      int[] my_arr = new int[4];
      my_arr[0] = 65;
      my_arr[1] = 'S';
      byte my_byte = 11;
      my_arr[2] = my_byte;
      my_arr[3] = 34;
      System.out.println("The array contains :");
      System.out.println(my_arr[0] + my_arr[1] + my_arr[2] + my_arr[3]);
   }
}

Output

The array contains :
193

A class named ‘Demo’ contains the main function wherein a new array instance is defined and elements are added to it. These are different type of elements, int, double, byte and so on. These elements are concatenated and displayed on the console, wherein they are converted to a single type.

Updated on: 04-Jul-2020

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements