Values of variables are not exchanged within the method

Asked

Viewed 46 times

1

I do not understand why the program displays, in the last System.out.print, that:

2 5 2 4 6 8 10

Instead:

5 2 5 10 15 20 25

The first method, trocaB, should not change the values of the variables a and b?

public class Java {  
 public static void trocaB(String a, String b){  
  String tmp = a;  
  a = b;  
  b = tmp;  
 }  
 public static void trocaC(int[] array, String a){      
  for (int x = 0; x < array.length; x++){  
   array[x] = array[x] * Integer.valueOf(a);
  }  
 }  
 public static void main(String[] args){  
  int[] array = {1,2,3,4,5};  
  String a = "2", b="5";  
  trocaB(a, b);  
  trocaC(array,a);  
  System.out.print(a + " " + b + " ");  
  for (int x = 0; x < array.length; x++) {
   System.out.print(array[x] + " ");
  }    
 }  
}
  • Gentlemen(s), forgive me the stupid question, I’m still learning Java. I deeply appreciate you helping me with the links. I understood that the values of strings are immutable and that complex variables store addresses of the objects to which they are referenced. However, in the trocaB method, I say that the complex variable A, from that moment on, will refer to the complex variable B. Why doesn’t the value of A change? This should not make the variable Saving a new address?

  • Read this answer, especially the final part about Java that says references are passed by value. Highlight for the last paragraph: "references themselves are independent of each other. They are copies of each other. And tampering with a copy doesn’t change the original"

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.