Skip to content

Week 4 - Methods

Methods

Method Signature

  • Access Modifer (public, protected, private),
    • Optional [static] modifier,
      • Return Type (void, double, String, Object, etc)
        • Method Name (Anything you want following nameing convention)
          • Method Parameters (Comma separated list of DataType parameterName)

Static/Class Method

First Let’s Re-Visit Static

  • In the Student class below remember you can declare static variables, which are variables that won’t vary with instances of a class.
1
2
3
4
5
6
7
class Student {
    String name;   // Student name always varies with student
    String ssn;    // Student social security number always varies with the student.
    int startYear; // The student's academic start year will always vary with the student.
    static String institution;  // static variable because the current school/institution does not vary per student.
    static int semester;        // static variable because the current semester will not vary per student.
}
  • Storing variables statically is more memory efficient because we don’t have separate storage locations for institution and semester per student.
  • Because static means class-level we only allocate memory for these variables once when the class is loaded.
  • Static is largely used for efficient memory mangagment in Java.

  • Example of a static or class method (i.e. belongs to the class)

    1
    2
    3
    4
    5
    public class MyClass {
        public static void main(String args[]) {
            // Method block statments go here...
        }
    }
    

  • Every instance of the class has access to the static/class method.

    • If ANY instance of the class modifies the static variable, its modified for ALL Instances
  • Static methods can access static/class variables without an object instance.
  • Only static data can be accessed.
  • All static variables and methods are stored in the Heap when a class is loaded, but the Addresses are shared.
    • Prior to Java 8, there used to be a static/non-heap memory location called the Method Area or PermGen where they were stored, but this is no longer used.
    • A new area of Heap called MetaSpace is now used where all the names fields of the class, methods of a class with the byte code of methods, constant pool, JIT optimizations are stored.

Memory of Static Var/Method

Static Instance Counter
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class InstanceCounter {

   private static int numInstances = 0;

   protected static int getCount() {
      return numInstances;
   }

   private static void addInstance() {
      numInstances++;
   }

   InstanceCounter() {
      InstanceCounter.addInstance();
   }

   public static void main(String[] arguments) {
      System.out.println("Starting with " + InstanceCounter.getCount() + " instances");

      for (int i = 0; i < 500; ++i) {
         new InstanceCounter();
      }
      System.out.println("Created " + InstanceCounter.getCount() + " instances");
   }
}

  • This is a mental picture, of Instance methods, but in reality a single memory location is used and the Object pointer is passed to it. Memory of Non-Static Var/Method
    Object Instance Counter
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    public class InstanceCounter {
    
       private static int numInstances = 0;
    
       protected static int getCount() {
          return numInstances;
       }
    
       private void addInstance() {
          numInstances++;
       }
    
       InstanceCounter() {
          this.addInstance();
       }
    
       public static void main(String[] arguments) {
          System.out.println("Starting with " + InstanceCounter.getCount() + " instances");
    
          for (int i = 0; i < 500; ++i) {
             new InstanceCounter();
          }
          System.out.println("Created " + InstanceCounter.getCount() + " instances");
       }
    }
    

Public/Object/Instance Method

  • Example of a public or object/instance method (i.e. can only be called from an object instance)

    1
    2
    3
    4
    5
    public class MyClass {
        public String sayHello(String firstName, String lastName) {
            return "Hello %s %s!".format(firstName, lastName);
        }
    }
    
  • Does NOT contain static keyword.

  • Requires an Object Instance to call.
    • Belong to the Object of the class, not to the class
  • Are NOT stored on a per-instance basis, even with virtual methods (CIS-18 will talk about these).
    • They’re stored in a single memory location, and they only know which object they belong to because the Object’s pointer is passed when you call them.
  • They can be overridden since they are resolved using dynamic binding (binding method to method body/declaration) at run time.

Calling Methods

Calling a Static/Class Method

  • Example calling the static/class method
    1
    MyClass.main(new String[]);
    

Calling an Object/Instance Method

  • Example calling the public/object/instance method
    1
    2
    MyClass myClass = new MyClass();
    myClass.sayHello("Trevor", "Hartman");
    

Scope

Static Variable / Method Scope

  • You can NOT declare static variables in main(String[] args) or any other method.
  • Static variables/methods must be declared as class members, since the belong to the class.
  • Static variables/methods can be accessed by calling the class name, no instance needed.
  • Static variables/methods can be called from static OR non-static methods.

Non-Static / Instance Method Scope

  • Can only be accessed by first creating an instance of the class.
  • Trying to access a non-static variable from a static method is an error.
Error Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class Scaler {

  int number;

  static void check() {
    // Error as non-static number is accessed in a static method
    System.out.println(number);
  }

  void check1() {
    System.out.println(number); // Valid accessing
  }
}
Example of Proper Access
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Main {

  static int age = 10;
  int objAge;

  public Main(int objAge) {
    this.objAge = objAge;
  }

  public int getObjAge() {
      return this.objAge;
  }

  public static void main(String[] args) {
    // Static variable access in static Method
    System.out.println(Main.age);
    System.out.println(age);

    // Object/Instance method access to static variable (works with WARNINGs)
    Main ob = new Main();
    System.out.println(ob.age);  // WARNING
    System.out.println(ob.objAge); // Need an object to access non-static variable
    System.out.println(ob.getObjAge()); // Need an object to access non-static variable
  }
}

What do we use Methods for?

  • Reuseable Code!
    • i.e. don’t have to rewrite System.out.println from scratch every time we want to print to console.
  • Parameterize Code
    • Allow us to provide a parameters that changes the way the code works.
  • Top-Down Programming
    • Solve big problems by breaking it down into smaller parts (i.e. methods)
  • Smaller Conceptual Units (Cleaner Code)
    • Makes it easier to debug and maintain the code over-time if methods are concise and well-named.
  • Abstraction
    • Methods hide local variables and implementation from rest of code, simplifying other parts of the program.

When to use Static Methods

  • Static Methods criteria for use

    • static methods can’t modify the state of an object.
      • 4 wheels of a car, but all 4 are independent or have independent state.
    • static methods mostly operate on arguments passed into it, commonly Utility Methods.
      • java.lang.Math or StringUtils both only really perform action on arguments.
      • StringUtils.isEmpty(String text)
    • if you need a method to act on the entire class hierarchy
      • equals() method for Ojbects is a good example
  • Other Examples of Static Methods

    • Factory design pattern (i.e. a method to CREATE other objects)
    • Utility methods like Array (provides methods that only work on array arguments)
    • valueOf functions that convert types
  • Every other type of method should be a public/object/instance method

Method Parameters

  • Parameters are values given to a method that can be used in its execution.
  • The parameters of a method are defined on the uppermost line of the method within the parentheses following its name.
  • The values of the parameters that the method can use are copied from the argument values given to the method when it is executed.

Example Parameterized Method
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class Main {
    public static void greet(int numOfTimes) {
        int i = 0;
        while (i < numOfTimes) {
            System.out.println("Greetings!");
            i++;
        }
    }

    public static void main(String[] args) {
        greet(1);
        System.out.println("");
        greet(3);
    }
}
* A method can be defined with multiple parameters. * When calling such a method, the parameters are passed in the same order.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class Main {
    public static void main(String[] args) {
        sum(3, 5);

        int number1 = 2;
        int number2 = 4;

        System.out.println("" + number1 + " + " + number2 + " = " + sum(number1, number2));
    }

    public static int sum(int first, int second) {
        return first + second;
    }
}

Excercises

  1. Create a method called printText which prints the phrase “In a hole in the ground there lived a method” and a newline.
Exercise 1
1
2
3
4
5
6
7
8
9
public class Main {
    public static void main(String[] args) {
        Main.printText();
    }

    public static void printText() {
        System.out.println("In a hole in the ground there lived a method.");
    }
}
  1. The code below contains a method that has been named with an incorrect style.
    1
    2
    3
    public static void printcodingis_cool() {
        System.out.println("Coding is cool!");
    }
    
Exercise 2
1
2
public static void printCodingIsCool() {
}
  1. Write a method public static void division(int numerator, int denominator) that prints the result of the division of the numerator by the denominator. Keep in mind that the result of the division of the integers is an integer — in this case we want the result to be a floating point number.
Exercise 3
1
2
3
4
5
6
7
8
9
public class Main {
    public static void main(String[] args) {
        Main.division(22, 7);
    }

    public static void division(int numerator, int denominator) {
        System.out.println(1.0*numerator/denominator);
    }
}