Professional Documents
Culture Documents
User Defined Methods
User Defined Methods
1
User Defined Methods
Methods with no argument and no return value
A method that takes no arguments and returns
nothing is the simplest of all examples.
In this example the method called sayHello()
simply prints a message to the screen.
2
User Defined Methods
// A method with no arguments and no return value
import javax.swing.JOptionPane;
public class Methods1 {
// method definition
public static void sayHello() {
String output = "Hello";
// print message
JOptionPane.showMessageDialog(null, output, "Methods",
JOptionPane.INFORMATION_MESSAGE);
}
} // end class 3
User Defined Methods
Running the program only produces a window as
shown below, the important point is that a
method was called.
4
User Defined Methods
Methods with a return value but no argument
Let's look at another fairly simple method that
takes no arguments but this time a value is
returned.
5
User Defined Methods
// A method with no arguments and a return value
import javax.swing.JOptionPane;
public class Methods2 {
} //end class
7
User Defined Methods
Below is a sample of running the program
8
User Defined Methods
In this example the method takes one argument
but does not return a value.
9
User Defined Methods
// A method with one argument and no return value
import javax.swing.JOptionPane;
public class Methods3 {
public static void main( String args[]) {
String yourAgeString;
int yourAge;
// read in age
yourAgeString = JOptionPane.showInputDialog("please enter your age");
// convert string to integer
yourAge = Integer.parseInt(yourAgeString);
// call method
printAge(yourAge);
} // end main
10
User Defined Methods
// method definition
public static void printAge(int anAge) {
String output;
// print message
output = "You are " +anAge +" years old";
JOptionPane.showMessageDialog(null, output, "Methods",
JOptionPane.INFORMATION_MESSAGE);
} // end method
} // end class
11
User Defined Methods
Below is a sample of running the program
12
User Defined Methods
Notice that the list of arguments in the
method must contain the argument type
followed by the name
public static void printAge(int age);
13