Aug 17, 2014

15. Local variables

Local variables are local to methods or the code block in which they are defined. Parameters that are passed into a method as value, and not as reference such as arrays, are also local. For example, the primitives will be copied and passed as value.




Instance and class variables must be defined outside any method. Also if two methods need access to one variable, it has to be instance or class variable.


 // *** 1. Start (Instance and Class)
 int a = 1; // Instance
 static int b = 2; // Class
 // *** 1. End



Local variables lose scope when the block in which are defined ends with }. Should we want to save it, we have to return it. We can only return one value. But if an array is passed into a function as a parameter, it is not local but references the actual address and thus any changes will persist, regardless of what is returned.


  // *** 2. Start (main() method)
  int b = 2; // Local to main()
  System.out.println(b); // local
  System.out.println(Ex15.b); // static
  Ex15 obj1 = new Ex15();
  System.out.println(obj1.a); // instance
  obj1.ex15(); // call ex15()
  // *** 2. End



The this keywords is used to access instance variables. It is especially useful if a local variable exists with the same name.


  // *** 3. Start (ex15() method)
  int b = 3; // Local to ex15()
  int a = 4; // Local to ex15()
  System.out.println(b); // local
  System.out.println((new Ex15()).a); // instance
  System.out.println(a); // local
  System.out.println(this.a); // instance
  System.out.println(this.b); // warning
  System.out.println(Ex15.b); // class ( correct way)
  // *** 3. End 



// Ex15.java
package com.javaAndroid.ex15;

public class Ex15 {
 // *** 1. Start (Instance and Class)
 int a = 1; // Instance
 static int b = 2; // Class
 // *** 1. End
 public static void main(String[] args) {
  // *** 2. Start (main() method)
  int b = 2; // Local to main()
  System.out.println(b); // local
  System.out.println(Ex15.b); // static
  Ex15 obj1 = new Ex15();
  System.out.println(obj1.a); // instance
  obj1.ex15(); // call ex15()
  // *** 2. End
 }
 // 
 void ex15() {
  // *** 3. Start (ex15() method)
  int b = 3; // Local to ex15()
  int a = 4; // Local to ex15()
  System.out.println(b); // local
  System.out.println((new Ex15()).a); // instance
  System.out.println(a); // local
  System.out.println(this.a); // instance
  System.out.println(this.b); // warning
  System.out.println(Ex15.b); // class ( correct way)
  // *** 3. End 
 }
}



No comments:

Post a Comment