I have never seen the keyword "new" used in a return statement and my understanding of new is that it creates a new object. And "new" used in this context Practice permutation = new Practice(); is that it creates a new object called permutation. And permutation is a reference to some memory address. So maybe, return new String(content) is return a memory address? So my question is, what does new used in this context actually mean? I apologize for my noob question...
import java.util.Arrays;
public class Practice {
public String sort(String s) {
char[] content = s.toCharArray();
Arrays.sort(content);
return new String(content);
}
public static void main(String[] args){
Practice permutation = new Practice();
System.out.println(permutation.sort("hello"));
}
}
return new String(content); means it creates a new string object with the content you have passed. It's similar to
String str = new String(content)
return str;
When using the keyword new you shouldn't associate it with any assignment operator. What the new keyword does, in laymans terms, is it creates a reference to a new instance of the specified class and returns it. So when you put the statement
new Object();
That statement is completely valid and it is returning a new reference to an Object class. The only thing is that the reference doesn't get set to anything because there is no operator performing on it. So when you have
Object myObj = new Object();
The reference comes from the new Object() statement and the equals operator sets it equal to the myObj variable. So now, if you understand that, when you have
return new Object();
The reference comes from the new Object() statement again and the return keyword takes that reference and returns it out of the method that you're in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With