If you want to go past the basics of working with methods in Java, this article is for you. You will learn about methods returning no values, methods accepting parameters, and more.
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:
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: