Académique Documents
Professionnel Documents
Culture Documents
Chapter 3
Creating a Method
Syntax / structure:
modifier returnValuetype methodname (list of parameters)
{
//method body
}
Example:
return valueType
methodname
Parameter
modifier
Method
header/signature
if ( num1>num2 )
result = num1;
else
result =num2;
method body
return result;
}
return value
CDP
The modifier
Is optional, tells the compiler how to call the method.
static modifier is used (will be introduced in Chapter 4)
returnValuetype
Is a data type of the value the method returns
If the method does not return a value, the returnValuetype is the keyword void.
All method except constructors requires returnValuetype. Constructors are
introduced in Chapter 4.
Page 1 of 14
ainee/5018/Tri47
Chapter 3
Parameters
Refers to the type, order and number of the parameters of a method.
Parameters are optional; a method may contain no parameters.
When a method is invoked, you pass a value to the parameter. This value is
referred to as actual parameter or argument.
Method body
Contains a collection of statements that define what the method does.
A return statement using the keyword return is required for a non-void method to
return a result.
The method terminates when a return statement is executed.
CAUTION:
You need to declare a separate data type for each parameter. For instance,
int num1, num2 should be replaced by int num1, int num2.
Note: In certain other languages, methods are referred to as procedures
and functions.
Calling a Method
To use a method, you have to call or invoke it. Two ways to call a method:
If the method returns void, a call to the method must be a statement. Example:
convert_meter (km) ;
When a program calls a method, program control is transferred to the called method. A called
method returns control to the caller when its return statement is executed or when its methodending closing brace is reached.
CDP
Page 2 of 14
ainee/5018/Tri47
Chapter 3
Problem:
Write a program that demonstrates how to create and invoke the max method. The method will
return the maximum number.
Solution: (Source Text book page 128)
//Chapter 2 eg1: TestMax.java
public class TestMax {
public static void main (String [] arg)
{
int i = 5;
int j = 2;
int k = max(i, j);
System.out.println(The maximum between +i+ and +j+ is +k);
} //close main
public static int max (int num1, int num2)
{
int result;
if ( num1>num2 )
result = num1;
else
result =num2;
return result;
}
} //close class
Explanation:
Passing Parameters
The power of a method is its ability to work with parameters. When invoke a method with
parameters, a copy of the value of the actual parameter is passed to the method. This referred to
as pass by value. The actual variable outside the method is not affected, regardless the changes
made to the formal parameter inside the method.
Refer to example program, the max is passing parameters: i and j.
CDP
Page 3 of 14
ainee/5018/Tri47
Chapter 3
Overloading Methods
Analyze the program:(TestMax.java)
The max method works only with the int data type. But if we need to find which of two
floating-points numbers has the maximum value? The solution is to create (add) another
method with the same name but different parameters in the program.
If you call max with the double parameters, the max method that expects double
parameters will be invoked. This is referred to as method overloading; that is two methods
have the same name but different parameters profiles. Refer to the example below:
(TestMethodOverloading.java)
CDP
Page 4 of 14
ainee/5018/Tri47
Chapter 3
CDP
Note
Overloaded methods must have different parameter lists. You cannot overload methods
based on different modifiers or return types.
Page 5 of 14
ainee/5018/Tri47
Chapter 3
The scope of variable is the portion of the program where the variable can be accessed.
Is limited locally to a method. It starts from its declaration and continues to the end of the
block that contains the variable.
A variable must be declared before it can be used.
And it must be initialized before it is referenced.
You will learn about instance variables and class variables in Chapter 3.
You can declare a local variable with the same multiple times in different non-nesting
blocks in a method, but you cannot declare a local variable twice in nested blocks. Thus,
the following code is correct.
public static void correctMethod( )
{
int x=1;
int y=1;
// i is declared
for ( int i = 1; i<10; i++)
x += i;
// i is declared again
for ( int i = 1; i<10; i++)
y += i;
}
The next code would cause a compilation error because variable i is declared in the for
loop body block where another i is declared.
public static void incorrectMethod( )
{
int x=1;
int i=1;
for (int i = 1; i<10; i++)
{
x = 0;
x+= i;
}
}
The next code would cause a syntax error because variable x is not defined outside of the
for loop.
for(int x=0; x<10; x++)
{ }
System.out.println(x);
CDP
Page 6 of 14
ainee/5018/Tri47
Chapter 3
Caution: Do not declare a variable inside a block and then use it outside the block.
If a variable is declared as a method parameter, it cannot be declared inside the method. The
scope of a method parameter covers the entire method.
A variable declared in the initial action part of a for loop header has its scope in the entire loop.
But a variable declared inside a for loop body has its scope limited in the loop body from its
declaration and to the end of the block that contains the variable.
Method Abstraction
Method abstraction is achieved by separating the use of a method from its implementation.
The client can use a method without knowing how it is implemented. The details of the
implementation are encapsulated in the method and hidden from the client who invokes the
method.
This is known as encapsulation or information hiding.
If you change the implementation, the client program will be not affected, provided that you
dont change the method signature.
For example, you have already used the System.out.println and System.out.printf
method to display a string. You know how to use and invoke that method in your programs
but as a user you are not required to know how they are implemented.
CDP
Page 7 of 14
ainee/5018/Tri47
Chapter 3
ARRAYS
Introduction
An array is a collection of data elements or objects of the same type. It is a consecutive group
of memory locations that all have the same name and the same type.
Or in other word, an array is a list or more than one variable that having the same name.
The individual data items can be characters, integers, floating-point numbers, etc.
See example above: values in the price array are floating numbers. The important is
only one type of data. The content (data type) cannot be mixed.
Same rules and conditions as variables, but we have to write the [ ]. The syntax of declaring:
dataType arrayName [];
OR
dataType [] arrayName;
Example:
Unlike declarations for primitive data type variables, the declaration of an array variable does
not allocate any space in memory for the array.
So, we have to create array, then we can assign elements to the array.
You can create an array by using new operator with the following syntax:
CDP
Example:
Page 8 of 14
ainee/5018/Tri47
Chapter 3
This statement declares an array variable, score, creates an array of five elements of double
type, and assigns its reference to score.
score
score[0]
score[1]
score[2]
score[3]
score[4]
Array initialization
(Assigning or giving a value to array before using it)
Two ways.
1) In the definition time
2) In the program
We do not know the content, or in other word; we are not giving the array
values.
The array will get the elements from the program or the user. We only
set for the size.
This steps we need to use repetition structure
Example:
In the program
CDP
Page 9 of 14
ainee/5018/Tri47
Chapter 3
Because of we share the same name, so maybe its confusing to refer to that particular
value for example, we want to print 60.0 from the score.
90.5
0
95.0 60.0
1
2
45.0
3
77.5
4 this is subscripts/index
So,
System.out.println(score[2]) ;
CDP
Page 10 of 14
ainee/5018/Tri47
Chapter 3
Processing Arrays
We need to use looping (usually for) to process array. You need to understand clearly
about looping.
2) To display
Example:
Lets say, we want to display (print) all the elements in the array.
for (int n = 0; n < 5; n++)
{
System.out.print(mark[n] + );
}
4) Sorting Array
Sorting is the common task in computer programming. It would be used when
you wanted to display the grades in alphabetical order, for example.
Many different algorithms have been developed for sorting
Since you had learned sorting in Data Structure, we will not cover this part. You
know how it works; the task now is to implement it in Java.
Selection sort repeatedly selects the largest number and swaps it with the last
number.
CDP
Page 11 of 14
ainee/5018/Tri47
Chapter 3
Java uses pass by value to pass arguments to a method. There are important
differences between passing the values of variables of primitive data types and
passing arrays.
o For an argument of a primitive type, the arguments value is passed
o For an argument of an array type, the value of the argument contains a
reference to an array; this reference is passed to the method.
Example 1:
o You can invoke it by passing an array.
o For example:
int myArray[ ] = { 7,10, 12, 45, 3 };
printArray(myArray);
public static void printArray(int[] arr)
{
for(int j = 0;j<arr.length;j++)
System.out.printl(arr[j]+ );
}
Example 2
public class ArrayPassing
{
public static void main(String [] args)
{
int x = 1;
int [] y = new int[4];
methodArray(x,y); //calling methodArray
System.out.println(x is +x);
System.out.println(y[0] is +y[0]);
}
public static void methodArray(int n, int[]z)
{
n = 1001;
z[0] = 5555;
}
}
CDP
Output:
x is 1
y[0] is 5555
Since y contains the reference value to the array, z now contains the
same reference value to the same array.
Page 12 of 14
ainee/5018/Tri47
Chapter 3
6) Copying Arrays
Multidimensional Arrays
(Two dimensional Array)
Declaring
dataType arrayName [][];
OR
dataType [][] arrayName;
Example:
double collection [][]; //allowed but not preferred
int [][] myarray;
Creating
arrayName = new dataType[][]
Example:
collection = new double[5][5];
myarray = new int[4][3];
CDP
Two subscripts are used in a two-dimensional array. One for the row and the other is
for the column.
Page 13 of 14
ainee/5018/Tri47
Chapter 3
0
1
2
3
myarray [4][3]
To initialize the array, same concepts are applied to two-dimensional array (with 2loops).
1) In the definition time
2) In the program
o
5
4
10
89
7
6
1
3
3
9
8
66
x
x[0]
x[1]
x[2]
x[3]
x [0][0]
x[0][1] x[0][2]
x [1][0]
x[1][1]
x [2][0]
x [3][0]
x[2][1]
x[3][1]
x[1][2]
x[2][2]
x[3][2]
x.length is 4
x[0].length is 3
x[1].length is 3
x[2].length is 3
x[3].length is 3
CDP
Page 14 of 14
ainee/5018/Tri47