Search code examples
javaobjectnew-operator

When is the appropriate time to use the 'new' keyword?


When is it necessary to use the new keyword in Java. I know you are supposed to use it when you create an instance of an object like this:

TextView textView = new TextView(this);

Sometimes in code I notice that new isn't used and I get confused.. In this line of code:

    AssetManager assetManager = getAssets();

Why isn't an instance of the AssetManager created like this:

AssetManager assetManager = new AssetManager();

then it is set equal to getAssests()?

When should new be used?


Solution

  • You use the new keyword when an object is being explicitly created for the first time. Then fetching an object using a getter method new is not required because the object already exists in memory, thus does not need to be recreated.

    if you want a more detailed description of new visit the oracle docs

    An object will need the 'new' keyword if it is null (which is fancy for not initialized).

    This will always print "needs new" under the current circumstances.

    Object mObj = null;
    if (mObj == null)
        System.out.println("needs new");
    else
        System.out.println("does NOT need new");
    
    OUTPUTS: needs new
    

    So to fix it, you would do something like:

    Object mObj = new Object();
    if (mObj == null)
        System.out.println("needs new");
    else
        System.out.println("does NOT need new");
    OUTPUTS: does NOT need new
    

    And under those circumstances we will always see "does NOT need new"