bench
bench

Reputation: 136

Refernces, pointer and variables in Java

I usually program in python and C, so this world of java confuses me quite a bit.

I am looking for a way to make my code more elegant, and in these other languages I would do it by passing by reference (or with pointers, depending on the language), the variable.

At one point in the code, I repeat a piece of code several times because each one depends on a certain previous situation. In summary, it could be understood that I want to modify several variables with the same code block, for which I first want to select the variable that I want to modify, assign it a "nickname", and then work with the nickname but modify the original variable.

So i want to change this

if (condition){
    if (condition){
        //modify var1
    } else {
        //modify var2
    }
}else if (condition){
    if (condition){
        //modify var1
    } else {
        //modify var2
    }
}

for something like this

if (condition){
    nickname = var1;
} else {
    nickname = var2;
}

if (condition){
    // modify nickname
}else if (condition){
    // modify nickname
}

Is there a way to do this in Java? Or am I condemned (using this aproach) to have redundant code?

In C i could do something like

// nickname as pointer from type of var1 and var2
if (condition){
    nickname = &var1;
} else {
    nickname = &var2;
}

// Work over nickname

Upvotes: 0

Views: 80

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86754

Given

if (condition){
    nickname = var1;
} else {
    nickname = var2;
}

This works ONLY if var1 and var2 are:

  1. References to object instances (i.e. not primitive values)
  2. Mutable, i.e. have internal state that can be changed (String is immutable)
  3. Type-compatible with each other. nickname must be assignable from both var1 and var2

In that case you can use nickname to modify the internal state of a referenced object.

Upvotes: 1

Related Questions