next up previous
Next: Example: use of static Up: Unit 03 Previous: Result of a method:

Example: use of static methods defined in the same class

The following program shows the use of static methods defined in the same class.

import javax.swing.JOptionPane;

public class Program1 {

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

  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("!");
  }

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

  public static String personalGreeting(String firstName, String lastName) {
    return "Good morning " + firstName + " " + lastName + "!";
  }

  public static void main(String[] args) {
    printGreeting();
    String fn = JOptionPane.showInputDialog("First name");
    String ln = JOptionPane.showInputDialog("Last name");
    printPersonalGreeting(fn,ln);
    printInformalGreeting(fn);
    JOptionPane.showMessageDialog(null,personalGreeting(fn,ln));
    System.exit(0);
  }
}

Note: The static methods defined in the class Program1 are called by the main method of Program1 without preceding them by the name of the class. This is possible since the method belongs to the same class as main.


next up previous
Next: Example: use of static Up: Unit 03 Previous: Result of a method: