Accepting and Returning Arrays in Java - Methods returning arrays: demo
(Page 3 of 5 )
In the previous section, we went through only the methods accepting arrays as parameters. Now, we shall see about methods returning arrays. Modify your code (in “MyCalc.java”) so that it looks something like the following:
package MyPack;
/**
*
* @author Administrator
*/
public class MyCalc {
int[] a;
/** Creates a new instance of MyCalc */
public MyCalc() {
}
public void setValues(int[] p) {
a = p;
}
public int[] getDoubledValues() {
int[] b = new int[a.length];
for(int i=0;i<a.length;i++) {
b[i] = a[i] + a[i];
}
return b;
}
public int getSum() {
int s=0;
for(int i=0;i<a.length;i++) {
s += a[i];
}
return s;
}
}
Now, go back to the frame “test.java.” Double click on it to open and finally double click on the button to open source view. Within the source view, modify your “buttonActionPerformed” in such a way that it looks like the following:
private void btnShowActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
MyCalc obj1 = new MyCalc();
MyCalc obj2 = new MyCalc();
int[] ar = {12,23,34,45,56,67};
obj1.setValues(ar);
obj2.setValues(obj1.getDoubledValues());
int r;
r = obj1.getSum();
this.lblMsg.setText("Sum = " + String.valueOf(r));
r = obj2.getSum();
this.lblMsg2.setText("Sum = " + String.valueOf(r));
}
The next section will explain the above code.
Next: Methods returning arrays: explanation >>
More Java Articles
More By Jagadish Chaterjee