Select Page

Welcome to “Java Diaries” a series in which I document my self-teaching of Java as both a record of what I’ve done and a reference for me to check back on later – hopefully aiding the information I’ve been consuming to sink in. Click here to view all posts in this series.

A method is a collection of statements that perform some specific task and return result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. – GeeksForGeeks.com

So far in Java if I have wanted to perform a function with a different set of parameters I would have had to copy and paste code, which obviously works, but for example if I needed to update the function of the code I would have to replace all instances of the code which is time-consuming and could lead to a mistake causing bugs further down the line. Methods solve this problem, allowing you to reuse code but only needing to change it once if you want to update all instances of the function. Take this simple piece of code:

int myInt1 = 1;
int myInt2 = 2;
int result = myInt1 + myInt2;

System.out.println("The result is " + result);

myInt1 = 3;
myInt2 = 4;
int result = myInt1 + myInt2;

System.out.println("The result is " + result);

myInt1 = 5;
myInt2 = 6;
result = myInt1 + myInt2;

System.out.println("The result is " + result);

Here I have copied and pasted the same code three times, each time changing the values so the calculation is different. But what if for example, I decided I needed the result to actually be “myInt1 / myInt2” or “myInt1 % myInt2“. In that case I would need to update all three instances of the code, but with methods, this is avoided altogether.

package com.danpos;

public class Main {

    public static void main(String[] args) {
  // write your code here
    }
}

When opening up a new project in IntelliJ we have had a method defined by default, this is called the main method and this is where the main code of the program goes. To create a new method you need to add this below the main method as you can’t have a method inside a method. In the code above, you will see two lines:

  • public class Main { }
  • public static void main (String[] args) { }

We haven’t covered Class yet in the Udemy course I am following with so the line which is the method here is “public static void main (String[] args) { }.”

Tip: You can type “psvm” and hit Enter inside IntelliJ and it will automatically type this class for you.

Keeping in mind that you can’t have a method inside a method we need to create our next method following the final “}” of the main method, but before the final “}” of the Main class.

package com.danpos;

public class Main {

    public static void main(String[] args) {
  // write your code here
    }
    
    public static void myCalculation () {
        
    }
    
}

You will now notice we have “public static void calculation { }”. Public, static, and void, are all keywords and myCalculation is the method name. We can pass information (also known as arguments) to methods, from within the main method – but first, we have to define what information (also known as parameters) our new method will hold. We define the parameters the same way we declare variables, except this time we do it inside the “( )” of the method.

public static void myCalculation (int myInt1, int myInt2) {

}

Now we have our myCalculation method we need to be able to call this in our main method which is very simple to do. You just type the methods name followed by “( )” and then inside the brackets you type in the values, or arguments, that correspond to the parameters set for the method. Sticking with our example above:

In the main method we have called myCalculation and passed it the arguments “3” and “4”. These match up directly with the parameters we set when we first defined myCalculation. Using the arguments in the picture we slot the number 3 into the variableint myInt1″ and the number 4 goes into “int myInt2″.

Here it is in actual code terms:

package com.danpos;

public class Main {

    public static void main(String[] args) {
  myCalculation(3, 4);
    }

    public static void myCalculation (int myInt1, int myInt2) {

    }

}
IntelliJ Method Feature

If you start calling your method in IntelliJ it will show you what parameters you need to fill in, and which order they are in.

Once you have your arguments, the code inside your method runs. Currently, we have no code inside our method, so let’s take our addition calculation which we coded originally at the start and make it run from within our myCalculation method.

package com.danpos;

public class Main {

    public static void main(String[] args) {
        
  myCalculation(3, 4);
  
    
    }

    public static void myCalculation (int myInt1, int myInt2) {

        int result = myInt1 + myInt2;

        System.out.println("The result is " + result);
        
    }

}

You can see that we now have our result int inside the myCalculation method and result is myInt1 + myInt2. Because we have myCalculation (3, 4); in our main method when we run this program 3 and 4 will be dropped into myInt1 and myInt2 respectively, then added together and stored in result. The system will then print “The result is 7”.

The result is 7 – who knew!?

We can repeat this process over and over again and keep feeding it different arguments and the method will just run over and over again displaying the correct answer.

package com.danpos;

public class Main {

    public static void main(String[] args) {

      myCalculation(3, 4);
      myCalculation(20, 50);
      myCalculation(1, 9876);
      myCalculation(3847387, 39839474);

    }

    public static void myCalculation (int myInt1, int myInt2) {

        int result = myInt1 + myInt2;

        System.out.println("The result is " + result);

    }

}

We can use myCalculation multiple times and just change the argument values.

If we wanted to change our calculation above to become a multiplication it is as simple now as changing the to a in the myCalculation method the once, instead of multiple times.

A method is just a chunk of code that does a particular job. But methods are set out in a certain way. You have a method header, and a method body. The header is where you tell Java what value type, if any, the method will return (an int value, a double value, a string value, etc). As well as the return type, you need a name for your method, which also goes in the header. You can pass values over to your methods, and these go between a pair of round brackets. The method body is where you code goes.– HomeAndLearn.co.uk

Using methods you can also return values. So far in our code we have been typing the keywords “public static void”. Void in this instance means no value is returned (it’s void of any value), you can however substitute the word void for a data type such as int, boolean, string, etc.

We’ll use an int as an example, typing “public static int calculateLeaderboardPosition“. We have defined a method/variable hybrid here (this is not official terminology just my way of thinking about it)

  •  public static int calculateLeaderboardPosition

If we strike through the public static piece of code, can you see how this looks very similar to how we would normally declare an int with the name of calculateLeaderboardPosition?

Let’s break down the following code:

package com.danpos;

public class Main {

    public static void main(String[] args) {


       int finalPosition = calculateleaderboardPosition(9000);
        System.out.println("Your leaderboard position is " + finalPosition);

    }

    public static int calculateLeaderboardPosition (int finalScore) {

        int position = 4;

        if (finalScore >= 1000) {
            position = 1;
        } else if (finalScore >= 500) {
            position = 2;
        } else if (finalScore >= 100) {
            position = 3;
        }

        return position;
        }

}

The concept of returning values was hard to wrap my head around at first but I now get it (I hope!?).

  1. In the above code in the main method I have an int named finalPosition and I have set this value to equal = calculateLeaderboardPosition(9000);
  2. I then follow this with a System.out.println message saying “Your leaderboard position is…” with whatever the finalPosition int is equal to.
  3. Then in the calculateLeaderboardPosition method we have set a parameter of int and named this finalScore. The calculateLeaderboardPosition method has been set up as a public static int method.
  4. Inside the calculateLeaderboardPosition method we declare another int called position. We have set it’s value to 4, as an assumption that the default leaderboard position will be 4.
  5. Next is the if/else statement which changes the value of int position depending on the value of finalScore.
  6. From within the main method we pass the calculateLeaderboardPosition method an argument of 9000.
  7. The calculateLeaderboardPosition method then runs the if/else code to see what position 9000 falls into. In this case 9000 is Greater Than or Equal to (>=) 1000 so our int position is assigned a value of 1.
  8. Because the if/else statement has been satisfied, the next piece of code to run is return position; this assigns the current value of position (in our example position = 1) to our calculateLeaderboard int/method.
  9. Back in the main method we have our finalPosition int which we then make equal to the value of calculateLeaderboardPosition which because of the process in the previous step has a value of 1.
  10. The System.out.println code runs and “Your leaderboard position 1” would run.

My head hurts after writing that process out but hopefully you can follow along with it. I know I will be referring back to these notes when I need to remember exactly what the return function in Java does.

TIP: When using a data type method, such as public static boolean/int/string, you must return a value. If you have a void method then you do not need to return anything.

The title of this blog post is Method to the Madness which is not just a play on words.

After completing the method section of the Udemy course there was a series of interactive skill tests. The way these tests work is to present you with a challenge and you have to enter the Java code directly into your browser and then the browser checks whether your code was correct and if so you can move on to the next skill test. These tests included creating a leap year calculator and a test to see whether we should wake up if a dog was barking amongst others.

These challenges were quite tricky, as some involved working out calculations and my math skills aren’t the strongest unfortunately. But once I worked out the solution I had a sense of accomplishment and started to realise that there is indeed method to the madness of Java.

See you in the next one!

Next Post Button