Programming Basics 3 – Methods


In the last part of the series you learned how to use variables to store data in a program. This part will discuss methods, which give you the possibility to define behavior for a class.

Solution to the last exercise

The exercise was:

Now play around with the inputs and create a simple calculator! Make the user input two floating point numbers after each other, add them together, cast the result to an integer and print out the result!

I’ve come up with the simplest possible solution I could think of, it just uses variables and no custom methods, as we’ll discuss them in this part:

import javax.swing.JOptionPane;

public class Calc
    public static void main(String[] args)
        float number1 = Float.parseFloat(JOptionPane.showInputDialog(null, "Enter a number:"));
        float number2 = Float.parseFloat(JOptionPane.showInputDialog(null, "Enter another number:"));
        int result = (int) (number1 + number2);

        JOptionPane.showMessageDialog(null, result);

Note that I’ve used the nicer looking GUI inputs and outputs instead of the console IO. You may as well use the console IO. The result looks like this:

Figure 1: Solution to the last homework


You’ve already seen some methods in this series and you might even have already written some yourself, even though you didn’t exactly knew what was going on. So in general a method declaration consists of the following elements:

  • access modifier
    We discussed this one earlier. It does absolutely the same thing as for variables: It limits access to the method, so that other classes can’t call this Method. You’ll see how useful this is, when we get into the object oriented parts later in this series.
  • return type
    This determines what type the value has, that is returned by a method. Basically a method is a set of instructions grouped together. And this set of instructions might as well be a complex mathematical function that has a solution. Of course you’d like to give this result back to who ever called the method. The return type can be any primitive data type or object. If a method doesn’t return anything, you must use the return type ‘void’
  • name
    The method’s name. Other than variables this is not necessarily unique. Methods can have any name you can image, however in java they should start with a lower case character. There might be two methods with the same name, but other signatures. Don’t worry, I’ll explain a method’s signature in a second.
  • parameter list
    These are the values you pass into a method. These values might be needed by the method to calculate something. These are variables that are only valid inside the specific method, they are declared for. If you don’t want to pass any parameters, leave the parameter list empty.
  • Exception List
    We’ll discuss this one later.
  • Method body
    This is the actual part of the method, that does the work. It is the part between the curly brackets.

Here are some example method declarations:

public int getAdditionResult(int number1, int number2) { ... }
private String addStrings(String name, float size, int age) { ... }
public static void main(String[] args) { ... }
protected void doSomething(){ ... }

I’ve talked about a method’s signature above. The signature consists of the the name and the data types of the parameter list of a method (the parameter’s names don’t matter, however you have to use different names for parameters in one list). It is allowed to have several methods with the same name, but not with the same signature. You might ask yourself what it is good for to have two methods with the same name. This will get more important later, but I can show you an example for now:

public int getAdditionResult(int number1, int number2) { ... }
public int getAdditionResult(float number1, float number2) { ... }

As you can see, this is useful if you have the same functionality for different data types. However you’ll lern an even better way to do this later in this series, as this topic is too advanced for now.

Parameters and return values

Like I said above, parameters are variables that are valid only inside a method’s body:

public int getAdditionResult(int number1, int number2)
    // You can use number1 and number2 in here
    int number3 = number1 + number2;

As stated above, you can return a value from a method, but you have to declare the type, the value returned, will have:

public int getAdditionResult(int number1, int number2)
    // You can use number1 and number2 in here
    int number3 = number1 + number2;

    return number3;

The return statement marks the last line of a method. Anything written after it, will not be executed. When returning a value from a method, you can save the value you just calculated. Otherwise it will be lost, because you can’t access it outside the method:

// result will be 1337, as the method returns this value
int result = getAdditionResult(1300, 37);

Calling a method

If you followed this tutorial, you have already invoked(called) a lot of methods. If you call a method, you have to provide the values, declared as the method’s parameters (See the example above).

By calling a method, you make it do whatever is supposed to do. When a method finished it’s work, you get a return value, if there is one. You can use this value, but it’s not mandatory, you might also just call the method without using it’s return value.

A special case

Look at the following code. Can you see the problem here?

public class VariableTest
    static int x = 1000;

    public static void printX(int x)
        x = 9999;


    public static void main(String[] args)

As you can see, we have a variable x declared in the class itself (it is a global or class variable), then there is the printX method, which also has an integer named x in it’s parameter list. As I’ve stated in the last part of the series, two variables may not have the same name. However the two variables are not declared in the same scope. The method’s integer x is only valid inside the method. You can not modify or read it outside the method, however you can use the global x variable inside the method (I’ll show you later in this series).

This is pretty tricky, isn’t it? What x will be modified and what will be printed to the console?


Answer the following questions!

  1. What will be printed to the console when you call printX?
  2. Which x will be altered? The global one or the method’s one?
  3. What happens if you print out x in the main method (with the println-method)?

Table of contents

Part 1 – MyFirstProgram
Part 2 – Access Modifiers and Variables
Part 3 – Methods (You are here)
Part 4 – Arrays
Part 5 – Control flow
Part 6 – Classes and Objects
Part 7 – Exceptions and exception handling

Addendum 1 – IntelliJ QuickTip
Addendum 2 – Important programming concepts explained


11 thoughts on “Programming Basics 3 – Methods

Leave your two cents, comment here!

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

You are commenting using your 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.