3
I’m recurring in two situations: one changes an object field and the other directly changes the string. What is the difference between these two forms of return since it gives different result?
public class Person {
String fname = "f";
String lname = "Doe";
int age = 24;
public static String mudaNome(String nome){
if(!nome.equals("fiii")){
nome = nome + "i";
System.out.println("name1: " +nome);
mudaNome(nome);
}
System.out.println("name1 output: " +nome);
return nome;
}
public static Person mudaNomeObj(Person myObj){
if(!myObj.fname.equals("fiii")){
myObj.fname = myObj.fname + "i";
System.out.println("name2 : " +myObj.fname);
mudaNomeObj(myObj);
}
System.out.println("name2 output: " +myObj.fname);
return myObj;
}
public static void main(String[] args) {
Person myObj = new Person();
System.out.println("name1 final output:" +mudaNome(myObj.fname));
System.out.println("---------------");
Person myObj2 = new Person();
System.out.println("name2 final output:" + mudaNomeObj(myObj2).fname);
}
}
Exit:
name1: fi name1: fii name1: fiii name1 output: fiii name1 output: fiii name1 output: fii name1 output: fi name1 final output:fi --------------- name2 : fi name2 : fii name2 : fiii name2 output: fiii name2 output: fiii name2 output: fiii name2 output: fiii name2 final output:fiii
Great. Thank you, bro!
– Hugo V