S
S
STVDI2020-07-19 14:19:47
Java
STVDI, 2020-07-19 14:19:47

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

1 answer(s)
O
Oleg Zakharov, 2020-07-19
@STVDI

Primitives are always passed by value
Only the argument is updated at this point

public static void incrementA(int first)
{
first = first + 1;
}

I wanted it like this:
public static void incrementA(int first)
{
this.first = first + 1;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question