Introduction to Methods in java Unit 3 - Methods Introduction to Methods in java
What is a method? A method is a block of code that can be re-used (called) over and over whenever we want. The benefit is that you can reuse methods in different programs. This is especially useful for making our programs smaller and modular
Sample – Reusable Code // Create a Scanner to retrieve input. Scanner sc = new Scanner (System.in); // Request input from the user. System.out.print(“Please enter an integer: “); int num = sc.nextInt();
Creating a Method Methods require three things: 1) A unique name (similar to a variable) 2) A return type (if applicable – void if none) 3) A body of code (possibly with a return type) SYNTAX: public static <return type> <method name> () { <body of code> }
Example: Retrieving a number public static int getNumber () { // Create a Scanner to retrieve input. Scanner sc = new Scanner (System.in); // Request input from the user. System.out.print(“Please enter an integer: “); int num = sc.nextInt(); // Return the int value to the calling. return num; }
Using a Method To use a method, simply write its name within your main() code. public static void main (String[] args) { getNumber(); }
Using a Method To use a method, simply write its name within your main() code. public static void main (String[] args) { getNumber(); } PROBLEM: The main method isn’t doing anything with the integer that getNumber() returns.
Using a Method To use a method, simply write its name within your main() code. public static void main (String[] args) { // Solution: Save its returned value in a variable! int userNumber = getNumber(); }
Void Methods A method with a return type of void doesn’t return anything. It simply does stuff. public static void greetUser () { // Say hello and ask for their name. Scanner sc = new Scanner(System.in); System.out.print(“Hey there, what’s your name?”); String name = sc.next(); System.out.println(“Nice to meet you, “ + name); // No return statement needed. }