Methods

Definition

A method (sometimes called a procedure or a subroutine) is a set of statements that perform a well-defined singular task. The use of methods has several advantages:

  • A method can be reused in other programs. A set of methods can be stored in a program library and can be integrated in a new development when needed;
  • The use of methods will enhance the readability of a program: a (long) set of statements can be replaced by one method call;
  • Debugging becomes easier: a programmer does not have to spend a lot of time to debug again a well-tested and error-free method. 

Java Predefined Methods

Predefined methods are available in numerous Java packages. Examples of Java packages are java.io, java.lang, java.util… A package contains several classes and each class defines several methods. For example, the package java.lang contains two important classes: Math and String

Math Class

The following table lists some important methods from the Math class:

MethodDescriptionArgumentsReturn
abs(x)Absolute value of xint, long, float, doubleint, long, float, double
ceil(x)Smallest integer value greater than or equal to xdoubledouble
floor(x)Largest integer value that is less than or equal to xdoubledouble
max(x,y)Returns the greater of the two values (x and y have the same data type)int, long, float, doubleint, long, float, double
min(x,y)Returns the smaller of the two values (x and y have the same data type)int, long, float, doubleint, long, float, double
pow(x,y)Power (xy)x and y must be doubledouble
random()Random number greater than or equal to 0.0 and less than 1.0No argumentsdouble
round(x)integer or long closest to xfloat, doubleint, long
sqrt(x)Square root of xdoubledouble
Math Class

The column Arguments shows the data types (x and y) needed by the method when the method is called. The column Return shows the data type of the result sent by the predefined method to the calling statement.

To use a method from a predefined class the programmer has to import the class or the method from the package. This can be done as follows:

Import all methods of a class:

import static packagename.classname.*;

import one method of a class: 

import static packagename.classname.methodname;

The above methods are used in the following program:

//MathMethods
//Carlos De Backer
import static java.lang.Math.*;
public class MathMethods{
   public static void main(String[] args){
      System.out.println("abs(-100.5) = " + abs(-100.5));
      System.out.println("ceil(101.5) = " + ceil(101.5));
      System.out.println("floor(-101.5) = " + floor(-101.5));
      System.out.println("max(200,300) = " + max(200,300));
      System.out.println("min(200.45,200.44) = " + min(200.45,200.44));
      System.out.println("pow(2.0,3.0) = "+ pow(2.0,3.0));
      System.out.println("random() = "+ random());
      System.out.println("round(50.25) = "+ round(50.25));
      System.out.println("sqrt(49.0) = " + sqrt(49.0));
   }
}
abs(-100.5) = 100.5
ceil(101.5) = 102.0
floor(-101.5) = -102.0
max(200,300) = 300
min(200.45,200.44) = 200.44
pow(2.0,3.0) = 8.0
random() = 0.0952228904917185
round(50.25) = 50
sqrt(49.0) = 7.0

String Class

A String is a sequence of characters. In Java a string is a non-primitive data type because it is implemented as an object (an instance) from the class String. String literals must be enclosed in double quotes.

In Java a String object can be created in the following way:

String firstName = "Napoleon ";

firstName is the name of the object and the object is initialised with the name “Napoleon “.

Strings can not be changed after they have been created.

The class String provides a lot of useful methods:

MethodDescriptionArgumentsReturn
charAt(i)Returns the character on position i of the specified string. The first character is located on position 0. intchar
concat(s)Adds the string s at the end of the specified string. StringString
equals(s)Compares the string s with the specified string.Stringboolean
length()Returns the length of the specified string.int
replace(a,b)Replaces all occurrences of character a in the specified string with character b.charString
substring(i,j)Returns a string starting from position i through position j from the specified string.intString
String methods

+ Operator

Strings can also be concatenated using the + operator instead of the concat() method.

String name = "Napoleon " + "Bonaparte";
Non-string operands will first be converted to strings before concatenation with the + operator:
String yearOfDeath = "Napoleon " + "Bonaparte " + "died: " + 1821;

Some String methods are used in the following program:

//StringMethods
//Carlos De Backer
import static java.lang.String.*;
public class StringMethods{
   public static void main(String[] args){
      String firstName = "Napoleon ";
      String lastName = "Bonaparte";
      System.out.println("firstName.charAt(5) = "+firstName.charAt(5));
      System.out.println("firstName.concat(lastName) = "+firstName.concat(lastName));
      System.out.println("firstName.equals(Bonaparte) = "+firstName.equals("Bonaparte"));
      System.out.println("lastName.length() = "+ lastName.length());
      System.out.println("lastName.replace('e','a') = "+ lastName.replace('e','a'));
      System.out.println("lastName.substring(0,3) = "+ lastName.substring(0,3));
      System.out.println("firstName + lastName + died + 1821 = " + firstName + lastName + " died "+ 1821);
   }
}
firstName.charAt(5) = e
firstName.concat(lastName) = Napoleon Bonaparte
firstName.equals(Bonaparte) = false
lastName.length() = 9
lastName.replace('e','a') = Bonaparta
lastName.substring(0,3) = Bon
firstName + lastName + died + 1821 = Napoleon Bonaparte died 1821

User-Defined Methods

Define a User-Defined Method

A method is part of a class. A user-defined method can be defined in a class as follows:

modifiers returndatatype methodname(parameters){
   code to be executed
}

Modifiers

There are two groups of modifiers: visibility modifiers and non-visibility modifiers. The most commonly used visibility modifiers are:

ModifierDescription
publicThe method is also accessible from outside the class.
privateThe method is only accessible from inside the class.
Visibility modifiers

The most commonly used non-visibility modifiers are:

ModifierDescription
finalA final method cannot be modified.
staticA static method can be called without creating an object of the class (e.g. the methods defined in the class Math are static methods).
Non-visibility modifiers

Visibility and non-visibility modifiers are separated by spaces (e.g. public static)

Return Data Type

The return data type is the data type (byte, short, int, long, float, double…) of the value returned (return statement) by the method. When the method doesn’t return a value the return data type is replaced by the keyword void.

Parameters

The list of parameters is a list of variables with their data type. The elements in the list are separated by a comma. These variables will receive data from the calling method and will be used in the called method.

Example:

private static float calculateAverage (int score1, int score2);

Declaration of the main() method

These rules can be applied to our well-known  public static void main(String[] args) method definition:

  • public static: the method main() is accessible from outside the class and can also be used without creating an object.
  • void: the method main() will not have a return statement.
  • String[] args: the variable args has the data type String. The square brackets refer to an array of strings. Arrays will be covered in a later chapter.

Call a User-Defined Method

A user-defined method can be called by:

A user-defined method with a return statement:

variable = methodname(arguments);

A user-defined method without a return statement (void):

methodname(arguments);

The parameters declared in the method definition are replaced with the values (arguments) supplied when calling the method. The argument list can stay empty when no parameters have been declared. 

Example: 

average = calculateAverage(17,12);

The way data is passed between the calling statement and the called method is illustrated in the following image:

Data between calling and called method

The Java program to calculate the average of two integer numbers can now be developed as follows:

//Average of two numbers
//Carlos De Backer
public class Average{

   public static void main(String[] args){
      float average;
      
       average = calculateAverage(17,12);
       printAverage(average);
      
       average = calculateAverage(5,18);
       printAverage(average);
      
   }
   
   private static float calculateAverage(int score1, int score2){
       float result;
       result = (score1 + score2)/(float)2.0;
      return(result);
   }
   
   private static void printAverage(float average){
       System.out.println("The average is: "+average);
      
   }
}
The average is: 14.5
The average is: 11.5