0% found this document useful (0 votes)
5 views36 pages

Lecture10-2024

The document provides an overview of Java functions and methods, detailing their structure, access modifiers, and the importance of Javadoc comments. It explains variable scope, parameter passing, and includes examples of various types of functions such as void, boolean, and string functions. Additionally, it covers method signatures and the concept of method overloading in Java.

Uploaded by

HAMO
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views36 pages

Lecture10-2024

The document provides an overview of Java functions and methods, detailing their structure, access modifiers, and the importance of Javadoc comments. It explains variable scope, parameter passing, and includes examples of various types of functions such as void, boolean, and string functions. Additionally, it covers method signatures and the concept of method overloading in Java.

Uploaded by

HAMO
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

J AVA F UNCTIONS /M ETHODS

‣ Functions
‣ Access modifiers
‣ Javadoc comments for methods
‣ Variable scope and Parameter
passing
h t t p : / / ho r st m a n n . c o m / b j l o 1/ i n de x . h t m l ‣ Dry-running a class
J AVA F UNCTIONS /M ETHODS

‣ Functions
‣ Access modifiers
‣ Javadoc comments for methods
‣ Variable scope and Parameter
passing
h t t p : / / ho r st m a n n . c o m / b j l o 1/ i n de x . h t m l ‣ Dry-running a class
Functions

A Java function is a static method.


• May require 0 or more arguments
• May return 0 or 1 value (NOT print!)
• May perform other operation on top of what
the function primarily computes.

Benefits Input
• Allows for program modularization
• Allows for code reuse
• Allows for code sharing
• Effective code management and
maintenance
Function f

Output
3
A closer look at a Java static method aka function

Access
Return Method Formal
modifier
type name parameters

public static boolean isPrime(int num) {


for(int i = 2; i*i < num; i++) {
if (num % i == 0) {
Method
return false;
body
}
}
return true;
}

Return statements
4
Java class structure – A Java Library!

Imports
public class ABC
{
public static int fOne(...) { // body }
public static String fTwo(...) { // body }
.
.
.
public static double fM(...) { // body }
public static void main(String[] args) {
.
.
.
}
}

• No method inside another method body! 5


Creating your own static method – a function

• Give the method an appropriate name – must


be meaningful
• Declare input parameters for the method
(separated by comma)
• Specify the return type
• Implement the body of your function
• Return the value to be returned. Each path
that the execution of your method may take
MUST end with a return statement

6
Example 1 – A void function
❑ This function does not return a value but performs some
functionality
Write a Java function
public class Lib that displays the
{ following menu:
public static void displayMenu() { 1. Multiplication
System.out.printf(“1. Multiplication\n”); 2. Division
System.out.printf(“2. Division\n”); 3. Addition
System.out.printf(“3. Addition\n”); 4. Subtraction
System.out.printf(“4. Subtraction\n”); 5. Quit
System.out.printf(“5. Quit\n”);
}
public static void main(String[] args) {
Lib.displayMenu(); // invocation
}
}

7
Example 1 – A void function with proper
implementation
❑ All functions/methods must have Javadoc comments.
❑ - it includes a description of what the method does
❑ - it describes what the formal parameters are
❑ - it describes what is returned (if any) by the method

public class Lib { • void means there is no


/** value returned, so no
* Method to display the menu need to explain return
*/ type
public static void displayMenu() { • Method has no
System.out.printf(“1. Multiplication\n”); parameters, so no need
System.out.printf(“2. Division\n”); to explain parameters
System.out.printf(“3. Addition\n”); • So only the purpose of
System.out.printf(“4. Subtraction\n”); the method is
System.out.printf(“5. Quit\n”); explained in the
} comment
}
8
Example 2 – A boolean function
❑ This function returns either true or false

Write a Java function


public class Lib that returns true if the
{ given character is a
public static boolean isVowel(char ch) { vowel or not.
String vowels = “AaEeIiOoUu”;
boolean result = vowels.indexOf(ch) >= 0;
return result;
}
public static void main(String[] args) {
boolean f = Lib.isVowel(‘V’); //invocation
}
}

9
Example 2 – A boolean function with proper
implementation

public class Lib {


/**
* Checks if a given character is a vowel.
*
* @param ch a character to check if it is a vowel.
* @return true if the given character is a vowel.
*/
public static boolean isVowel(char ch) {
String vowel = “AaEeIiOoUu”;
boolean result = vowel.indexOf(ch) >= 0;
return result;
}
}

10
Example 3 – A number function
❑ This function returns an integer or double value

public class Lib


Write a Java function
{
that returns the largest
public static int largestFactor(int N) {
factor of an integer N
for (int i = N/2; i >= 2; i--) {
other than 1 and N
if (N % i == 0) {
itself.
return i; // found a factor between 2 and N/2

}
}
return N; // N is prime!
}
public static void main(String[] args) {
int factor = Lib.largestFactor(1000);
}
}

11
J AVA F UNCTIONS /M ETHODS

‣ Functions
‣ Access modifiers
‣ Javadoc comments for methods
‣ Variable scope and Parameter
passing
h t t p : / / ho r st m a n n . c o m / b j l o 1/ i n de x . h t m l ‣ Dry-running a class
Example 3 – A number function with
implementation
public class Lib {
/**
* Method to compute the largest factor of a given integer other
* than 1 and N.
*
* @param N the integer to compute the largest factor of.
* @return the largest factor of the given integer, or N itself
* if N is prime
*/
public static int largestFactor(int N) {

}
}

13
Example 4 – A String function
❑ This function returns a String value

public static String dayToString(int day) {


Write a Java function
String result = “”;
that returns the string
if (day == 0 || day == 6) {
“Weekday” or “Weekend”
result = “Weekend”;
for a day given as a
}
number.
else {

result = “Weekday”;

return result;

14
Calling functions from another class

public class Another


{
public static void main(String[] args) {
int x = 23456;
Lib.displayMenu();
boolean f = Lib.isVowel(‘V’);
int pf = Lib.largestFactor(x);
String today = Lib.dayToString(5);
}
}

We use the class name as


the methods are static.

15
POP QUIZ

1. Write a Java method that given a string returns the


string with all the vowels removed.
If given “Tallman”, the method returns “Tllmn”

2. Write a Java method that given two strings of


equal length will return the number of positions in
which the two strings differ.

If given “Tallman” and “Tillmen”, the method


should return 2
J AVA F UNCTIONS /M ETHODS

‣ Functions
‣ Access modifiers
‣ Javadoc comments for methods
‣ Variable scope and Parameter
passing
h t t p : / / ho r st m a n n . c o m / b j l o 1/ i n de x . h t m l ‣ Dry-running a class
Access Modifiers

• public: means method can be invoked outside


the class.
• private: means method cannot be invoked
outside the class – only from within the
class.
➢ Only one of public and private can be
specified, not both.
• static: means method belongs to the class –
it’s a function. Class name is to be used
for invoking the method.
• final means that method cannot be
overridden/adapted by subclasses.

18
J AVA F UNCTIONS /M ETHODS

‣ Functions
‣ Access modifiers
‣ Javadoc comments for methods
‣ Local variables and Formal
parameters
h t t p : / / ho r st m a n n . c o m / b j l o 1/ i n de x . h t m l ‣ Variable scope and Parameter
passing
‣ Dry-running a class
Local variables and formal parameters

public class MyLib {


public static double average(int num1, int num2) {
int sum = num1 + num2;
double mean sum / 2.0;
return mean;
}
}

• Formal parameters: variables used to hold values passed


to the method. It is considered bad practice for the
method to change values held by formal parameters
• Local variables: variables declared within the method
and used by the method for computations.
• Both formal parameters and local variables are
destroyed when the method/function is terminated.
For the function average:
• Formal parameters: num1, num2
• Local variables: sum, mean
20
Coding Bat

❑ Visit the website https://codingbat.com/java


❑ Create an account
❑ Work on the Warmup-1, Warmup-2, Logic-1, String-1,
problems ---- ALL Problems

21
J AVA F UNCTIONS /M ETHODS

‣ Functions
‣ Access modifiers
‣ Javadoc comments for methods
‣ Variable scope and Parameter
passing
h t t p : / / ho r st m a n n . c o m / b j l o 1/ i n de x . h t m l ‣ Dry-running a class
Variable scope

import java.util.Scanner;
public class MyLib {
public static void main(String[] args) {...}
public static int max(int num1, int num2) { int i;... }
public static String myst(String i) { int num1; ...}
}

• Variables declared inside a method/function are not visible in


other methods/functions.
• Variables declared in a class, outside all other
methods/functions, are visible to all methods / functions

23
Variable scope
public class Example {
int x;
public void swap(int x, int y) {
int temp = x;
}
public static int max(int num1, int num2) {
int m = num1;
}
public static void main(String[] args) {
int x = 5;
for(int y = 1; y<=10; y++) {
int w = 5;
} Arrows show where
while (x <= 200) { visibility of a variable
int w = 6; ends.
}

}
}
24
What is the output?
public class Example {
public void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
public static int max(int num1, int num2) {
int m = num1;
if (num2 > m ) { m = num2; } return m;
}
public static void main(String[] args) {
int x = 5; int t = 7;
System.out.printf(“x = %d t = %d\n”, x, t);
Example test = new Example(); // magic!
test.swap(x, t);
System.out.printf(“x = %d t = %d\n”, x, t);
System.out.printf(“Max = %d\n”, Example.max(x, t));
}
}
25
J AVA F UNCTIONS /M ETHODS

‣ Functions
‣ Access modifiers
‣ Javadoc comments for methods
‣ Variable scope and Parameter
passing
h t t p : / / ho r st m a n n . c o m / b j l o 1/ i n de x . h t m l ‣ Dry-running a class
Executing a Java class
❑ Execution starts in the main method
❑ If there is no main method, a Java class can not be
executed.
main

x t args
5 7

test 123

123
test: Example

Console

x = 5, t = 7
Object diagram
_
27
Executing a Java class…

test.swap

temp ? x 5

y 7

Console

x = 5, t = 7
_
28
Executing a Java class…

test.swap

temp 5 x 5

y 7

Console

x = 5, t = 7
_
29
Executing a Java class…

test.swap

temp 5 x 7

y 7

Console

x = 5, t = 7
_
30
Executing a Java class…

test.swap

temp 5 x 7

y 5

Console

x = 5, t = 7
_
31
Executing a Java class…
❑ Method swap terminates and its box/frame is deleted

test.swap

temp 5 x 7

y 5

❑ Controls returns to the calling method…which is main

Console

x = 5, t = 7
x = 5, t = 7
32
What is the output?
public class Example2 {
public void changeXtox(String s) {
String t = “”;
for(int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ‘X’) { t = t + ‘x’;}
else { t = t + s.charAt(i);}
}
}
public static String middle(String s, int num) {
int mid = s.length / 2
return (mid % 2 ==0)? s.substring(mid-1, mid+num+1) :
s.substring(mid, mid+num+1);
}
public static void main(String[] args) {
String str = “Xmen live in the X-dimension”;
Example2 test = new Example2(); // magic!
test.changeXtox(str);
System.out.printf(“str = %s\n”, str);
System.out.printf(“mid = %s\n”, Example.middle(str, 2));
}
}
33
How arguments are passed to methods in Java
Arguments are passed-by-value in Java,
regardless of whether the value is an
address/reference to an object or its just a
value (primitive)

34
Method signature
❑ Used to differentiate methods – different signatures implies
different methods.
❑ Is made up of method name and data types of formal
parameters, in the order they appear in the declaration
❑ This allows us to reuse a method name!

public static boolean isPrimeNumber( int n) { … }


public static int gcd(int a, int b) { … }
public static char randomChar(String s) { … }
public static void main(String[] args) { … }
public static double gcd(long a, long b) { … }

Signatures:
isPrimeNumber( int) Same method name
gcd(int, int)  overloaded method BUT different
randomChar(String) signatures!
main(String[])
gcd(long , long)  overloaded method

35
Summary

▪ Anatomy of a Java method


▪ Access modifiers: public, private, static, and final
▪ Functions are an extremely useful construct
▪ They promote code reuse
▪ They facilitate code modularization
▪ Dry running a Java class – class/method diagrams
▪ Method signatures
▪ Local variables and formal parameters
▪ Pass-by-value technique in Java for method arguments

36

You might also like