Java method can accept data from callers via parameters.
The following code creates a method to calculate square for any input integer values.
int square(int i) { return i * i; }
square()
will return the square of whatever value passed in.
public class Main { public static void main(String args[]) { System.out.println(square(2)); System.out.println(square(10)); }/* w ww .j a v a 2 s . c o m*/ static int square(int i) { return i * i; } }
The following code shows how to pass in array as parameters.
// Use an array to pass a variable number of arguments to a method. public class Main { static void myTest(int v[]) { System.out.print("Number of args: " + v.length + " Contents: "); for(int x : v) System.out.print(x + " "); System.out.println(); //from ww w . j ava 2 s . c om } public static void main(String args[]) { // Notice how an array must be created to // hold the arguments. int n1[] = { 10 }; int n2[] = { 1, 2, 3 }; int n3[] = { }; myTest(n1); // 1 arg myTest(n2); // 3 args myTest(n3); // no args } }
The following code use parameters to set new dimensions of a lego block.
// uses a parameterized method. class LegoBlock { double width;//from w w w. ja va 2 s . co m double height; double depth; // compute and return volume double volume() { return width * height * depth; } // sets dimensions void setDim(double w, double h, double d) { width = w; height = h; depth = d; } } public class Main { public static void main(String args[]) { LegoBlock myLegoBlock1 = new LegoBlock(); LegoBlock myLegoBlock2 = new LegoBlock(); double vol; // initialize each box myLegoBlock1.setDim(10, 20, 15); myLegoBlock2.setDim(3, 6, 9); // get volume of first lego vol = myLegoBlock1.volume(); System.out.println("Volume is " + vol); // get volume of second lego vol = myLegoBlock2.volume(); System.out.println("Volume is " + vol); } }
We can pass objects to methods.
For example, consider the following short program:
// Objects may be passed to methods. class Test {/* www. j a va 2 s . c om*/ int a, b; Test(int i, int j) { a = i; b = j; } // return true if o is equal to the invoking object boolean equalTo(Test o) { if(o.a == a && o.b == b) return true; else return false; } } public class Main { public static void main(String args[]) { Test ob1 = new Test(100, 22); Test ob2 = new Test(100, 22); Test ob3 = new Test(-1, -1); System.out.println("ob1 == ob2: " + ob1.equalTo(ob2)); System.out.println("ob1 == ob3: " + ob1.equalTo(ob3)); } }
The equalTo()
method compares two objects for equality.