next up previous
Next: Result of a method: Up: Unit 03 Previous: Definition of static methods

Examples of definitions of static methods

Example 1:

public static void printGreeting() {
  System.out.println("Good morning!");
}

The method printGreeting is a static public method that does not have formal parameters and does not return any result (see header). Its body is constituted by a single statement that prints the string "Good morning!"

Example 2:

public static void printPersonalGreeting(String firstName, String lastName) {
  System.out.print("Good morning ");
  System.out.print(firstName);
  System.out.print(" ");
  System.out.print(lastName);
  System.out.println("!");
}

The method printPersonalGreeting is a static public method that has two formal parameters firstName and lastName of type String and does not return any result (see header). Its body is constituted by a sequence of statements that print respectively the string "Good morning!", the value of the formal parameter firstName, a blank, the value of the formal parameter lastName, and finally the string "!".

Note that the formal parameters are used inside the body of the method exactly as already initialized local variables.

Example 3: Realize a static method printInformalGreeting that takes as input a string representing a name and prints the string "Ciao " followed by the name passed as a parameter and followed by the string "!".

Solution:

public static void printInformalGreeting (String name) {
  System.out.println("Ciao " + name + "!");
}


next up previous
Next: Result of a method: Up: Unit 03 Previous: Definition of static methods