- 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
- How to Create an Array in Java – Array Declaration Example
- What is an Array in Java?
- How to Declare and Initialize and Array in Java in a Single Statement
- How to Declare and Initialize an Array in Java in Separate Statements
- How to Declare an Array in Java with Default Values
- Multi-Dimensional Arrays in Java
- 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:
How to Create an Array in Java – Array Declaration Example
Shittu Olumide
Creating and manipulating arrays is an essential skill for any Java programmer. Arrays provide a way to store and organize multiple values of the same type, making it easier to work with large sets of data.
In this article, we will provide a step-by-step guide on how to create an array in Java, including how to initialize or create an array. We will also cover some advanced topics such as multi-dimensional arrays, array copying, and array sorting.
Whether you're new to Java programming or an experienced developer looking to refresh your skills, this article will provide you with the knowledge you need to become proficient in working with Java arrays.
What is an Array in Java?
In Java, an array is a data structure that can store a fixed-size sequence of elements of the same data type. An array is an object in Java, which means it can be assigned to a variable, passed as a parameter to a method, and returned as a value from a method.
Arrays in Java are zero-indexed, which means that the first element in an array has an index of 0, the second element has an index of 1, and so on. The length of an array is fixed when it is created and cannot be changed later.
Java arrays can store elements of any data type, including primitive types such as int, double, and boolean, as well as object types such as String and Integer. Arrays can also be multi-dimensional, meaning that they can have multiple rows and columns.
Arrays in Java are commonly used to store collections of data, such as a list of numbers, a set of strings, or a series of objects. By using arrays, we can access and manipulate collections of data more efficiently than using individual variables.
There are several ways to create an array in Java. In this section, we will cover some of the most common approaches to array declaration and initialization in Java.
How to Declare and Initialize and Array in Java in a Single Statement
Array declaration and initialization in a single statement is a concise and convenient way to create an array in Java. This approach allows you to declare and initialize an array using a single line of code.
To create an array in a single statement, you first declare the type of the array, followed by the name of the array, and then the values of the array enclosed in curly braces, separated by commas.
In this example, we declare an array of integers named numbers and initialize it with the values 1, 2, 3, 4, and 5. The type of the array is int[] , indicating that it is an array of integers.
You can also create an array of a different data type, such as a string array. Here's an example:
In this example, we declare an array of strings named names and initialize it with the values "John", "Mary", "David", and "Sarah".
When using this approach, you don't need to specify the size of the array explicitly, as it is inferred.
How to Declare and Initialize an Array in Java in Separate Statements
Array declaration and initialization in separate statements is another way to create an array in Java. This approach involves declaring an array variable and then initializing it with values in a separate statement.
To create an array using this approach, you first declare the array variable using the syntax datatype[] arrayName , where datatype is the type of data the array will hold, and arrayName is the name of the array.
In this example, we declare an array of integers named numbers , but we haven't initialized it with any values yet.
To initialize the array with values, we use the new keyword followed by the type of data the array will hold, enclosed in square brackets, and the number of elements the array will contain. Here's an example:
In this example, we initialize the numbers array with the values 1, 2, 3, 4, and 5. Note that we use the syntax to specify the values of the array.
You can also initialize the array with values in separate statements, like this:
String[] names; names = new String[];
In this example, we declare a string array named names and initialize it with the values "John", "Mary", "David", and "Sarah" in a separate statement.
Using this approach, you can also initialize the array with default values by omitting the values in the initialization statement. For example:
boolean[] flags = new boolean[5];
In this example, we declare a boolean array named flags and initialize it with 5 elements. Since we haven't specified any values, each element is initialized with the default value of false .
How to Declare an Array in Java with Default Values
Array declaration with default values is a way to create an array in Java and initialize it with default values of the specified data type. This approach is useful when you need to create an array with a fixed size, but you don't have specific values to initialize it with.
To create an array with default values, you first declare the array variable using the syntax datatype[] arrayName = new datatype[length] , where datatype is the type of data the array will hold, arrayName is the name of the array, and length is the number of elements the array will contain. Here's an example:
In this example, we declare an array of integers named numbers with a length of 5. Since we haven't specified any values, each element in the array is initialized with the default value of 0.
You can also create an array of a different data type and initialize it with default values. For example:
boolean[] flags = new boolean[3];
In this example, we declare an array of booleans named flags with a length of 3. Since we haven't specified any values, each element in the array is initialized with the default value of false .
When using this approach, it's important to note that the default values of an array depend on its data type. For example, the default value of an integer is 0, while the default value of a boolean is false . If the array holds objects, the default value is null .
Array declaration with default values is useful when you need to create an array with a fixed size, but you don't yet have specific values to initialize it with. You can later assign values to the elements of the array using indexing.
Multi-Dimensional Arrays in Java
A multi-dimensional array is an array that contains other arrays. In Java, you can create multi-dimensional arrays with two or more dimensions. A two-dimensional array is an array of arrays, while a three-dimensional array is an array of arrays of arrays, and so on.
To create a two-dimensional array in Java, you first declare the array variable using the syntax datatype[][] arrayName , where datatype is the type of data the array will hold, and arrayName is the name of the array. Here's an example:
In this example, we declare a two-dimensional array of integers named matrix , but we haven't initialized it with any values yet.
To initialize the array with values, we use the new keyword followed by the type of data the array will hold, enclosed in square brackets, and the number of rows and columns the array will contain. Here's an example:
In this example, we initialize the matrix array with 3 rows and 4 columns. Note that we use the syntax new datatype[rows][columns] to specify the dimensions of the array.
Here's another example of declaring a two-dimensional array of integers:
You can also create a multi-dimensional array with default values by omitting the values in the initialization statement. For example:
boolean[][] flags = new boolean[2][3];
In this example, we declare a two-dimensional array of booleans named flags with 2 rows and 3 columns. Since we haven't specified any values, each element in the array is initialized with the default value of false .
Multi-dimensional arrays are useful when you need to store data in a table or grid-like structure, such as a chess board or a spreadsheet.
Conclusion
Creating arrays is a fundamental skill in Java programming. In this article, we covered four different approaches to array declaration and initialization in Java, including single-statement declaration and initialization, separate declaration and initialization, default values, and multi-dimensional arrays.
Understanding these different techniques will help you write more effective Java code and work more effectively with Java arrays.
Let's connect on Twitter and on LinkedIn. You can also subscribe to my YouTube channel.