You are on page 1of 51

Chapter 5:

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.

• method signature is the combination of the method name and


the parameter profiles.

• The parameters defined in the method header are known as


formal parameters.

• When a method is invoked, its formal parameters are replaced


by variables or data, which are referred to as actual
parameters.

5
Notes !!!
If the return data type of a method is “void”, then, it
can’t return any value to the calling method.

If the return data type of the method is other than


void such as “int, float, double etc”, then, it can
return values to the calling method.
Only one value can be returned from a method.

6
Types of Methods
Methods

Predefined User-defined
Methods Methods

String Character Math

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.

public static int xMethod(int n) {


if (n > 0) return 1;
else if (n == 0) return 0;
else if (n < 0) return –1;
}

To fix this problem, delete if (n<0) in the code.

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.

Original value is not modified in pass by value but it is modified in pass


by reference.
In this chapter we will cover only pass by value
In order to change the original value we need to use:
IntClass instead of int
DoubleClass instead of double
StringBuffer instead of String

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

swap( n1, n2) n1 1 Swap n1 2

n2 2 n2 1

temp 1

Execute swap inside the swap body

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.

In the method call, the parameter profile


determines which method to execute !

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));
}

public static double max(int num1, double num2) {


if (num1 > num2)
return num1;
else
return num2;
}

public static double max(double num1, int num2) {


if (num1 > num2)
return num1;
else
return num2;
}
}
Methods with variable Number of
Parameters (Varargs)
Syntax:
MethodName(data_type … VarName)
varargs are arrays so we work with them just like we'd work with a
normal array.
You can call it with 0 or more Arguments.
Rules:
❑Each method can only have one varargs parameter
❑The varargs argument must be the last parameter

19
Varargs Example
import java.util.Scanner;

public class Test_Varargs {


public static void formatWithVarArgs(String... values) {
for (String value : values) {
System.out.println(value);
}
}

public static void main(String[] args) {


System.out.println("First Call:");
formatWithVarArgs("Mehdi", "Ameni", "Mohamed");
System.out.println("\nSecond Call:");
formatWithVarArgs("Hello World");
}
}

20
Scope (Local/Global identifier)
The scope of a declaration is the block of code where the
identifier is valid for use.

◦ A global declaration is made outside the bodies of all functions and


outside the main program. It is placed at the beginning of the
program file.
◦ A local declaration is one that is made inside the body of a function.
Locally declared variables cannot be accessed outside of the function
they were declared in.
◦ It is possible to declare the same identifier name in different parts of
the program.

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

max(a, b)and • Returns the maximum or


min(a, b) minimum of two parameters.

• Returns the absolute value of


abs(a) the parameter.

• Returns a random double value


random() in the range [0.0, 1.0).

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

Write a program that will


read a string from user,
count the number of
letters and digits, and then
display it to the screen.
33
The String Class

34
Constructing Strings
String newString = new String(stringLiteral);

String message = new String("Welcome to Java!");

Since strings are used frequently, Java provides


a shorthand notation for creating a string:

String message = "Welcome to Java!";

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

message.charAt(0) message.length() is 15 message.charAt(14)

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

s1.substring(0, 11) message.substring(11)

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) {

// s1 and s2 are equal

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

String s1 = “Programming in Java is Fun”;


String replaceString = s1.replace('a','e');
//replaces all occurrences of 'a' to 'e'
System.out.println(replaceString);

String s1 = "my name is Ahmed my name is beautiful";


String replaceString = s1.replace("is“,"was");
//replaces all occurrences of "is" to "was"
System.out.println(replaceString);

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

Write a method that will return


true if a given number is
palindrome, false otherwise: a
palindrome number that reads
the same forward and
backward.

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()

4. Your main should (throws FileNotFoundException)


5. Close the files.
◦ inFile.close();
◦ outFile.close();

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

You might also like