Java-Functions-Emoon
Java-Functions-Emoon
text I/O
2
Functions (Static methods)
Applications function f
• Scientists use mathematical functions to calculate formulas.
• Programmers use functions to build modular programs.
• You use functions for both.
output f (x)
Examples seen so far
• Built-in functions: Math.random(), Math.sqrt(), Math.abs(), Integer.parseInt().
• User-defined functions: main().
• A static method is associated with the class itself, not with a particular instance of the
class.
3
input x
function f
output f (x)
The method signature comprises the method’s name and the parameter types.
5
public static void main(String[] args) { The scope of arg and value.
Scanner input = new Scanner(System.in);
This code cannot refer to n or sum.
while(input.hasNextInt()) {{
while(input.hasNextInt())
int =arg
int arg = input.nextInt();
input.nextInt(); Best practice.
double
valuevalue = harmonic(arg);
double = harmonic(arg);
System.out.println(value);
Declare variables
System.out.println(value);
} } so as to limit their scope. 8
System.out.print("Terminate the program.");
}
Robert
} Sedgewick | Kevin Wayne
Why define static methods?
When you write an essay, you break it up into paragraphs;
When you write a program, you will break it up into methods.
Bottom line:
Whenever you can clearly separate tasks within programs,
you should do so.
Answer.
The best way to answer a question like this is to try it yourself
and see what happens. Here is the result of omitting the static
modifier from harmonic() in Harmonic.java:
Main.java:23: error: non-static method harmonic(int) cannot be referenced from a static context
double value = harmonic(arg);
^
1 error
Error: Could not find or load main class elice.Main
11
13
14
15
17
19
A. Works fine.
public class CubicPQ {
public static int cube(int i){
Preferred (compact) code.
return i * i * i;
}
5
public static void main(String[] args){ 1 1
Scanner input = new Scanner(System.in); 2 8
int N = input.nextInt(); 3 27
for (int i = 1; i <= N; i++) 4 64
System.out.println(i + " " + cube(i)); 5 125
}
}
20
Answer.
If the return type is void, there is no problem. In this case, control will
return to the caller after the last statement.
If the return type is not void, Java will report a missing return statement
compile-time error if there is any path through the code that does not
end in a return statement.
Q. Can I return from a void function by using return? If so, which return
value should I use?