Java: create and use arrays - how it works
Related Videos: Java Programming Tutorial - 27 - Introduction to Arrays (May 2024).
An array is a collection of variables of the same type. In this practical tip you can read how you can create and use arrays correctly in Java.
Create arrays in Java
If you have not yet worked with Java, you can read the Java Basics here first. You can find some examples in the picture gallery at the end of the article.
- For example, if you need to store a lot of different numbers, you can store them in an array in Java. To declare an array, you must first write the data type and two square brackets. The "int [] arr;" command creates an integer array called "arr".
- You also need to set the capacity of the array. Use the "int [] arr = new int [5];" command to create an array that can store five integers.
- In an array all elements are ordered and have a certain position, which is also called "index".
- For example, you can use the "arr [2] = 42;" command to assign the value 42 to the element with index 2.
- Note, however, that the computer starts counting from 0.
- So that you don't have so much paperwork, you can also create an array with a command such as »String [] arr2 = {" A ", " B ", " C ", " D "};«. This command automatically creates an array called "arr2" that can hold 4 strings.
Java: Tips for working with arrays
- You can get the length of an array with »arr.length«. You can also include this command in for loops, for example.
- In Java there is also a function called "Enhanced For Loop". First, a variable is declared which is compatible with the data type of the array. This variable is inserted in the for command. The value of the variable is equal to the value of the current array element. So you can have all values of an array output one after the other. An example would be the code "int [] primes = {2, 3, 5, 7};" ⮩ "for (int t: primes) {" ⮩ "System.out.println (t);" ⮩ "}".
Multidimensional arrays in Java
A multidimensional array is an array that contains other arrays.
- The command "int [] [] sample = {{1, 2, 3}, {4, 5, 6}};" creates an array that contains two individual arrays. The command "System.out.println (sample [1] [0]);" returns the value 4.
- In Java, however, you are not limited to one- or two-dimensional arrays. An array can contain as many arrays as you want.
Learn Java Programming - Part 4
Now that you know how to use arrays correctly in Java, we will explain in the next part of the programming guide what you need to know about "classes in Java".
Next we show how you can embed a catcha on one side.