Sreedhar Dhulkhed
Sreedhar Dhulkhed

Reputation: 23

Changing value of a an object of Integer class

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

Answers (3)

Nullndr
Nullndr

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

papaya
papaya

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

Subramanian Mariappan
Subramanian Mariappan

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

Related Questions