You are here:

Java/Passing and returning array elements

Advertisement


Question
Hi,

If I want to pass an array elment to have it changed, is the code below the proper way to do it? Note, I skipped the for loops I would use to add numbers to the array.

//ClassOneTest

ClassTwoTest classTwo = new ClassTwoTest();

int array[] = new int[4];

array[2] = classTwo.getElement(array[2]);

---------------

//ClassTwoTest

public int getElement(int element) {
    element = 5;
    return element;
}

Thanks

Answer
In the case you have, yes. int is a primitive and cannot be modified. For this reason, you can replace it in the array with another primitive. With class instances, it is possible to simply modify the item directly (which would modify all references to it). In that case you would have a void method and not return anything (or have the method return the same instance).

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.