Aug 18, 2014

16. Parameters

Different kinds of parameters can be passed to methods, such as primitives, arrays, and objects.




A test class, Ex16a, is written with instance variables x and y.


// *** 1. Start (Ex16a)
class Ex16a {
 public int x = 5;
 public int y = 8;
}
// *** 1. End



This method changes the instance variables.


 // *** 2. Start (change class)
 public static void retc(Ex16a c) {
  c.x = 10;
  c.y = 20;
 }
 // *** 2. End



If we pass primitives to a method, local variables will be created.


 // *** 3. Start (change local)
 public static void reta(int a) {
  a = a + 1;
 }
 // *** 3. End



If we pass a String, a local variable is made of that Sting.


 // *** 4. Start (change local)
 public static void rets(String s) {
  s = "abcd";
 }
 // *** 4. End



However, arrays, are passed by reference so any array changes persist.


 // *** 5. Start (change array)
 public static void retA(int[] A) {
  A[0] = 5;
  A[1] = 2;
 }
 // *** 5. End



// Ex16.java
package com.javaAndroid.ex16;

// *** 1. Start (Ex16a)
class Ex16a {
 public int x = 5;
 public int y = 8;
}
// *** 1. End

public class Ex16 {
 // *** 2. Start (change class)
 public static void retc(Ex16a c) {
  c.x = 10;
  c.y = 20;
 }
 // *** 2. End
 // *** 3. Start (change local)
 public static void reta(int a) {
  a = a + 1;
 }
 // *** 3. End
 // *** 4. Start (change local)
 public static void rets(String s) {
  s = "abcd";
 }
 // *** 4. End
 // *** 5. Start (change array)
 public static void retA(int[] A) {
  A[0] = 5;
  A[1] = 2;
 }
 // *** 5. End
 public static void main(String[] args) {
  int a = 5;
  Ex16.reta(a);
  System.out.println(a);
  String s = "This";
  Ex16.rets(s);
  System.out.println(s);
  int[] A = {1,1,1};
  Ex16.retA(A);
  for (int arr : A) {
   System.out.println(arr);
  }
  Ex16a ex16a = new Ex16a();
  System.out.println(ex16a.x + "," + ex16a.y);
  Ex16.retc(ex16a);
  System.out.println(ex16a.x + "," + ex16a.y);
 }
}



No comments:

Post a Comment