Method

Definition

A method is a series of statements that perform one task. Methods take in one or more values and can return zero or one value.

Benefits

Methods are useful for performing a series of statements numerous times without having to duplicate the code. Methods are also great for breaking a large program into manageable chunks.

Using Methods

Main Method

Every Java application must contain a main method. The main method is the starting point for your program. The main method's header is as follows:

public static void main (String[] args)

Constructors

  1. Constructors are used for initialization of instance variables
  2. Constructors are automatically invoked when the object is created
  3. Constructors don't have any return type not even void
  4. Constructors have the same name as the class
  5. We can't call the constructor explicitly

Example

this is an example for creating the object Player in the dreidel program

public class Player {
    private int gelt;
    private String name;

    public Player(String n, int g){ //constructor method
        name = n;
        gelt = g;
    }

Return type

Methods must declare the type of value that they will return if they return one. The type goes immediately before the method name. If the method does not return a value then it declares itself as void instead.

public int methodThatReturnsAnInt() {
    return 13;
}
 
public void methodThatDoesntReturnValue(){
    return;
}

Argument List (Parameters)

A method can take in zero or more variables. If a method takes in more than one variable they need to be separated by commas.

public int methodThatTakesInVariables(int x, int y, int[] z) {
    return 13;
}

Calling a method

To run a method, you call it from another method and pass it its arguments as follows:

methodThatTakesAnInt(13);

Pass-By-Value

Java variables are exclusively pass-by-value, which means that a copy of the variable, not the variable itself, is passed to the method.

Primitive Types

When dealing with primitive types this means that the value in the calling method will not change no matter what happens in the called method. Take this example, which attempts to take variable a, pass it through method meth, and print it out:

public static void main (String[] args) {
  int a = 0;
  meth(a);
  System.out.print(a);
}
public static void meth(int a) {
  a++;
}

The printed value will be no matter what happens in meth. This occurs because meth is changing its own copy of a, not the one from the main method.

In order to change the value in main you would have to return a value from meth like this:

public static void main (String[] args) {
  int a;
  a = meth(a);
  System.out.print(a);
}
public static int meth(int a) {
  a++;
  return a;
}

Non-Primitive References

Pass-by-value works very differently when dealing with objects. When, in java code, a non-primitive type is assigned to a value, the variable being used does not represent the actual value that it has been set to, but rather it represents a reference that refers to that value.

public static void main (String[] args){
    Fraction x = new Fraction (1,2);
    change(x);
    System.out.print(x);
}
 
public static void change(Fraction y){
    y = (2,1);
}

This will print out 2/1. When Farction x is created in the main method it creates a reference (let's call it 123) to a value of 1/2. Then when Fraction x gets passed to the change method Fraction y is created as a copy, not of the value 1/2, but of the reference 123. Since these references are the same they both correspond to the same Fraction value of 1/2. When Fraction y is changed in the change method both x and y change because they are both references to the same value.

Visual References

untitled.bmp

The picture shows that when the value of 123 changes every 123 reference that exists changes as well.

Immutable objects

Some objects such as String and Integer are immutable. This means that they will behave much like a primitive type when it comes to pass-by-value.

public static void main(String[] args){
     String s = "whatever";
     change(s);
     System.out.print(s);
}
 
public static void change(String u){
     u = "ouch!";
}

This will return "whatever". Because String is immutable, when String s is passed to the change method and is then changed from "whatever" to "ouch!" an intirely new object, referenced by u, is made.

Method Overloading

Method overloading is when there are more than one method with the same name in the program. This is only allowed when the methods do not have the same signature (that do not take in the same types of variables in the same order).

Correct Overloading

public static int find(int[] x) {
  int max = x[0];
  for (int i = 1; i < x.length; i++)
    if (x[i] > max) {
      max = x[i];
    }
  }
  return max;
}
 
public static int find(int[] x, int number) {
  for (int i = 0; i < x.length; i++) {
    if (x[i] == number) {
      return number;
    }
  }
}

The code above is correct because one of the methods is taking in 1 type, and the other is taking in 2. So when we call the method, the program knows which one to use depending on whether there are 1 or 2 types. In this case, the maximum of the array will be printed out (6).

Another good example of Correct Overloading can be seen in the Fraction class.

public class Fraction{
     public Fraction addition(Fraction x){
            if(x.denominator == denominator){
                return new Fraction(numerator + x.numerator, x.denominator).reduce();
            }
            else{
                return new Fraction((numerator * x.denominator) + (x.numerator * denominator),
                        x.denominator* denominator).reduce();
            }
        }
    public Fraction addition(int y){
        Fraction x = new Fraction(y, 1);
        if(x.denominator == denominator){
                return new Fraction(numerator + x.numerator, x.denominator).reduce();
            }
            else{
                return new Fraction((numerator * x.denominator) + (x.numerator * denominator),
                        x.denominator* denominator).reduce();
            }
    }
}

Both of these methods show addition of a fraction, but one is added to another fraction, and one is added to an integer. This is advantageous because it allows someone to pass a different type to the addition method, but it still is doing correct addition. These methods take in different types, which is a correct usage of method overloading.

Incorrect Overloading

public static int find(int[] x) {
  int max = x[0];
  for (int i = 1; i < x.length; i++)
    if (x[i] > max) {
      max = x[i];
    }
  }
  return max;
}
 
public static int find(int[] x) {
  int min = x[0];
  for (int i = 1; i < x.length; i++) {
    if (x[i] < min) {
      min = x[i];
    }
  }
  return min;
}

In this case, the main method does not know which method to call since both of them take in only 1 array. This will cause a compile-time error.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License