Methods one more time


Note: A method is the object oriented word to describe a function, so I use the words function and method interchangeably.

You already know, there are various data types in Java.

Look at the picture above.

That’s what you have:

  • access level modifier
  • data type
  • method name
  • method arguments with data type before
    (int summand1, int summand2)
  • keyword

In the line

return summand1+summand2;

after the keyword return, you have the actual calculation. It is the result of the function.

What is important, your result must be the same data type as specified in
method declaration, i.e.:

public int power(int base, int exponent) {
    int power = 1;
    return power;

The methods in class Calculator were supposed to do only simple calculations.

When you create a method you state what a method can use (what arguments) to give you a result (you have it after return keyword).
In other words: inside the method you use arguments. You do whatever you want with the arguments to get the result you need.

Here is how the more complicated function may look like:

public int power(int base, int exponent) {
    int power = 1;
    int i = 0;
    while(i< exponent) {
    return power;

What happens inside:

public int power(int base, int exponent) { //declare method
    int power = 1;          //declare and initialiaze variable power
    int i = 0;              //declare and initialiaze variable i
    while(i<exponent) {    //start loop and add a condition
        power=power*base;  //calculate power for given iteration
        i=i+1;             //increase iteration number by 1
    return power;         //return the result of calculation: power

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s