Welcome to the Treehouse Community
Looking to learn something new?
Alexander Schott8,318 Points
when to use new to allocate memory
i have learned, if we use userdefined types and instanciating objects of those classes, we have to allocate memory for them by using new. Only integrated classes like int and co doesnt need new. Why you didnt use new String() in your field declaration? Like private String mArtist = new String();
When to use new and when not?
Ryan Ruscett23,307 Points
This is a loaded question so I will do my best.
Yes, you are correct. User defined data types are created with the new keyword. But remember, String is not a user defined data type. It's also a Final class meaning you can't extend it. User defined types can also have static methods which don't require the class to be instantiated for it to work. You use new not to give memory but to call the class and it's constructors. Which set all the data and variables. the keyword new doesn't know how much memory something needs. It just kicks off the process of creating an object that has all the data set and defined within it. When you continut to add items to say an ArrayList or say String. The object gets bigger. You don't call new again to give more memory. The memory increases by way of JVM, not by way of new.
You don't need to allocate memory to this variable. It's already being done.
As soon as I see private String mArtist;
This says modifier private, String data type and mArtist, the reference to the object. Oh there it is, reference to the object. Which means it's already on the heap. It's small but will expand as needed. What you are saying is you want to take a String object, referenced by mArtist and you want to make mArtist the reference of a String object.
What if I wanted to do a valueOf method in String. If I did what you were saying I would do it like this. mArtist.valueOf wait wait. mArtist is a reference to a String Object that has valueOf method. But what is mArtist value? It doesn't have one it's a reference. So you see how it doesn't make any sense to do?
You would do something like this. private String mArtist; mArtist = "whatever"; mArtist.valueOf
now I create a String reference to mArtist. I then say mArtist equals whatever. So not I can do mArtist it's a string, with a data in which to get a value from.
Do you see where I am going with this? My brian is tired so I am starting to lose myself.