First Steps in Java — Part 8

mike dietz
5 min readMay 6, 2020

--

Methods

Photo by Marcus Wallis on Unsplash

1: Setup | 2: Variables, Data Types and Sizes | 3: Get Some Input | 4: Operators | 5: Strings | 6: Conditionals | 7: Loops | 8: Methods | 9: Arrays

After talking about loops in our yesterday’s lesson, we move on to methods, the next big building block in Java.

Methods

A method in Java is basically a function.
In general, it is designed to take an input, perform an action on it and return an output. Of course, there are exceptions to this statement (there are functions that do not take any input or don’t return any output) but for now, while we are laying the foundation of our programming skills, we neglect these exceptions.

So, why are functions then called methods in Java?
A function that belongs to an object is called a method. While a function is independent of an object (it must be defined outside of a class), a method belongs to an object. Since Java is class-based and any code, including functions, has to be in the class body, the function belongs to the object that is instantiated from the class. Therefore, we call it a method and not a function.

In Java, functions are class members and called methods.

Similar to the class structure, a method has a method declaration and a method body.
The method declaration includes the access modifier, the returntype, and the signature, which is the method name and the parameter list.

  • Access modifier: defines from where the method can be called.
    public allows access from everywhere within the entire application.
    protected gives access to all sub-classes and the directory where the class is defined.
    package restricts access to the directory where the class is defined.
    private, can it only be accessed from within the class itself.
  • Returntype: the datatype of the return value must be specified in Java, i.e. byte, char, short, int, long, float, double, String, Array, etc. If the method does not return anything, the return type is void.
  • Methodname: Java’s naming convention suggests a verb as a method name, written in camelcase, i.e. first letter lowercase and any composed word parts capitalized.
  • Parameter list: contains the input parameters, preceded by their data type and separated by commas, and enclosed in parenthesis.
    Parameters can be of type primitive type data or reference type data. While the primitive type data is decoupled from the object that the parameter value provides once it is used as an argument. The reference type data stays connected to the object where the value comes from and will update the value there. This is useful for callback functions.
  • Signature: Java groups the method name and the parameter list together as the signature. This allows method overloading, which allows the creation of methods with the same name only differentiated by the parameter list.

The method body, enclosed in curly braces, includes the method’s code.

[method scope] [return type] [method name](parameters) {
// method body
return variables
}

Let’s create a few methods to get some practice. Create a file Methods.java.
Create the methods outside of the main() method and call them from within main(). Add the modifier static to the methods. We talk about static methods at the end of the article.

Add two numbers and compute the result

  • Create a public static method with the returntype String that requires three arguments of type integer: num1, num2 and guess.
  • Declare a variable result of type String.
  • Declare a variable sum of type int that holds the addition of num1 and num2.
  • Create an if-else statement that checks if the variables guess and sum are equal.
  • Create a text string for the if and the else block that you assign to the variable result.
  • Return the variable result.

public static String checkSum(int num1, int num2, int guess) {
String result;
int sum = num1 + num2;
if (guess == sum) {
result = “Correct! The sum of “ + num1 + “ and “ + num2 + “ equals “ + guess;
}
else {
result = “Wrong! The sum of “ + num1 + “ and “ + num2 + “ does not equal “ + guess + “. Please try again!”;
}
return result;
}

Print Words in Upper Case or Lower Case
If the number of letters in a word is odd, the word should be printed in lowercase. If the number of letters in a word is even, print it in upper case. Utilize the functions length(), toUpperCase() and toLowerCase().

  • Create a public static function of type String that requires an argument of type String. You will pass a word to the method.
  • Declare a variable of type String for the result.
  • Get the length of the string argument and store it in a variable stringLength of type integer.
  • Create an if-else statement that checks if the length of the string argument is even. Use the remainder operator for this purpose. If the remainder equals zero, the number is even.
  • For the if statement, apply the toUpperCase() function to the argument and assign it to the variable result.
  • For the else statement, apply the toLowerCase() function to the argument and assign it to the variable result.
  • Return the variable result.

public static String upperLower(String text) {
String result;

int stringLength = text.length();
if (stringLength % 2 == 0) {
result = text.toUpperCase();
}
else {
result = text.toLowerCase();
}
return result;
}

Special Methods

The constructor is a special method. It is called automatically when an object is instantiated. The constructor creates the object whenever the new keyword is used. Some rules apply for a constructor. Some, but not all, are listed here:

  • A constructor cannot have a returntype. It does not return any value.
  • A constructor must have the same name as the class.
  • Every class must have a constructor. A class can have multiple constructors due to constructor overloading.
  • If no constructor is defined, a default constructor is set, it is empty

Static Methods

A static method is a utility method that is available to all other classes without having to create an object first. A static method can be called without an object instance. It does not belong to a particular object, but instead, it belongs to the whole class. There are several rules that apply for static methods.
A static method:

  • can only access and modify static data members,
  • can only call a static method,
  • cannot use the keywords this or super.

The method main() is an example of a static method. It is called directly by calling the class. No object needs to be instantiated first for the method to be available.

Get the code for this lesson at GitHub.

In the next and final lesson, we will talk about Arrays.

--

--