JAVATM- The Beginnings
In the Hello World lesson we defined a method as a series of statements which are grouped together in order to perform a common task. All methods in Java are contained inside classes. The only method we have written so far in our classes is the main method. You can write other methods for your classes. This is useful to organize your work and avoid repeated operations.
Let’s say we needed to add and print the sum of several integers. As you can see, it’s easy to
make a mistake:
int a =1, b = 2, c = 3, d, e, f;
d = a + b;
System.out.println(“sum = “ + d);
e = a + c;
System.out.println(“sum = “ + e);
f = b - c; // Oops!
System.out.println(“sum = “ + f);
Since these statements repeatedly sum and print of numbers, it would make sense to write a method called sumAndPrint.
public static void sumAndPrint(int i1, int i2)
int sum = i1 + i2;
System.out.println(“sum = “ + sum);
This method consists of two statements: the expression which sums two numbers, and the statement which prints the sum. Both of these statements work to perform the task of sumAndPrint. We can call the method repeatedly to sum and print the numbers in our example. Note that the error we made in computing the sum of b and c disappears.
int a =1, b = 2, c = 3;
Copyright ©2017 by Ralph Lecessi Incorporated. All rights reserved.