All of them have a fixed value.
When I use the code below, I leave explicit the amount of indexes the array should have, in case 99 strings .
String[] array1 = new String[99];
This is how Java works with array , all and any other way - as far as I know - are mere shortcuts,
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 (I 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 output:
Não deu certo. O tamanho do índice foi extrapolado
java.lang.ArrayIndexOutOfBoundsException: 2
By using split
, it changes these array values and automatically assigns a fixed value again.
Example:
String[] array2 = {};
array2 = "Maçã, Banana, Pera".split(",");
Java automatically "converts" this code to a fixed array and then passes its reference to the variable array2 . p>
Ps .: If you'd like to test the codes, you can use link