An array without any name is anonymous array in java. They are mainly created for one time use only.
Note: Anonymous arrays can be passed as an argument of a method.
Syntax: Anonymous Int Array
new int[] { 15, 25, 23, 45, 34};
Syntax: Anonymous Char Array
new char[] {'a', 'b', 'c', 'd');
Syntax: Anonymous String Array
new String[] {"Java", "JSP", "Servlet", "Spring"};
Syntax: Anonymous Multi-Dimensional Array
new String[][] { {"Java", "JSP", "Servlet", "Spring"}, {"MySQL", "Oracle"} };
Example 1
package com.w3schools; public class Test { public static void main(String args[]){ //Creating anonymous arrays System.out.println(new int[]{11, 22, 13, 14, 51}.length); System.out.println(new int[]{21, 64, 65}[2]); } } |
Output
5 65 |
Example 2
public class Main { static void total(int[] array) { int result = 0; for (int num : array) result = result + num; System.out.println("Total: " + result); } public static void main(String[] args) { total(new int[]{ 10, 5, 15 }); } } |
Output
Total: 30 |
Interview Questions on Arrays
- Can we change array size in java?
- What is an anonymous array in java?
- Difference between array and arraylist in java?
- What are jagged arrays in java?
- Can array size be negative in java?
- Java program to find duplicate elements in an array.
- Java program to find second largest element in an array of integers.
- Java program to check the equality of two arrays.
- Find all pairs of elements in an integer array whose sum is equal to a given number.
- Java program to find continuous sub array whose sum is equal to a given number
- Java program to find the intersection of two arrays
- Java program to separate zeros from non-zeros in an integer array
- Java program to find all the leaders in an integer array
- Java program to find a missing number in an integer array
- Java program to convert an array to ArrayList and an ArrayList to array
- Java program to count occurrences of each element in an array
- Java program to reverse an array without using an additional array
- Java program to remove duplicate elements from an array
- Java program to find union and intersection of multiple arrays
- Java program to find the most frequent element in an array