Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the keyword "new" in a return statement

Tags:

java

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"));
    }
}
like image 274
aejhyun Avatar asked Feb 18 '26 17:02

aejhyun


2 Answers

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;
like image 99
Shriram Avatar answered Feb 21 '26 06:02

Shriram


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.

like image 36
Jmrapp Avatar answered Feb 21 '26 06:02

Jmrapp