What is an anonymous array and explain with an example in Java?


An array is a data structure/container/objectthat stores a fixed-size sequential collection of elements of the same type. The size/length of the array is determined at the time of creation.

The position of the elements in the array is called as index or subscript. The first element of the array is stored at the index 0 and, the second element is at the index 1 and so on.

Each element in an array is accessed using an expression which contains the name of the array followed by the index of the required element in square brackets.

For example, if an array of 6 elements is created with name myArray, you can access the element of the array at index 3 as −

System.out.println(myArray[3]);
//25

Creating an array in Java

In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as −

int myArray[] = new int[7];
myArray[0] = 1254;
myArray[1] = 1458;
myArray[2] = 5687;
myArray[3] = 1457;
myArray[4] = 4554;
myArray[5] = 5445;
myArray[6] = 7524;

Or, you can directly assign values with in flower braces separating them with commas (,) as −

int myArray = {1254, 1458, 5687, 1457, 4554, 5445, 7524};

Anonymous arrays

In addition to the above specified ways you can create an array without specifying any name such arrays are known as anonymous arrays. Since it doesn’t have name to refer you can use it only once in your program. Generally, anonymous arrays are passed as arguments to methods.

You can create an anonymous array by initializing it at the time of creation.

new int[] { 1254, 5452, 5743, 9984}; //int array

new String[] {"Java", "JavaFX", "Hadoop"}; //String array

Example

In the following Java program the arrayToUpperCase() method accepts an array of Strings, converts each String to upper case and prints the results.

To this method we are passing an anonymous array of Strngs as a parameter.

public class AnonymousArray {
   public static void arrayToUpperCase(String [] array) {
      for(int i=0; i< array.length; i++) {
         char[] ch = array[i].toCharArray();
         for(int j=0; j<ch.length; j++){
            ch[j] = Character.toUpperCase(ch[j]);
         }
         System.out.println(new String(ch));
      }
   }
   public static void main(String args[]) {
      arrayToUpperCase(new String[] {"Krishna", "Vishnu", "Dhana", "Rupa", "Raja", "Kavya"});
   }
}

Output

KRISHNA
VISHNU
DHANA
RUPA
RAJA
KAVYA

Updated on: 02-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements