Tutorial04 - 10 11 12 public static int sum(int a, int b,...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Tutorial #4: Methods O P T I O N A L Introduction: This tutorial is recommended if you have limited experience using methods. 1. Enter the following program and execute it. It should display the sum of 1 + 2 + 3 which is 6. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import java.util.Scanner; public class Tutorial04 { public static void main(String[] args) { int num; num = sum(1, 2, 3); System.out.println(num); } public static int sum(int a, int b, int c) { int sum; sum = a + b + c; return sum; } } 2. A method is a “subprogram” that is executed when it is called, aftewhich the main program can continue running. Use the debugger (see Tutorial #3) to step through the program. Set a breakpoint at line 6 and click on “Step into” until you reach line 8. After you reach line 8, you can click on “Resume” to quit. 3. The return statement in line 13 is critical for sending data back to the main method. Any valid expression can be used after the keyword “return”. Change the sum() method as follows to see this.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 10 11 12 public static int sum(int a, int b, int c) { return a + b + c; } 4. If a method does not return any data, its return type must be void . Modify your program as shown below to use an additional method that prints the sum but does not return anything. Changes are shown in bold . 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import java.util.Scanner; public class Tutorial04 { public static void main(String args) { int num; num = sum(1, 2, 3); printSum(num); } public static int sum(int a, int b, int c) { int sum; sum = a + b + c; return sum; } public static void printSum(int sum) { System.out.println("The sum is " + sum + "."); } } 5. To observe the program flow, use the debugger to step through the program. Set a breakpoint at line 6 and click on Step into until you reach line 8. After you reach line 8, you can click on Resume to quit....
View Full Document

Page1 / 2

Tutorial04 - 10 11 12 public static int sum(int a, int b,...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online