Download presentation
Presentation is loading. Please wait.
1
Introduction to Methods in java
Unit 3 - Methods Introduction to Methods in java
2
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
3
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();
4
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> }
5
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; }
6
Using a Method To use a method, simply write its name within your main() code. public static void main (String[] args) { getNumber(); }
7
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.
8
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(); }
9
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. }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.