Literal is just unlikely any constant value that can be assigned to a variable.
Illustration:
int x = 10;
// Here 10 is a literal.
Now let us stick to the array literals that are just like primitive and string literals java also allows us to use array literals. Java defines special syntax that allows us to initialize array values literally in our programs.
Methods:
There are two different ways of creating array literals.
- Initialization of array elements at the time of creating array object.
- Using anonymous arrays
Method 1: Initialization of array elements at the time of creating array object. It is the most commonly used syntax and can only be used when declaring a variable of array type.
Syntax:
int[] factorsOf24 = { 1, 2, 3, 4, 6, 12, 24 };
Implementation:
The above statement creates an array of int data types containing 7 elements. Here, we:
- Created an array object without using new keyword.
- Didn’t specify the type of the array.
- Didn’t explicitly specify the length of the array object.
Example
Java
import java.io.*;
public class GFG {
public static void main(String[] args)
{
int [] factorsOf24 = { 1 , 2 , 3 , 4 , 6 , 12 , 24 };
for ( int i : factorsOf24)
System.out.print(i + " " );
}
}
|
Note: There is a flaw in this method as this array literal syntax works only when you assign the array object to a variable. If you need to do something with an array value such as pass it to a method but are going to use the array only once. In this case, we can avoid assigning it to a variable, but this syntax won’t allow us to do so.
Method 2: We have another syntax that allows us to use anonymous arrays. Anonymous arrays are arrays that are not assigned to any variables and hence, they don’t have names).
Syntax:
double volume = computeVolume(new int[] { 3, 4, 5 });
Implementation:
The above statement call a method computeVolume with an anonymous array. Here, we:
- Didn’t store the array in any variable.
- Used new keyword for creating an array object.
- Explicitly specified the type of array.
Example
Java
import java.io.*;
public class GFG {
public static double computeVolume( int [] dimensions)
{
int l = dimensions[ 0 ];
int b = dimensions[ 1 ];
int h = dimensions[ 2 ];
return (l * b * h);
}
public static void main(String[] args)
{
double volume
= computeVolume( new int [] { 3 , 4 , 5 });
System.out.print(volume);
}
}
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
14 Aug, 2021
Like Article
Save Article