Evo. G Tech Team Forum
Welcome to Evo. G Tech Team Forum. We have moved to a new website : www.evogtechteam.com

Thanks you.

by Evo. G Tech Team Management.


Go down


Post by LifeStyle on August 25th 2014, 13:11

Chapter 3: METHODS and ARRAYS



A method is a collection of statements that are grouped together to perform an operation. For example, when you call the System.out.println() method, the system actually executes several statements in order to display a message on the console.

Creating a Method

• Syntax / structure:

modifier returnValuetype methodname (list of parameters)  {
//method body }

return value

• 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.
• 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.

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 a value

int larger = max(3,4);   double m = convert_meter(km);

  // it calls convert_meter( ) and assigns the result to the variable m


System.out.println (max(3,4)); System.out.println (convert_meter(km));
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.
• Refer the example program below: To test the max method:

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;
      result =num2;
                  return result;
} //close class          


This program contains the main method and max method.
In this example, the main method invokes max (i, j) which is defined in the same class with the main method.
When the max method is invoked, i and j values are passed to num1 and num2. The flow of control transfers to the max method.
The max is executed. When the return statement is executed, it returns the control to its caller (main) and the value of result is passed to variable k.

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.

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.

public static double max (double num1, double num2)
if(num1> num2)
return num1;   else
return num2;

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: Demonstrate method overloading

public class TestMethodOverloading {  

 public static void main(String[] args) {
       // Invoke the max method with int parameters  
  System.out.println("The maximum between 3 and 4 is " + max(3, 4));

   // Invoke the max method with the double parameters  
   System.out.println("The maximum between 3.0 and 5.4 is "+ max(3.0, 5.4));  

   // Invoke the max method with three double parameters
   System.out.println("The maximum between 3.0, 5. 4, and 10.14 is "+ max(3.0,
5.4 , 10.14));


/** Return the max between two int values */

 public static int max(int num1, int num2) {     if (num1 > num2)      return num1;     else
    return num2;

/** Find the max between two double values */

  public static double max(double num1, double num2) {    if (num1 > num2)       return num1;     else      return num2;  

/** Return the max among three double values */   public static double max(double num1, double num2, double num3) {     return max(max(num1, num2), num3);  


Overloaded methods must have different parameter lists. You cannot overload methods based on different modifiers or return types.
The scope of local variables o The scope of variable is the portion of the program where the variable can be accessed. o Is limited locally to a method. It starts from its declaration and continues to the end of the block that contains the variable.
o A variable must be declared before it can be used. o And it must be initialized before it is referenced.
o 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++)
{ }

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 don’t 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.

The Math Class

• Contains the methods needed to perform basic mathematical functions.
• For example:
1) Exponent methods  o Math.pow(2,3) – returns 8.0
o Math.sqrt(4) – returns 2.0

2) Trigonometric methods o Math.sin(0) – returns 0.0 o Math.sin(Math.PI /6) – returns 0.5 o Math.cos(0) – returns 1.0

3) The rounding methods o Math.ceil(2.1) – returns 3.0
o Math.floor(2.1) – returns 2.0

4) The min, max and abs Methods o Math.max(4,5) – returns 5 o Math.min(2.5,3.6) – returns 2.5
o Math.abs(-2.1) – returns 2.1

5) The random Methods o (int) (Math.random()*10) – returns a random integer between 0 and 9.


• 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.

• An array is same as variables but to identify an array is from this symbol [ ] .

• 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.  

• Two types of array:  1) One-Dimensional Array
       2) Two-Dimensional Array

To declare and create Array

• Same rules and conditions as variables, but we have to write the [ ]. The syntax of declaring:

dataType arrayName [];
dataType [] arrayName;

double score [];
OR double [] score;

• 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:

arrayName = new dataType[size];

score = new double[5];

• Example:

• Declare and create: (can be combined in one statement)

double score [] = new double[5];

• This statement declares an array variable, score, creates an array of five elements of double type, and assigns its reference to 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

• In the definition time
- We assign the value in the first place which means we set the values.

Example: double score [ ] = { 90.5,95.0,60.0,45.0,77.5 } ;

- so the ‘score’ has already been set, the content are 90.5,95.0,60.0,45.0,77.5 (only).
• 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:

for (int i = 0; i
list [i] = i ;
How to refer to the certain value in the array?

• Because of we share the same name, so maybe it’s confusing to refer to that particular value for example, we want to print ’60.0’ from the ‘score’.  

• An array has subscripts or index, to identify the values. It starts with 0.

double score [ ] = { 90.5,95.0,60.0,45.0,77.5 };

90.5 95.0 60.0 45.0 77.5
0 1 2 3 4 this is subscripts/index
• So,  
System.out.println(score[2]) ;   // will print ’60.0’

Important: you have to remember that array’s index start with 0.

• Example program (1)

public class arrayExample
{ public static void main (String [] args)
double score[ ] = {90.5,95.0,60.0,45.0,77.5};   double max;
  max = score[0];
 for (int n = 0; n < 5; n++)
  {          if (score[n] > max)
             max = score[n];

System.out.println(“The highest score is ” +max);

Processing Arrays

• We need to use looping (usually for) to process array. You need to understand clearly about looping.

• 1) To initialize with user input Example:
Let’s say, we want to input data to an array (mark) that has 5 values. Assuming that the array is already been defined.
Scanner input = new Scanner(System.in); System.out.print(“Enter marks: ”); for (int n = 0; n < 5; n++)
{      mark[n] = input.nextDouble();

• 2) To display Example:
Let’s say, we want to display (print) all the elements in the array.

for (int n = 0; n < 5; n++)


    System.out.print(mark[n] +” ”);


• 3) To search a value in an array Example:
Let’s say, we want to find a value such as the highest value in an array (refer to Program 1 page 10)

for (int n = 0; n < 5; n++)


   if (score[n] > max)
   max = score[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.

5) Passing Array to Methods  

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 argument’s 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

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;
o Output: x is 1 y[0] is 5555

o Since y contains the reference value to the array, z now contains the same reference value to the same array.

o Remember, when passing an array to method, the reference of the array is passed to the method.

6) Copying Arrays

To duplicate an array or part of an array  Three ways, using:
1. = operator,  
2. for loop (individual) and  
3. method arraycopy( )
4. clone method (will not be covered)

(Further discussion in the class/lab session)

Multidimensional Arrays

(Two –dimensional Array)
• Declaring  

dataType arrayName [][];
dataType [][] arrayName;


double collection [][]; //allowed but not preferred
int [][] myarray;

• Creating

  arrayName = new dataType[][]


collection = new double[5][5];

myarray = new int[4][3];

• OR COMBINE (Declare and Create)
double collection [][] = new double [5][5];
int [][] myarray = new int[4][3];
o Two subscripts are used in a two-dimensional array. One for the row and the other is for the column.

0 1 2





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 Refer to the one dimensional array   initialization.  o Analyze this statement:
int [][] myarray = { {5,7,3} , {4,6,9}, {10,1,8}, {89,3,66} };

0 1 2
5 7 3
4 6 9
10 1 8
89 3 66

It is a common mistake to use myarray [ 2, 1 ] to access the element at row 2 and column 1. In Java, each subscript must be enclosed in a pair of square brackets.
Remember : two-dimensional array must has 2 for looping statements for processing to represent rows and columns.

• To obtain the lengths of Multidimensional Arrays
o Same as one-dimensional array, we may use the method length. o To understand the concept, analyze the figure below:

int [][] x = new x[4][3];
 x.length is 4
x[3].length is 3

Posts : 10
Points : 37010
Reputation : 0
Join date : 2014-01-06
Location : Behide you

View user profile

Back to top Go down

Back to top

- Similar topics

Permissions in this forum:
You cannot reply to topics in this forum