Reputation: 23
How to change value of a an object of Integer class ex: here I have declared the values of objects x and y to 5 and 6 respectively and I want to swap the value stored in the objects i.e x.intValue() should be 6 and y.intValue() should be 5. Please help.
class second{
public static void main(String[] args) {
System.out.println(In1.a);
Integer x = new Integer(5);
Integer y = new Integer(6);
System.out.println(x.equals(y));
System.out.println(x.intValue());
}
}
Upvotes: 0
Views: 1114
Reputation: 1827
You can use a third variable.
public static void main(String[] args){
Integer a = new Integer(6);
Integer b = new Integer(3);
Integer temp = a;
a = b;
b = temp;
}
Upvotes: 1
Reputation: 1545
Adding a different answer without using a temporary variable
Integer x = 10;
Integer y = 5;
x = x + y;
y = x - y; //y contains 10
x = x - y; //x contains 5
Upvotes: 2
Reputation: 3886
Try,
Integer temp = x;
x = y;
y = temp;
1 ) Have the value of x in a temporary variable
2 ) Assign value of y to x
3 ) Assign value of temp to y
In this way, your values of x and y will get swapped.
Upvotes: 1