+ 2

Basic array question

Hi All, Why do we need to use the word ‘new’ when declaring an array, as in : String[] arr = new String[5]; Why not simply write : String[] arr = String[5]; ? :)

29th Oct 2018, 12:22 AM
Robert Iticovici
Robert Iticovici - avatar
5 Antworten
+ 2
Because the keyword new is used to allocate a new memory for an object, if it is not used, it will become a assignment statement, and the variable to The right of The equal should be an existing variable.
29th Oct 2018, 4:02 AM
niewu
+ 6
The new keyword is required to allocate memory for the creation of a class object. String[] arr = String[5]; doesn't really make sense since String[5] has to be preceded by the new keyword, or followed by an identifier to declare an array of Strings (which would still be a syntax error since you can't declare variables this way on RHS). The only explanation is that the syntax of Java mandates the use of new to create new objects.
29th Oct 2018, 12:38 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
yes ! it’s an object, not a variable - that’s why. variables are already assigned a size ( in bytes ) but objects aren’t thank you very much for your help 🙏
29th Oct 2018, 12:44 AM
Robert Iticovici
Robert Iticovici - avatar
+ 1
New is a keyword used to allocate the memory to the array
2nd Nov 2018, 1:46 AM
R. Naga Sowjanya
R. Naga Sowjanya - avatar
+ 1
New keyword is used so that new memory is allocated for the object. Its same as when we create input for the system. Scanner sc=new Scanner(String. in). New means to create some new space for this default.
2nd Nov 2018, 11:03 AM
himanshu kumar
himanshu kumar - avatar