Java Methods

From JavaProgramming

About passing arguments to methods in Java, which is very different from C++

Default values for method arguments as we know and love from C++ are not allowed. A new method has to be declared for every method signature:

 /* TestDefaultConstructor.java */
 public class TestDefaultConstructor {
private int i;
private String s;
 //  public TestDefaultConstructor(String arg = "") {// Not allowed
public TestDefaultConstructor() {
i = 0;
System.out.println("TestDefaultConstructor()");
}
public TestDefaultConstructor(String arg) {// "Overloaded" constructor
this(); // Call default constructor
s = arg;
System.out.println("TestDefaultConstructor\(\" + arg + \"\)");
}
public static void main(String[] args) {
TestDefaultConstructor obj = new TestDefaultConstructor("abc");
// output: TestDefaultConstructor()
// TestDefaultConstructor(abc)
}
 }

Method arguments are allways called by value. Calling by reference is not possible for basic data types such as integer. In order to call by reference, variables of basic data types must be wrapped within an object:

 /* TestMethodCall.java */
 class Wrapper {
public int i;
public Wrapper(int n) { i = n; }
 }

public class TestMethodCall { public static void inc(int i) { i++; }// Primitive types is call by value public static void inc(Wrapper w) { w.i++; } // Argument is an object reference public static void main(String[] args) { int i = 1; inc(i); System.out.println(i); // Output: 1, i is only modified locally Wrapper w = new Wrapper(i); inc(w); System.out.println(w.i); // Output: 2, Wrapper object is modified } }


EditText of this page (last edited August 12, 2008) or FindPage with title or text search