Answer the question
In order to leave comments, you need to log in
JAVA how to increment object argument?
I am interested in understanding how to write a method that, when called, will
ncrementA(c2.a);
incrementB(c2.b);
increase them.
I get some kind of nonsense (
Public class MyClass
{
private int a;
public double b;
public MyClass(int first, double second)
{
this.a = first;
this.b = second;
}
public static void incrementBoth(MyClass c1) {
c1.a = c1.a + 1;
c1.b = c1.b + 1.0;
}
// new method
public static void incrementA(int first)
{
first = first + 1;
}
// new method
public static void incrementB(double second)
{
second = second + 1.0;
}
public static void main(String[] args)
{
MyClass c1 = new MyClass(10, 20.5);
MyClass c2 = new MyClass(10, 31.5);
// different code below
incrementA(c2.a);
incrementB(c2.b);
System.out.println(c2.a + ", "+ c2.b);
}
}
Answer the question
In order to leave comments, you need to log in
Primitives are always passed by value
Only the argument is updated at this point
public static void incrementA(int first)
{
first = first + 1;
}
public static void incrementA(int first)
{
this.first = first + 1;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question