Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Java-Functions-Emoon

KAIST Data Structure ppt

Uploaded by

[HA] Nights
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Java-Functions-Emoon

KAIST Data Structure ppt

Uploaded by

[HA] Nights
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Basic building blocks

• Built-in types of data


• Conditionals and loops
• Functions objects
• OOP functions
• Data Abstraction
conditionals and loops

text I/O

built-in data types assignment statements

Robert Sedgewick | Kevin Wayne


Building blocks of
Java
Functions
https://introcs.cs.princeton.edu/java/21function/

2
Functions (Static methods)

Java function ("aka static method") input x


• Takes zero or more input arguments.
• Returns zero or one output value.

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

Robert Sedgewick | Kevin Wayne


Terminology

input x

function f

output f (x)

𝑓 𝑥 = 1 + 𝑥 + 𝑥2 • The symbol 𝑥 is a placeholder for some input


value that will be substituted into the formula
to determine the output value.
• A particular, actual input value is an argument.

Robert Sedgewick | Kevin Wayne


Anatomy of a Java static method
To implement a function (static method)
•Access control modifiers—such as public and private
•Create a name.
•Declare type and name of parameter(s).
•Specify type for return value.

Method declaration param param
Implement body of method. type name
•Finish with return statement.

The method signature comprises the method’s name and the parameter types.
5

Robert Sedgewick | Kevin Wayne


Control flow : Harmonic.java
import java.util.Scanner; Even though harmonic( )
public class Harmonic {
appears first in the code, the
// returns 1/1 + 1/2 + 1/3 + ... + 1/n first statement that Java
public static double harmonic(int n) { executes is the first statement in
double sum
double sum == 0.0;
0.0; main().
for (int
fori (int
= 1; ii =<=1;n;i i++)
<= n;{ i++) {
sum += sum
1.0 +=
/ i; • Control transfers to the
1.0 / i;
} } function code.
return return
sum; sum; • Argument variables are
}
declared and initialized with
public static void main(String[] args) { the given values.
Scanner input = new Scanner(System.in); • Function code is executed.
while(input.hasNextInt()) {
• Control transfers back to the
int =arg
int arg = input.nextInt();
input.nextInt(); calling code (with return
double
double valuevalue = harmonic(arg);
= harmonic(arg); value).
System.out.println(value);
System.out.println(value);
} }
System.out.print("Terminate the program.");
} 6

Robert Sedgewick | Kevin Wayne


elice>Week 2-1> Harmonic numbers
Function call trace : Harmonic.java
import java.util.Scanner; This program clearly separates the
public class Harmonic {
two primary tasks performed by
// returns 1/1 + 1/2 + 1/3 + ... + 1/n the program:
public static double harmonic(int n) { • Calculating harmonic
double sum
double sum == 0.0;
0.0; numbers—Harmonic( )
for (int
fori (int
= 1; ii =<=1;n;i i++)
<= n;{ i++) {
sum += sum
1.0 +=
/ i; • Interacting with the user—
1.0 / i;
} } main( )
return return
sum; sum;
}
1
public static void main(String[] args) { 1.0
Scanner input = new Scanner(System.in); 2
1.5
while(input.hasNextInt()) {
int =arg
int arg = input.nextInt();
input.nextInt(); 4
double
double valuevalue = harmonic(arg);
= harmonic(arg); 2.083333333333333
System.out.println(value);
System.out.println(value); 10
} }
System.out.print("Terminate the program.");
2.9289682539682538
} q 7

} Terminate the program.


Robert Sedgewick | Kevin Wayne
Scope of variables
Def. The scope of a variable is the code that can refer to it by name.
import java.util.Scanner;
In Java,
public class Harmonic { a variable’s scope is the code
// returns 1/1 + 1/2 + 1/3 + ... + 1/n following its declaration, in
public static double harmonic(int n) {
the same block.
double sum
double sum == 0.0;
0.0;
for (int
fori (int
= 1; ii =<=1;n;i i++)
<= n;{ i++) {
sum += sum
1.0 +=
/ i;
1.0 / i; The scope of n and sum.
} } This code cannot refer to ag or value.
return return
sum; sum;
}

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.

Separating a larger task into smaller ones is much more important in


programming than in writing, because:
➢ It greatly facilitates debugging, maintenance, and reuse, which are
all critical in developing good software.

Bottom line:
Whenever you can clearly separate tasks within programs,
you should do so.

Robert Sedgewick | Kevin Wayne


Questions?
Q. What happens if I leave out the keyword static when defining
a static method?

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

➢ Non-static methods are different from static methods.


You will learn about the former in the next topic, OOP. 10

Robert Sedgewick | Kevin Wayne


Multiple arguments
Like a mathematical function, a Java
static method can take on more than
one argument, and therefore more
than one parameter variable.

public static double hypotenuse(double a, double b)


{ return Math.sqrt(a*a + b*b); }

More than one parameter variable

11

Robert Sedgewick | Kevin Wayne


Overloading
Using the same name for static methods public static int abs(int x)
whose signatures differ is known as {
overloading. if (x < 0) return -x;
else return x;
Overloaded methods are differentiated by }
different parameter lists—the number and the public static double abs(double x)
type of the arguments—passed into the {
method. if (x < 0.0) return -x;
else return x;
A common use of overloading: }
• We often define the same operation for
values of different numeric types, as in
the static methods for computing
absolute values.

• Java’s Math library uses this approach


to provide implementations of 12
Math.abs(), Math.min(), and Math.max()
for all primitive numeric types.
Robert Sedgewick | Kevin Wayne
https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Pop quiz 1a on functions
Q. What happens when you compile and run the following code?

public class PQfunctions1a


{
public static int cube(int i)
{
int j = i * i * i;
return j;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int N = input.nextInt();
for (int i = 1; i <= N; i++)
System.out.println(i + " " + cube(i));
}
}

13

Robert Sedgewick | Kevin Wayne


Pop quiz 1a on functions
Q. What happens when you compile and run the following code?

public class PQfunctions1a


{
A. Takes N from the computer keyboard,
public static int cube(int i)
then prints the cubes of integers from
{
1 to N
int j = i * i * i;
return j;
}
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
}
}

14

Robert Sedgewick | Kevin Wayne


Pop quiz 1b on functions
Q. What happens when you compile and run the following code?

public class PQfunctions1b


{
public static int cube(int i)
{
int i = i * i * i;
return i;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int N = input.nextInt();
for (int i = 1; i <= N; i++)
System.out.println(i + " " + cube(i));
}
}

15

Robert Sedgewick | Kevin Wayne


Pop quiz 1c on functions
Q. What happens when you compile and run the following code?

public class PQfunctions1c


{
public static int cube(int i){
i = i * i * i;
}

public static void main(String[] args){


Scanner input = new Scanner(System.in);
int N = input.nextInt();
for (int i = 1; i <= N; i++)
System.out.println(i + " " + cube(i));
}
}

17

Robert Sedgewick | Kevin Wayne


Pop quiz 1d on functions
Q. What happens when you compile and run the following code?

public class CubicPQ {


public static int cube(int i){
return i * i * i;
}

public static void main(String[] args){


Scanner input = new Scanner(System.in);
int N = input.nextInt();
for (int i = 1; i <= N; i++)
System.out.println(i + " " + cube(i));
}
}

19

Robert Sedgewick | Kevin Wayne


Pop quiz 1d on functions
Q. What happens when you compile and run the following code?

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

Robert Sedgewick | Kevin Wayne


Questions?
Q. What if I do not include a return statement?

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?

Answer. Yes. Use the statement return; with no return value.


21

Robert Sedgewick | Kevin Wayne


Return type void version
public class CubicPQ {
public static void cube(int i){
System.out.println(i*i*i);
return; //or omit the return statement;
}

public static void main(String[] args){


Scanner input = new Scanner(System.in);
int N = input.nextInt();
for (int i = 1; i <= N; i++) {
System.out.print(i + " ");
cube(i);
}
}
}
22

Robert Sedgewick | Kevin Wayne

You might also like