I am confused about the pass of parameters between two functions, here are two examples with opposite results:
Example 1: If I run the java code below, it will print false on the console. From my understanding, it is related to function scope so that the variable called flag would remain the same in the main function. And function called dfs can not change the variable from the main function.
class HelloWorld {
public static void main(String[] args) {
boolean flag=false;
dfs(flag);
System.out.println(flag); //this prints false
}
public static void dfs(boolean flag){
flag=true;
}
}
Example 2: this code below is a solution to leetcode 17(i.e., https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/) my question is that why the variable called combinations here would be changed(combinations here is acted as a container to store all the satisfying results) in the main function? And why function called doCombination can change the variable from the main function?
private static final String[] KEYS = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits) {
List<String> combinations = new ArrayList<>();
if (digits == null || digits.length() == 0) {
return combinations;
}
doCombination(new StringBuilder(), combinations, digits);
return combinations;
}
private void doCombination(StringBuilder prefix, List<String> combinations, final String digits) {
if (prefix.length() == digits.length()) {
combinations.add(prefix.toString());
return;
}
int curDigits = digits.charAt(prefix.length()) - '0';
String letters = KEYS[curDigits];
for (char c : letters.toCharArray()) {
prefix.append(c);
doCombination(prefix, combinations, digits);
prefix.deleteCharAt(prefix.length() - 1);
}
}
Many thanks in advance
I tried to compare those two examples mentioned above. However, I am still confused that why they would have completely different results.