Reputation: 647
Can someone tell me the different below :
void change(List<String>strings){
strings.add("Hello");
}
List<String>newString(List<String>strings){
strings.add("Hello");
return strings;
}
List<String>strings = new ArrayList<String>();
change(strings);
/// The different?
List<String>strings = new ArrayList<String>();
strings = newString(strings);
Upvotes: 1
Views: 74
Reputation: 1511
void change(List<String>strings){
strings.add("Hello");
}
The above has a void
return type, so this means the function doesn't return anything. strings.add("Hello");
will simply add the string "Hello" to the List of Strings passed in as an argument.
List<String>newString(List<String>strings){
strings.add("Hello");
return strings;
}
The above has a List<String>
return type, so an object of that type must be returned. strings.add("Hello");
will simply add the string "Hello" to the List of Strings passed in as an argument.
So the different between newString
and change
is just simply newString
adds a string to the List, and then returns the List passed in, while change
simply just adds the string, but doesn't return the List.
You can:
List<String> newList;
List<String> otherList = new ArrayList<>();
newList = newString(otherList); // can do because List<String> return type
newList = change(otherList); // can't do because void return type
Upvotes: 1
Reputation: 2521
There are no any difference.
1-method: will add new string to your list reference, which is you sent.
2-method: this method will do same thing, but finally, just return list reference.
Thus, we can say both methods are do same things. In Java, if you send object to method, it will not be copied, instead will send reference of object
Upvotes: 0