Avatar ·

How to declare and initialize an array in Java? Detailed guide for beginners

Hello everyone! I just started learning Java and got confused when working with arrays. I've read several tutorials, but I still don't fully understand how to properly declare and fill arrays.\n\nThe problem is that in different sources I see different syntaxes. For example, I tried to write this code:\n\n
int numbers[] = new int[5];\nnumbers = {1, 2, 3, 4, 5};
\n\nBut the compiler gave an error. Then I saw that you can do it like this:\n\n
int[] numbers = {1, 2, 3, 4, 5};
\n\nThis works, but I don't understand why the first case gives an error and the second doesn't. I also tried to create an array of strings:\n\n
String names = new String[3];\nnames[0] = "Anna";\nnames[1] = "Ivan";\nnames[2] = "Maria";
\n\nBut something went wrong there too.