They all have a fixed value.
When I use the code below, I make explicit the amount of indexes that the array must have in case 99 strings.
String[] array1 = new String[99];
That’s how the Java works with array, any other way - as far as I know - are mere shortcuts, I explain later.
When we initialize the variable during creation (see below), we make a shortcut to the previous code.
String[] array2 = {"Pera", "Uva"};
In this example, the code is automatically converted by the compiler to String[] array2 = new String[2];
. You can confirm this using the code below (used Java 9.0.1
).
import java.util.Arrays;
import java.lang.ArrayIndexOutOfBoundsException;
public class HelloWorld
{
public static void main(String[] args)
{
try {
String[] array2 = {"Pera", "Uva"};
array2[2] = "Maçã";
System.out.println(Arrays.toString(array2));
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Não deu certo. O tamanho do índice foi extrapolado");
System.out.println( e.toString() );
}
}
}
Expected exit:
Não deu certo. O tamanho do índice foi extrapolado
java.lang.ArrayIndexOutOfBoundsException: 2
Already the use of split
, it alters these values of array and automatically assigns a fixed value again.
Example:
String[] array2 = {};
array2 = "Maçã, Banana, Pera".split(",");
The Java automatically "converts" and this code to a array fixed and then passes its reference to the variable array2.
Ps.: If you want to test the codes, you can use https://www.jdoodle.com/online-java-compiler