简体   繁体   中英

Not getting the value x and y i.e (10 and 5) in the replace method?

package interview_programs;
public class Swapping {

    int x,y ;

    Swapping(int a, int b){ 
    int x = a;      
    int y = b;
    System.out.println("the valueof x is" + x);
    System.out.println("the valueof y is" + y);     
    }

    public void replace(){
    x = x + y;
    y = x - y;
    x = x - y;          
    System.out.println("the value after swap");
    System.out.println("the valueof x is" + x);
    System.out.println("the valueof y is" + y);             
    }   

    public static void main (String args[]) {   
    Swapping Swap = new Swapping(10,5);
    Swap.replace(); 
    }
}

This is the output getting on console.

Output:

the valueof x is10

the valueof y is5

the value after swap

the valueof x is0

the valueof y is0

You do not initialize your class-level x and y but the local x and y in your constructor.

Replace 'int x = a' with 'x = a' and 'int y = b' with 'y = b'.

Take out the int from x and y. These are creating local variables and not setting the local class fields.

Swapping(int a, int b){ 
  x = a;      
  y = b;
  System.out.println("the valueof x is" + x);
  System.out.println("the valueof y is" + y);     
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM