VOOZH about

URL: https://www.geeksforgeeks.org/java/interesting-facts-array-assignment-java/

⇱ Interesting facts about Array assignment in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Interesting facts about Array assignment in Java

Last Updated : 6 Jan, 2019
Prerequisite : Arrays in Java While working with arrays we have to do 3 tasks namely declaration, creation, initialization or Assignment. Declaration of array :
int[] arr;
Creation of array :
// Here we create an array of size 3
int[] arr = new int[3];
Initialization of array :
arr[0] = 1;
arr[1] = 2;
arr[3] = 3;

int intArray[]; // declaring array
intArray = new int[20]; // allocating memory to array
Some important facts while assigning elements to the array:
  1. For primitive data types : In case of primitive type arrays, as array elements we can provide any type which can be implicitly promoted to the declared type array. Apart from that, if we are trying to use any other data-types then we will get compile-time error saying possible loss of precision. Output:
    108
    
    Output:
    possible loss of precision.
    
    Output:
    error: incompatible types: possible lossy conversion from long to char
    error: incompatible types: possible lossy conversion from double to char
    
  2. Object type Arrays : If we are creating object type arrays then the elements of that arrays can be either declared type objects or it can be child class object. Output:
    10
    20.5
    
    Output:
    Compile-time error(incompatible types)
    
    Output:
    error: incompatible types: char cannot be converted to Number
    error: incompatible types: String cannot be converted to Number
    
  3. Interface type array : For interface type array, we can assign elements as its implementation class objects.
Output:
Compile-time error(Incompatible types)
Explanation: In the above program, we are giving elements of String class that's cause compile time error. Because we know that String does not implements Runnable interface. Reference : https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
Comment