- Arrays in Java
- Creating, initializing, and accessing an Array
- One-Dimensional Arrays:
- Instantiating an Array in Java
- Array Literal
- Accessing Java Array Elements using for Loop
- Java Array Declaration – How to Initialize an Array in Java with Example Code
- What is an array?
- How to Declare and Intialize an Array in Java
- How to initialize an array with the new keyword
- 2. How to initialize an array in one line
- How to Loop Through an Array in Java
- How to loop through an array with the for loop
- How to loop through an array with the enhanced for loop
- Conclusion
Arrays in Java
Array in java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays.
- In Java, all arrays are dynamically allocated. (discussed below)
- Arrays are stored in contiguous memory [consecutive memory locations].
- Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++, where we find length using sizeof.
- A Java array variable can also be declared like other variables with [] after the data type.
- The variables in the array are ordered, and each has an index beginning with 0.
- Java array can also be used as a static field, a local variable, or a method parameter.
- The size of an array must be specified by int or short value and not long.
- The direct superclass of an array type is Object.
- Every array type implements the interfaces Cloneable and java.io.Serializable.
- This storage of arrays helps us randomly access the elements of an array [Support Random Access].
- The size of the array cannot be altered(once initialized). However, an array reference can be made to point to another array.
An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class depending on the definition of the array. In the case of primitive data types, the actual values are stored in contiguous memory locations. In the case of class objects, the actual objects are stored in a heap segment.
Creating, initializing, and accessing an Array
One-Dimensional Arrays:
The general form of a one-dimensional array declaration is
type var-name[]; OR type[] var-name;
An array declaration has two components: the type and the name. type declares the element type of the array. The element type determines the data type of each element that comprises the array. Like an array of integers, we can also create an array of other primitive data types like char, float, double, etc., or user-defined data types (objects of a class). Thus, the element type for the array determines what type of data the array will hold.
// both are valid declarations int intArray[]; or int[] intArray; byte byteArray[]; short shortsArray[]; boolean booleanArray[]; long longArray[]; float floatArray[]; double doubleArray[]; char charArray[]; // an array of references to objects of // the class MyClass (a class created by // user) MyClass myClassArray[]; Object[] ao, // array of Object Collection[] ca; // array of Collection // of unknown type
Although the first declaration establishes that int Array is an array variable, no actual array exists. It merely tells the compiler that this variable (int Array) will hold an array of the integer type. To link int Array with an actual, physical array of integers, you must allocate one using new and assign it to int Array.
Instantiating an Array in Java
When an array is declared, only a reference of an array is created. To create or give memory to the array, you create an array like this: The general form of new as it applies to one-dimensional arrays appears as follows:
Here, type specifies the type of data being allocated, size determines the number of elements in the array, and var-name is the name of the array variable that is linked to the array. To use new to allocate an array, you must specify the type and number of elements to allocate.
int intArray[]; //declaring array intArray = new int[20]; // allocating memory to array
int[] intArray = new int[20]; // combining both statements in one
Note:
The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types). Do refer to default array values in Java.
Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.
Array Literal
In a situation where the size of the array and variables of the array are already known, array literals can be used.
int[] intArray = new int[]< 1,2,3,4,5,6,7,8,9,10 >; // Declaring array literal
- The length of this array determines the length of the created array.
- There is no need to write the new int[] part in the latest versions of Java.
Accessing Java Array Elements using for Loop
Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of array can be accessed using Java for Loop.
// accessing the elements of the specified array for (int i = 0; i < arr.length; i++) System.out.println("Element at index " + i + " : "+ arr[i]);
Implementation:
Java Array Declaration – How to Initialize an Array in Java with Example Code
Kolade Chris
Arrays are an important part of the fundamental data structures in Java. And they are incredibly useful in solving a lot of programming problems.
What is an array?
By definition, an array is a collection of data of the same type.
An array is usually declared so you can have multiple values in the same memory – unlike variables where you can only have one value in the memory.
So, arrays let you create one variable that holds different values together, instead of declaring a variable for each value.
The position of a particular data point in the array is called its index, while the data itself is called an element.
In this tutorial, I will show you how to declare an array, initialize it, and loop through it with the for loop and enhanced for loop. Then you can start using it in your Java projects.
I will be using the intelliJIDEA IDE to write the code. You can use it if you want, or you can also use any IDE of your choice.
How to Declare and Intialize an Array in Java
There are two ways you can declare and initialize an array in Java. The first is with the new keyword, where you have to initialize the values one by one. The second is by putting the values in curly braces.
How to initialize an array with the new keyword
You can declare the array with the syntax below:
dataType : the type of data you want to put in the array. This could be a string, integer, double, and so on.
[ ] : signifies that the variable to declare will contain an array of values
nameOfArrary : The array identifier.
With the above information, you have only declared the array – you still need to initialize it.
The basic syntax for initializing an array in this way looks like this:
dataType [] nameOfArray = new dataType [size]
The size is usually expressed with a numberic value. It signifies how many values you want to hold in the array. Its value is immutable, meaning you won’t be able to put more than the number specified as the size in the array.
You can now go ahead and put values in the array like this:
package com.kolade; import java.util.Arrays; public class Main < public static void main(String[] args) < // write your code here String [] names = new String[3]; names[0] = "Quincy"; names[1] = "Abbey"; names[2] = "Kolade"; >>
In the code snippet above, I initialized an array of strings called names (the identifier). The size is 3, so it can only hold three values.
There are 3 indexes in total:
- The value, Quincy is at index 0
- The value Abbey is at index 1
- The value Kolade is at index 2
Don’t be confused by the numbers 0, 1, 2. Arrays are zero-indexed, so counting starts from 0, not 1.
In the array above, if you add extra data – for example, names[3] = “Chris” – you would get an error because you have specified that the array should only contain 3 values. If you want to add more values, you have to increase the size of the array.
To print the array to the console, you can use the inbuilt toString() method:
System.out.println(Arrays.toString(names));
2. How to initialize an array in one line
You can initialize an array in one line with the basic syntax below:
With this method, you don’t need to specify the size of the array, so you can put any number of values you want in it.
Check out the example in the code snippet below:
package com.kolade; import java.util.Arrays; public class Main < public static void main(String[] args) < // write your code here String [] namesTwo = ; > >
Printing the array to the console shows the values like this:
How to Loop Through an Array in Java
You can loop through an array in Java with the for loop and enhanced for loop. With the for loop, you have access to the index of the individual values, but with the enhanced for loop, you don’t.
How to loop through an array with the for loop
In Java, you can use the for loop with the basic syntax below:
You can then loop through the namesTwo array like this:
package com.kolade; import java.util.Arrays; public class Main < public static void main(String[] args) < // write your code here String [] namesTwo = ; for (int i = 0; i < namesTwo.length; i++) < System.out.println("Element at index " + i + " : " + namesTwo[i]); >> >
How to loop through an array with the enhanced for loop
The enhanced for loop is a cleaner version of the for loop. The downside is that with it, you don’t have access to the index of the individual values in the array.
The basic syntax of the enhanced for loop looks like this:
for (dataType variable : nameOfArray) < // Code to execute >
package com.kolade; import java.util.Arrays; public class Main < public static void main(String[] args) < // write your code here String [] namesTwo = ; for (String names : namesTwo) < System.out.println(names); >> >
Conclusion
In this tutorial, you learned how to declare and initialize an array in two different ways – with the new keyword and using curly braces.
You also learned how to loop through arrays with the for loop and enhanced for loop, so you don’t just initialize an array and do nothing with it.
Thank you for reading, and keep coding.