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};
4 Answers
+ 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
0
I don't get this part
This means that the same thing will be written two times
2times why?
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);
0
https://code.sololearn.com/cZzTT3H09obg/?ref=app
see this code. you may understand better