0
strings
int[ ] arr = new int[5]; Take this array as an example. why for most strings we add the "new" part? Couldnt I just leave it as is?
2 Answers
+ 3
Creating a variable involves two steps:
- declaration: the type and the name of the variable. This is the left side of the equal sign.
- initialization: allocate the value to the variable. This is the right side.
If the value is an object reference, that object must first be created in the memory. This is happening through the new keyword. Some bytes are reserved in the memory according to the type of the object.
+ 1
You can omit new for non-referenced types, which means primitives like
int i = 100;
for wrapper types and for String
Integer i = 100;
String str = "abcdefgh";
For array, it is possible to write without new
int[] a = {0,1,2,3};
For some types, there is also a "factory" method, e.g
Integer i = Integer.valueOf( 100 );