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.
}
}
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.
}
}
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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
so, is String an immutable class also ?
ASKER
so, is String an immutable class also ?
Yes, String is an immutable class. You can't change its content.
ASKER
so, is String an immutable class also ?
ASKER
sorry about the double posting!!
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);
}