You are here:

Java/Passing and returning array elements



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.


ClassTwoTest classTwo = new ClassTwoTest();

int array[] = new int[4];

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



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


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).


All Answers

Answers by Expert:

Ask Experts


Artemus Harper


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


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#

Washington State University

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

©2017 All rights reserved.