More about methods in Java using NetBeans IDE - Methods accepting parameters: explanation
(Page 4 of 5 )
This section will explain the code listed in the previous section. Let us start with the following:
int x=0;
int y=0;
int z=0;
There is no much of a difference in the “Fields.” The following is the new “method” I introduced:
public void addValue(int v) {
x += v;
y += v;
}
The above method is named “addValue.” It returns a “void” type (which returns nothing). But it accepts a parameter “v.” That means we need to pass some value (of type integer) when we call this method.
Now, if we proceed to our “test” frame, we have the following initially:
MyCalc obj1 = new MyCalc();
obj1.x = 10;
obj1.y = 20;
obj1.addValue(2);
obj1.calcSum();
I declared an object named “obj1.” Now, it internally contains five members (x, y, z, calcSum and addValue). You can also observe that I am simply providing the values for “x” and “y” (but not “z”). After assigning the values to “x” and “y,” I am simply calling the following statement:
obj1.addValue(2);
You can observe that we are passing a value 2 while calling the method “addValue.” This will be automatically passed to the variable “v,” and finally the same value gets added to both “x” and “y.” After that, I am simply calling “obj1.calcSum.” This method will indeed calculate the sum of “x” and “y” and place the result in “z” (which is also a member of the same object “obj1”).
Similarly, I am also working with another object as follows:
MyCalc obj2 = new MyCalc();
obj2.x = 100;
obj2.y = 200;
obj2.calcSum();
Once the calculations are over, I display the values of “z” in each of those objects with the following two statements:
this.lblMsg.setText("Sum = " + String.valueOf(obj1.z));
this.lblMsg2.setText("Sum = " + String.valueOf(obj2.z));
Next: A method that accepts parameters and returns a value >>
More Java Articles
More By Jagadish Chaterjee