0

the new keyword and java

when should I use the new keyword in java? I'm confused string a = "some" string a= new string ("some"); int [] array ={3,4,5,6}; int []array = new int []{34,5,6,7};

20th Jun 2017, 10:50 AM
Navid Tak
Navid Tak - avatar
4 odpowiedzi
+ 3
There comes a term 'string pool'. think of it as a notebook where string called are written. When we use double quotes to create a String, it first looks for String with same value in the String pool, if found it just returns the reference else it creates a new String in the pool and then returns the reference. However using new operator, we force String class to create a new String object in heap space. This means that the same thing will be written two times in the string pool or the virtual 'notebook'. This causes waste of memory and the first method is recommended. Same goes for the int example
20th Jun 2017, 3:24 PM
Snehit Sah
Snehit Sah - avatar
0
I don't get this part This means that the same thing will be written two times 2times why?
20th Jun 2017, 8:57 PM
Navid Tak
Navid Tak - avatar
0
in java all is an object except for primitive type (int, double, boolean, char ...) you can distinguish classes from capital letter. String is a class, it means you can write String hello=new String("hello"); or String hello = "hello"; The keyword new invoke the constructor of the class. The constructor have the same name of the class followed by parenthesis with the necexary parameter. The constructor of String is String(aStringParameter); Usually you need to use a constructor to assign a value to an object: Author author = new Author(name,surname);
21st Jun 2017, 12:31 AM
Federico Bachis
Federico Bachis - avatar
0
https://code.sololearn.com/cZzTT3H09obg/?ref=app see this code. you may understand better
23rd Jun 2017, 12:46 PM
Snehit Sah
Snehit Sah - avatar