Home > Mobile >  can we return constructor at the end of function
can we return constructor at the end of function

Time:06-26

i was solving a question on leetcode and came across the code which I'm having difficulty to understand and had searched through internet for answer but didn't found desired answer

The Question is Shuffle String on leetcode.

so, here is code!

class Solution {
    public String restoreString(String s, int[] indices) {
       char[] charArray = new char[indices.length];
        for(int i=0; i<indices.length; i  ){
            charArray[indices[i]] = s.charAt(i);
        }
        return new String(charArray);
    }
}

the last statement which return new String(charArray) which is String constructor according to me i don't know may be i'm wrong but if am i right can we return constructor to function which expect String DataType

I want some to understand the concept please can anyone explain me. I would love to have link for the study material if anyone suggest some

looking forward positively,

thanks.

CodePudding user response:

You are not 'returning a constructor'. You are constructing a String and returning it.

This:

return new String(charArray);

can be written as follows, introducing a superfluous variable just to make the point:

String r = new String(charArray);
return r;

In this reformulation, it's important not to think that you are "returning a variable", you are returning the value of a variable.

Similarly, in your original code, what you called "returning a constructor" was returning the value returned from the constructor (a reference to the newly-constructed String).

CodePudding user response:

)

The new String creates a new String object from the char-Array. So we create the String and then Return it. You can interpret this syntax as just doing both of these things consecutively. Alternatively, you could also first declare and then initialize the variable with the new String(charArray) and then return the new String, but that is unnecessary.

I hope I could help!

  • Related