Tuesday, November 22, 2011

Class Definition » Method Parameters

By Value or By Reference
  1. Primitive variables are passed by value.
  2. reference variables are passed by reference.
  3. When you pass a primitive variable, the JVM will copy the value of the passed-in variable to a new local variable.
  4. If you change the value of the local variable, the change will not affect the passed in primitive variable.
  5. If you pass a reference variable, the local variable will refer to the same object as the passed in reference variable.
  6. If you change the object referenced within your method, the change will also be reflected in the calling code.

 Reference Passing Test
class Point {
  public int x;

  public int y;
}

public class MainClass {
  public static void increment(int x) {
    x++;
  }

  public static void reset(Point point) {
    point.x = 0;
    point.y = 0;
  }

  public static void main(String[] args) {
    int a = 9;
    increment(a);
    System.out.println(a)// prints 9
    Point p = new Point();
    p.x = 400;
    p.y = 600;
    reset(p);
    System.out.println(p.x)// prints 0
  }
}
output
9
0
 
Passing objects to methods 
class Letter {
  char c;
}

public class MainClass {
  static void f(Letter y) {
    y.c = 'z';
  }

  public static void main(String[] args) {
    Letter x = new Letter();
    x.c = 'a';
    System.out.println("1: x.c: " + x.c);
    f(x);
    System.out.println("2: x.c: " + x.c);
  }
}
 
output
1: x.c: a
2: x.c: z

Use an array to pass a variable number of arguments to a method. 
This is the old-style approach to variable-length arguments. 
class PassArray {
  static void vaTest(int v[]) {
    System.out.print("Number of args: " + v.length + " Contents: ");

    for (int x : v)
      System.out.print(x + " ");

    System.out.println();
  }

  public static void main(String args[]) {
    int n1[] 10 };
    int n2[] 12};
    int n3[] {};

    vaTest(n1)// 1 arg
    vaTest(n2)// 3 args
    vaTest(n3)// no args
  }
}
 
http://www.java2s.com/Tutorial/Java/0100__
Class-Definition/Catalog0100__Class-Definition.htm


No comments:

Post a Comment