|
Java program that compute the sums of the numbers 1 to 10 and the numbers 23 to 36
public class Sum
{
public static void main(String[] args)
{
int i, sum;
sum = 0;
for ( i = 1; i <= 10; i++ ) // Sum numbers from 1 - 10
sum += i;
System.out.println(sum);
sum = 0;
for ( i = 23; i <= 36; i++ ) // Sum numbers from 23 - 36
sum += i;
System.out.println(sum);
}
}
|
DEMO: demo/06-methods/01-intro/Sum.java
Better solution: define a method once and invoke (= run) the method multiple times !
|
|
DEMO: demo/06-methods/01-intro/SumMethod.java
Example: a Java program with a method definition and two method invocations:
public class SumMethod { // Method definition< public static int sum(int a, int b) { int i, result = 0; for (i = a; i <= b; i++) result += i; return result; } public static void main(String[] args) { int s1, s2; s1 = SumMethod.sum(1,10); // Method invocation s2 = SumMethod.sum(23,36); // Method invocation } } |
Notice: You can define a method (= code) just once and invoke (= run) the method (code) multiple times
When you invoke a method from inside the same class, we can omit the class name:
public class SumMethod { // Method definition< public static int sum(int a, int b) { int i, result = 0; for (i = a; i <= b; i++) result += i; return result; } public static void main(String[] args) { int s1, s2; s1 = SumMethid.sum(1,10); // This is the official syntax s2 = sum(23,36); // Classname optional if invoked in same class } } |
(Because Java will add the classname (= " SumMethod) to the method call by default).
You can also save your methods in a dedicated class (with a meaningful class name):
| The Tools class containing useful methods | Java program that uses the method(s) |
|---|---|
public class Tools { public static int sum(int a, int b) { int i, result = 0; for (i = a; i <= b; i++) result += i; return result; } } |
public class UseTools
{
public static void main(String[] args)
{
int s1, s2;
s1 = Tools.sum(1,10);
s2 = Tools.sum(23,36);
}
}
|
You must use the classname Tools. before a method to invoke methods that are defined in a different class
Note: this is how Java provides the Mathematical functions to you, such as Math.pow( )
DEMO: demo/06-methods/01-intro/Tools.java and UseTools.java