Link to home
Start Free TrialLog in
Avatar of eugeneng
eugeneng

asked on

how to set the value of the Integer instance?

how to set the value of the Integer instance? for example, how to make the following Update work ?


class m
{
  public static void Update(Integer i)
  {
   // how to update the value of i to some arbitrary value
   // say, 999, i = new Integer(999) won't work.
  }
}
Avatar of yuri1976
yuri1976

this won't work because you can't change the reference of the external value i. This is what you do when you say i = new Integer(999).
And as Integer is a immutable class (you can't change the contents), you can't change the value of i also. The only way to do such a action is to calculate the new value and return it.

public static Integer Update(Integer i) {
  // do your calculations on i
  // and return the result
  return new Integer(999);
}
You need to make i a class variable not a parameter.

try this

class mytest
{

  private Integer i=new Integer(5);

  public void Update()
  {
     this.i=new Integer(999);
  }

  public Integer getVal()
  {
     return this.i;
  }

}

Then call the class using code similar to the following.

public static void main(String args[])
{
      mytest m = new mytest();
      Integer i = m.getVal();
      System.out.println("i=" + i.toString());
      m.Update();
      i = m.getVal();
      System.out.println("i=" + i.toString());

   }
}

Hope this helps.

Darren.
ASKER CERTIFIED SOLUTION
Avatar of yongsing
yongsing

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of eugeneng

ASKER

so, is String an immutable class also ?
so, is String an immutable class also ?
Yes, String is an immutable class. You can't change its content.
so, is String an immutable class also ?
sorry about the double posting!!