strings | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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?

13th Jul 2022, 7:48 AM
sabo
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.
13th Jul 2022, 8:33 AM
Tibor Santa
Tibor Santa - avatar
+ 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 );
13th Jul 2022, 1:46 PM
zemiak