Declare and Initialize Array in Java: Java is an incredibly powerful programming language where everything is an object – from classes and variables to arrays. Arrays offer a unique way of working with data that can be grouped together.
This post will cover initializing an array and the various ways to do so. You will see some code examples showcasing array initialization syntax using each approach. You will also learn about the warnings of array initialization using each method discussed.
Post On: | Declare and Initialize Array in Java |
Post Type: | Java Tutorials |
Published On: | www.softwaretestingo.com |
Applicable For: | Freshers & Experience |
Get Updates: | SoftwareTestingo Telegram Group |
What is a Java array?
Arrays can store multiple values of similar types in a single variable, which is helpful when storing a lot of data. Arrays are an often used object in Java and can accommodate many purposes, such as storing text strings, numbers, boolean values, etc.
The array object uses an index to keep track of each element inside it. The index of an element is determined by its position in the array, and arrays start counting indexes at zero. Therefore, each element’s location is one number higher than its index. So, in an array, the first element is located at index zero, the second at index one, and so on.
Great, now that we have reviewed the basics of arrays, let’s move on and learn how to create and Initialize an Array in Java.
Initialize Array in Java
Initializing an array in Java can be done in a few different ways, each with its benefits and drawbacks. In this section, we’ll show some code examples for each method and give some pointers on how to avoid common initialization mistakes.
Declaring a Java Array Variable
The syntax for declaring a Java array is very simple, as shown below. However, it’s important to remember that just because you’ve declared an array doesn’t mean it’s been initialized.
datatype[] arrayName;
There are three notable parts to the syntax mentioned above:
- Datatype: To declare an array, you will need to specify the datatype that the array will hold. Here are some of the acceptable data types like int, char, String, and Boolean.
- [] – It indicates that the variable will hold an array object.
- arrayName – It is simply the name of the array.
Declare and Initialize Array
You can use the declared array in your code by initializing it. This is where the fun starts. There are a few ways to initialize the array. The first way is using the new keyword. Let’s look at an example of declaring and initializing an array of primitive and object datatypes.
There is only a small syntax difference between the two data types. The object datatype’s keyword is written in full word format with a capital letter. Besides that, the syntax is almost identical to primitive datatype array initialization.
Here is the basic syntax for initializing an array:
dataType [] nameOfArray = new dataType [size]
Primitive Datatype Array
int[] nums = new int[5];
The code above declares a primitive array of five unspecified int values. The default value differs based on the data types used, but the array will have five default values of zero in this example.
Note: When creating an array with the new keyword, specify how many elements it will have to avoid getting an error.
Program: Initializing an array without assigning values:
package com.SoftwareTestingO.Array; public class DefaultInitilizeArray { public static void main(String[] args) { //Initializing array int[] array = new int[5]; //Printing the elements of array for (int i =0;i < 5;i++) { System.out.println(array[i]); } } }
Output:
0 0 0 0 0
Note: Here, we have only declared an array and not initialized it; that’s why the integer array has the default value of Zero.
Program: Initializing an array and assigning values
package com.softwaretestingo.array; public class InitilizeArrayEx { public static void main(String[] args) { int[] array = {11,12,13,14,15}; //Printing the elements of array for (int i =0;i < 5;i++) { System.out.println(array[i]); } } }
Output:
11 12 13 14 15
Note: The size is not specified when assigning values to an array during initialization.
Initialize Array After Declaration
You can declare an array without assigning values to it, and you can assign values to it later in your code. This is very useful when declaring an array before you have its values.
/* Declare */ int[] array; /* Initialize */ array = new int[5];
Note: When initializing an array after its declaration, the new keyword must be used, or it will result in unpredictable behavior and an error.
Program: Initializing an array after a declaration
package com.SoftwareTestingO.Array; public class DefaultInitilizeArray2 { public static void main(String[] args) { //Array Declaration int[] array; //Array Initialization array = new int[]{1,2,3,4,5}; //Printing the elements of array for (int i =0;i < 5;i++) { System.out.println(array[i]); } } }
Output:
1 2 3 4 5
Note: The new keyword must be used when assigning an array to a declared variable.
Object Datatype Array
Declaring and initializing an array of the object data types is similar to declaring and initializing an array of a primitive data type. The only difference is that the keywords for the object data type look different from those for a primitive data type. For example, we have a simple example of declaring and initializing an object datatype array below. In this case, the array would start with four default values of the String data types; each has the default null value.
String[] strArr = new String[4];
Multidimensional Array in Java
It is possible to create multidimensional arrays in Java. These are not multidimensional arrays but rather arrays containing other arrays (known as nested arrays). For example:
int[][] multiArray= new int[2][];
You can specify the size of one of the arrays within a multidimensional array by targeting it with an index, just like you would for a standard Java array. You must initialize the entire array structure before using it in your code.
multiArray[1] = new int[3];
Program: Create a multi-dimensional and print that array
package com.softwaretestingo.array; public class MultiDimensionalArrayEx { public static void main(String[] args) { // declaring and initializing 2D array int arr[][] = { {2,7,9},{3,6,1},{7,4,2} }; // printing 2D array for (int i=0; i< 3 ; i++) { for (int j=0; j < 3 ; j++) System.out.print(arr[i][j] + " "); System.out.println(); } } }
Output:
2 7 9 3 6 1 7 4 2
Initialize Java Array With Shorthand Syntax
Arrays can be declared and initialized in Java using a shorthand syntax, simplifying the process. This same syntax can also be used for multidimensional arrays. The code snippet below exemplifies this shorthand array declaration and initialization syntax.
int[] nums = {1,2,3};
If you want to create an array quickly and assign values simultaneously, shorthand syntax is the way to go! The curly braces wrapped around the numbers indicate that they should be added as array elements. So, for example, if your first array consists of three numbers – one, two, and three – they would be stored at indexes zero, one, and two, respectively.
When creating a multidimensional array, you don’t have to ensure that each inner array is the same size – a symmetric matrix. To initialize it, you’ll need to wrap your values in curly braces and then put those insides of another set of curly braces.
To get a better understanding of this syntax, let’s take a look at the code snippet below.
int[][] multiArray= ;
Passing Arrays to Methods
We can also pass arrays to methods, just like variables. For example, the program below passes the array to method sum in order to calculate the sum of all the values in the array.
Program: Write a program and pass an array to a method.
package com.softwaretestingo.array; public class PassingArrayAsMethodEx { public static void main(String[] args) { int arr[] = {3, 1, 2, 5, 4}; // passing array to method m1 sum(arr); } public static void sum(int[] arr) { // getting sum of array values int sum = 0; for (int i = 0; i < arr.length; i++) sum+=arr[i]; System.out.println("sum of array values : " + sum); } }
Output:
sum of array values : 15
Returning Arrays from Methods
As usual, a method can also return an array. For example, the below program returns an array from method1.
Program: Write a program that returns an array from a method
package com.SoftwareTestingO.Array; public class ReturnArray { public static void main(String[] args) { int arr[] = method1(); for (int i = 0; i < arr.length; i++) System.out.print(arr[i]+" "); } public static int[] method1() { // returning array return new int[]{1,2,3}; } }
Output:
1 2 3
Conclusion:
In this article, we discovered the different ways and methods you can follow to declare and initialize an array in Java. We’ve used curly braces {}, the new keyword, and for loops to initialize arrays in Java so that you have many options for different situations!
If you have implemented another process for Initialize Array, let us know in the comment section.