Comp 110 Method Calling

Method Calling

Method calling is the way to send messages in Java. Method calling is similar to telling someone, something, or yourself to do something in real life. In lecture we demonstrated method calling by telling the robot BB-8 where we want it to move. If we were to tell BB-8 to move forward 2 steps in real life we would probably say something like "yo bb8 please move forward 2 steps". Unfortunately when using Java to communicate we can't be that straight forward, so if we were to tell BB-8 to move forward to steps in Java we would have to type bb8.moveForward(2). This Java statement can be translated directly back into english and vice-versa. "bb8" in the Java statement is the subject in which we are communicating with. The moveForward(2) in the Java statement is what we are requesting the subject (bb8) to do. moveForward is the method that we are calling on the subject/object bb8. 

Essentially, the computer leaves your code in the main method and takes a journey to some "far off" place to get or change some information. This far off place is another method, still on your computer, just not visible in main. After it's done there, it comes back to your code right where it left off, usually with some more data and continues on. Business as usual.

Method Calling Syntax:

  •  Method calls in Java have parenthesis after method’s name
  •  Extra pieces of information needed by a method receiver are called parameters; the values given by the  caller are called arguments
  •  Example -- bb8.moveForward(2); --> Here 2 is the parameter and moveForward is the method name

Here's another simple example:

public void main (String [] args) {
     int example = 5;
     int examplePlusOne = addOne(example);
     System.out.println(examplePlusOne);
}

public static int addOne (int n){
     return n + 1; 
}

What does the above code print out? It's simple enough - a 6.

You can see how in my main method I declared a variable called example with the value of 5. If the computer is walking through the code, in the next line you will see it make another variable called examplePlusOne. It then sees that method call, jumps out of main and into addOne, where it took the integer value (example) and returned that value plus one. Now examplePlusOne is equal to six.