Professional Documents
Culture Documents
Methods
1
Chapter 5 Methods
Introducing Methods
◦ Benefits of methods, Declaring Methods, and Calling Methods
Passing Parameters
◦ Pass by Value
Overloading Methods
◦ Ambiguous Invocation
Scope of Local Variables
Method Abstraction
Some predefined Methods in (java.lang Package):
❑The Math Class
❑The String Class
❑The Character Class
2
Why to use Methods ?
separate the concept (what is done) from the
implementation (how it is done) (Information
hiding).
can be called several times in the same program
(reusability).
Different people can work on different methods
simultaneously.
Reduces complexity and increases readability.
3
Introducing Methods
A method is a collection of Method definition Structure:
statements that are grouped
together to perform an
operation.
4
Introducing Methods Cont…
• parameter profile refers to the type, order, and number of the
parameters of a method.
5
Notes !!!
If the return data type of a method is “void”, then, it
can’t return any value to the calling method.
6
Types of Methods
Methods
Predefined User-defined
Methods Methods
7
Example 1
public static int max(int num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
8
Calling Methods
pass i
pass j
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
9
Calling Methods Cont..
The main method pass 5 The max method
i: 5 num1: 5
pass 2
parameters
j: 2 num2: 2
k: 5 result: 5
10
CAUTION
A return statement is required for a non-void method. The following method
is logically correct, but it has a compilation error, because the Java compiler
thinks it possible that this method does not return any value.
11
Pass by value and Pass by Object
There are two ways to pass value or data to method in java:
◦ pass by value
◦ pass by object.
12
Passing Parameters
public static void nPrintln(String
message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
13
Pass by Value
pass num1
Pass num2
num1= 1
num2 = 2
14
Invoke swap
Pass by Value, cont.
num1 1 The values of num1 and
num2 are passed to n1 and
swap(num1, num2)
num2 2 n2. Executing swap does
not affect num1 and num2.
Pass by value
n2 2 n2 1
temp 1
15
Overloading Methods
public static double public static int
max(double num1, double max(int num1, int num2)
num2) { {
if (num1 > num2) if (num1 > num2)
return num1; return num1;
else else
return num2; return num2;
} }
Method overloading: Creating several
methods, within a class, with the same name.
16
Ambiguous Invocation
Sometimes there may be two or more
possible matches for an invocation of a
method
The compiler cannot determine the most
specific match.
This is referred to as ambiguous invocation.
Ambiguous invocation is a compilation
error.
Ambiguous Invocation
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
19
Varargs Example
import java.util.Scanner;
20
Scope (Local/Global identifier)
The scope of a declaration is the block of code where the
identifier is valid for use.
21
Scope (Local/Global Variable)
22
Some Predefined Methods
Some predefined Methods in (java.lang Package):
❑The Math Class
❑The String Class
❑The Character Class
❑Parsing String
23
The Math Class
24
The Math Class
Class • PI
constants: •E
• Trigonometric Methods
Class • Exponent Methods
methods: •
•
Rounding Methods
min, max, abs, and random Methods
25
The Math Class
Trigonometric Methods
❑sin(double a)
❑cos(double a)
❑tan(double a)
❑acos(double a)
❑asin(double a)
❑atan(double a)
26
The Math Class
Exponent Methods
❑ exp(double a)
Returns e raised to the power of a.
❑ log(double a)
Returns the natural logarithm of a.
❑ pow(double a, double b)
Returns a raised to the power of b.
❑ sqrt(double a)
Returns the square root of a.
27
The Math Class
➢ Rounding Methods
◦ double ceil(double x)
x rounded up to its nearest integer. This
integer is returned as a double value.
◦ double floor(double x)
x is rounded down to its nearest integer. This
integer is returned as a double value.
◦ int round(float x)
◦ long round(double x)
round(23.56) returns the value 24
round(23.35) returns the value 23
If x is float, the value returned is int
If x is double, the value returned is long
28
The Math Class
29
Exercise 1:
Computing Mean and Standard Deviation
Write a program that generates 10 random numbers and computes the
mean and standard deviation.
σ𝑛𝑖=1 𝑥𝑖
𝑥ҧ =
𝑛
𝑥ҧ is the mean
S is the standard deviation
30
The Character
Class
31
The Character Class
boolean isDigit(char ch)
boolean isLetter(char ch)
boolean isLetterOrDigit (char ch)
boolean isLowerCase (char ch)
boolean isUpperCase (char ch)
boolean isSpaceChar (char ch)
boolean isWhitespace (char ch)
char toLowerCase(char ch)
char toUpperCase(char ch)
32
Exercise 2:
Counting number of letters and digits in String
34
Constructing Strings
String newString = new String(stringLiteral);
35
The String Class
❑Finding string length using the ❑Retrieving Individual
length() method: Characters
◦ Do not use message[0]
message = "Welcome";
message.length() ◦ Use
message.charAt(index)
(returns 7)
◦ Index starts from 0
Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
message W e l c o m e t o J a v a
36
String Concatenation
String s3 = s1.concat(s2);
String s3 = s1 + s2;
s1 = “Hello“
s2 = “ World!“
S3 = “Hello World!”
37
Extracting Substrings
String s1 = "Welcome to Java";
String s2 = s1.substring(0, 11) + "HTML";
Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
s1 W e l c o m e t o J a v a
Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
S2 W e l c o m e t o H T M L
s1.substring(0, 11)
38
String Comparisons
equals
String s1 = "welcome";
String s2 = "welcome";
if (s1.equals(s2)){
// s1 and s2 have the same contents
}
if (s1 == s2) {
// it compares addresses (thus it will always give false)
39
String Comparisons, cont.
compareTo(String str)
comparing two strings lexicographically. Each character of both strings is converted into a Unicode value for comparison.
String s1 = "Welcome";
String s2 = "welcome";
if (s1.compareTo(s2) > 0) {
// s1 is greater than s2
else if (s1.compareTo(s2) == 0) {
else
// s1 is less than s2
40
String Conversions
toLowerCase ()
Converts the alphabet of the String into lower case
toUpperCase ()
Converts the alphabet of the String into lower case
trim ()
Eliminates leading and trailing spaces
str = “ Abc ” ;
System.out.println(str.toLowerCase());
System.out.println(str.toUpperCase());
abc
System.out.println(str.trim()); ABC
Abc
41
public String replace(char oldChar, char newChar)
returns a string replacing all the old char or CharSequence to new char or CharSequence
42
Finding Character/Substring
String str = "Welcome to Java“;
str.indexOf('W')) returns 0.
str.indexOf('x')) returns -1.
str.indexOf('o', 5)) returns 9.
str.indexOf("come")) returns 3.
str.indexOf("Java", 5)) returns 11.
str.indexOf("java", 5)) returns -1.
-1 is returned when the substring/character does NOT exist
Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
str W e l c o m e t o J a v a
43
Convert different types to
String
public static String valueOf(Object o)
method converts different types of values (boolean, char, char[], int, long, float, double) into string.
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);//concatenating string with 10
boolean bol = true;
boolean bol2 = false;
String s1 = String.valueOf(bol);
String s2 = String.valueOf(bol2); 3010
System.out.println(s1); true
System.out.println(s2); false
44
Parsing Numeric Strings
A string consisting of only an integer or decimal number is called a numeric string.
Example:
“6723”
“-4.2”
Integer.parseInt(strExp)
int x = Integer.parseInt(“6723”) x = 6723
Float.parseFloat(strExp)
float f = Float.parseFloat(“-4.2”) f = -4.2
Double.parseDouble(strExp)
double d = Double.parseDouble(“345.28”) d = 345.28
Note that Integer, Float, and Double are classes that contain methods to convert a
numeric string into a number.
45
Exercise 3:
Finding Palindromes
46
Reading/Writing
from/to file
47
Reading/Writing from/to file
1. import the necessary packages for reading/writing
◦ Import java.io.*;
◦ Import java.util.*;
2. Create and associate the appropriate objects with the input/output sources.
Scanner inFile = new Scanner(new FileReader(“FileName.txt”));
PrintWriter outFile = new PrintWriter (“outputFile.txt”);
3. Use the appropriate methods associated with objects created in step 2 to
input/output data.
❑ You will be using the same predefined methods associated with Scanner that we
studied in Chapter 1:
➢ inFile.next()
➢ inFile.nextLine()
➢ inFile.nextInt()
➢ inFile.nextDouble()
➢ etc
48
Reading/Writing from/to file
❑ In order to go through your file until EOF, you will be using the
following predefined method inside a loop:
➢ inFile.hasNext()
❑ and the same predefined methods for output:
➢ outFile.print()
➢ outFile.println()
➢ outFile.printf()
49
Example
50
Remarks
If the input/output file are located in the same project folder, you don’t
need to specify the full file path.
✓Scanner inFile = new Scanner(new
FileReader("C:/Users/Khouloud/Documents/NetBeansProjects/lab3/students.txt"
));
The output file does not have to exist before it is opened.
If it does not exist, the computer will prepare an empty file for your output
with the name you specified.
If the designated output file already exist, by default, the old contents are
erased when the file is opened.
Note that if the program is NOT able to access/create input/output file, it
throws a FileNotFoundException
This typically happens because of wrong path, or wrong file name.
51