Java is a general-purpose, mid-level, backend programming language with which you can build websites, web applications, Android applications for mobile and tablet, and other different kinds of software. Arrays are one of the most frequently used data structures in Java, therefore it’s crucial to understand how they work. Java arrays are, in fact, variables that allow you to store more than one values of the same data type and call any of them whenever you need.CHARACTERISTICS OF A JAVA ARRAY
Java arrays are case-sensitive and zero-based (the first index is not 1 but 0). Besides, Java arrays can only contain elements of the same data type. For instance, you can have an integer array or a string array but not a mixed one that contains both strings and integers. As Java is a compiled language (as opposed to interpreted languages), you also need to define the size of the array before passing it to the compiler.
If the Java compiler doesn’t know in advance how many elements your array will have it won’t be able to assign the necessary memory to the array and won’t be able to compile your code. This also means that you can’t change the size of an array at runtime (you can’t add new elements to the array & can’t remove superfluous ones). Therefore, Java arrays require a little more planning than arrays of an interpreted language such as JavaScript where you can freely add or remove elements on the go.
1. DECLARE A NEW JAVA ARRAY
As Java arrays can only contain elements of the same type, you need to define which data type it will use when you declare a new array. You can use either primitive data types such as integers, floats, or booleans or objects such as strings and dates. As the Array object is also one of Java’s built-in objects, you can also store arrays within an array. This kind of arrays are called multi-dimensional arrays.
When you declare an array, you specify the data type and the name of the array. At this point, the array won’t contain any elements yet. An array declaration, in fact, is a blueprint of which you will create an instance during the next step (called instantiation). For instance, this is how the declaration of a string array called myArray looks like:
/* Array declaration */
public class MyClass {
public static void main(String[] args) {
String[] myArray;
}
}
I placed the array into the main() method so that the Java compiler will evaluate it right away. However, you can place array declarations to other places in your Java code as well. Don’t forget the square brackets after the name of the data type (String[] in the example), as that is how the compiler knows that the new variable will be an array.
Note that as myArray hasn’t yet been instantiated, the compiler can’t yet evaluate its value, either.
2. CREATE A NEW ARRAY INSTANCE
After you declared the new array, you need to create a new instance of your array declaration, or with other words, you need to instantiate the array. For the instantiation, you need to use the new keyword that creates a new array instance in the memory. You also need to specify the number of elements your Java array will hold.
Following our example, this is how you can instantiate the myArray variable we declared in the previous step:
/* Array instantiation */
import java.util.Arrays;
public class MyClass {
public static void main(String[] args) {
String[] myArray = new String[6];
System.out.println(Arrays.toString(myArray));
}
}
As you can see in the code snippet above, myArray will contain 6 elements and each will be a string. I have also added the System.out.println() method that outputs the result of the compilation in the console. And, to make that method work, I have imported the Arrays classin the first line of the code (this way, all of its built-in methods are available to the MyClassclass).
This is the first spot when the Java compiler is able to make sense of the new array. However, it just returns 6 null elements, as we haven’t yet initialized values for any of the elements:
/* Console output */
[null, null, null, null, null, null]
3. INITIALIZE THE ARRAY
When you initialize an array, you define a value for each of its elements. You can initialize a value for every element separately by using the simple assignment operator (equals sign). In the example, I assigned the name of a famous writer to each item:
/* Array initialization */
import java.util.Arrays;
public class MyClass {
public static void main(String[] args) {
String[] myArray = new String[6];
myArray[0] = "Mark Twain";
myArray[1] = "Virginia Woolf";
myArray[2] = "William Shakespeare";
myArray[3] = "Maya Angelou";
myArray[4] = "Charles Dickens";
myArray[5] = "Agatha Christie";
System.out.println(Arrays.toString(myArray));
}
}
As Java arrays are zero-based, an array with six elements will have indices from 0 to 5. If you run the program you can check out in the console that after the initialization, each element has a value, indeed:
/* Console output */
[Mark Twain, Virginia Woolf, William Shakespeare, Maya Angelou,
Charles Dickens, Agatha Christie]
4. USE THE INITIALIZATION SHORTHAND
If you don’t want to type that much you can also perform the three aforementioned steps (declaration, instantiation, initialization) in one step using the following shorthand syntax:
/* Initialization shorthand */
import java.util.Arrays;
public class MyClass {
public static void main(String[] args) {
String[] myArray = {"Mark Twain", "Virginia Woolf",
"William Shakespeare", "Maya Angelou",
"Charles Dickens", "Agatha Christie"};
System.out.println(Arrays.toString(myArray));
}
}
Notice that when you use the shorthand syntax to initialize your Java array, you don’t need to specify the number of elements. That’s because the compiler can simply count the number of items you assigned to the array in order to know the size of memory it needs to allocate to the new array. However, you still need to use the brackets [] after the String class type.
In the console, you can test that the shorthand returns the same values as the longer syntax:
/* Console output */
[Mark Twain, Virginia Woolf, William Shakespeare, Maya Angelou,
Charles Dickens, Agatha Christie]
5. INITIALIZE AN ARRAY WITH THE FOR LOOP
If your array stores elements of a numeric data type (integers, floats, etc.) you can also use a for loop to initialize the array:
/* Initialization with for loop */
import java.util.Arrays;
public class MyClass {
public static void main(String[] args) {
int[] myArray = new int[15];
for (int i = 0; i < 15; i++) {
myArray[i] = i + 1;
}
System.out.println(Arrays.toString(myArray));
}
}
Here, myArray is an integer array and the for loop generates integer numbers from 1 to 15. During the instantiation, you need to define the number of items the for loop will return (int[15] in the example).
In the console, you can see that the array has been initialized with integers from 1 to 15:
/* Console output */
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
NEXT STEPS
To properly initialize Java arrays, you need to pay attention to a couple of things such as using the same data type, specifying the number of elements, and using the right syntax. However, arrays are just a small part of the Java language. If you want to know more about Java development take a look at our collection of 40 essential Java resources. Besides, we also have a great tutorial on the Java Enterprise Edition (Java EE) for beginners.
Post a Comment