Saturday, November 26, 2011

User Defined Methods

Do you want to know the secrets of Java Programming and use it for the advancement of your career in IT? Do you have problems in your Java course? Here is an instant solution for your problem. Avail the Java training package of Prof Erwin Globio and get free tips about Java Programming Secrets. For more free information about Java and Java Training visit the following sites:http://erwinglobio.sulit.com.ph/ http://erwinglobio.multiply.com/http://erwinglobio.wordpress.com/. You may contact the Java Trainer at 09393741359 or 09323956678. Call now and be one of the Java Experts.



Introduction

There are both predefined methods, methods that are already written and provided by Java, and user-defined methods, methods that you create.



Using methods has several advantages:

  • While working on one method, you can focus on just that part of the program and construct it, debug it, and perfect it.

  • Different people can work on different methods simultaneously.

  • If a method is needed in more than one place in a program, or in different programs, you can write it once and use it many times.

  • Using methods greatly enhances the program’s readability because it reduces the complexity of the method main.

Methods are often called modules. They are like miniature programs; you can put them together to form a larger program.


Predefined Methods

In Java, predefined methods are organized as a collection of classes, called class libraries.  The class Math contained in the package java.lang contains mathematical methods.  The method type is the data type of the value returned by the method.  Some predefined methods in the class Math are:

            Math.log10(x)
Math.abs(x)
Math.ceil(x)
Math.exp(x)
Math.floor(x)
Math.log(x)
Math.max(x, y)
Math.min(x, y)
Math.pow(x, y)
Math.round(x)
Math.sqrt(x)
Math.cos(x)
Math.sin(x)
Math.tan(x)

Teaching Tip

The method log10 is not available in JS2E versions lower than 5.0.



The class Character, also in the package java.lang, contains the following methods:

Character.isDigit(ch)
Character.isLetter(ch)
Character.isLowerCase(ch)
Character.isUpperCase(ch)
Character.isSpaceChar(ch)
Character.isWhitespace(ch)
Character.toLowerCase(ch)
Character.toUpperCase(ch)

Teaching Tip

The complete J2SE 1.5.0 API specification, which includes documentation for all predefined classes and methods in the J2SE 1.5.0 release, can be found at:


Using Predefined Methods in a Program

In general, to use predefined methods of a class in a program, you must import the class from the package containing the class.  By default Java automatically imports classes from the package java.lang. Therefore, if you use a method from the class Math or Character you do not need to explicitly import these classes in your program.

A method of a class may contain the reserved word static (in its heading). For example, the method main contains the reserved word static in its heading. If (the heading of) a method contains the reserved word static, it is called a static method; otherwise, it is called a nonstatic method.

The heading of a method may contain the reserved word public. If the heading of a method contains the reserved word public, it is called a public method. An important property of a public and static method is that (in a program) it can be used (called) using the name of the class, the dot operator, the method name, and the appropriate parameters.

To simplify the use of (public) static methods of a class, JS2E 1.5.0 introduces the following import statements:

import static packageName.ClassName.*;
import static packageName.ClassName.methodName;

These are called static import statements.

Teaching Tip

More information on static import statements can be found at:

Teaching Tip

The static import statement is not available in versions of Java lower than 5.0, such as 1.4.0. Therefore, if you are using, say Java 1.4.0, then you must use a static method of the class Math using the name of the class and the dot operator.


User-Defined Methods

User-defined methods in Java are classified into two categories:

  • Value-returning methods—methods that have a return type.

  • Void methods—methods that do not have a return type.


Value-Returning Methods

To use value-returning methods in your programs, you must know:

  1. The name of the method.

  1. The number of parameters, if any.

  1. The data type of each parameter.

  1. The data type of the value computed (that is, the value returned) by the method, called the type of the method.

  1. The code required to accomplish the task. (for a user-defined method)

The first four properties become part of what is called the heading of the method; the fifth property is called the body of the method. Together, these five properties form what is called the definition of the method.



Because the value returned by a value-returning method is unique, it is natural for you to use the value in one of three ways:

  • Save the value for further calculation.

  • Use the value in some calculation.

  • Print the value.

A value-returning method is used in an expression.

A Formal parameter is a variable declared in the method heading.  An Actual parameter is a variable or expression listed in a call to a method.

Teaching Tip

For predefined methods, you need to be concerned only with the first four properties. Software companies do not give out the actual source code, which is the body of the method.


Syntax: Value-Returning Method

The syntax of a value-returning method is:

modifier(s) returnType methodName(formal parameter list)
{
statements
}

  • The modifier(s) indicates the visibility of the method, that is, where in a program the method can be used (called). Some of the modifiers are public, private, protected, static, abstract, and final.

  • returnType is the type of value that the method returns. This type is also called the type of the value-returning method.

  • methodName is a Java identifier, giving a name to the method.

  • Statements enclosed between curly braces form the body of the method.

Teaching Tip

Abstract methods are covered in Chapter 11. Chapter 8 describes, in detail, the meaning of the modifiers public, private, and static.


Syntax: Formal Parameter List

The syntax of a formal parameter list is:

dataType identifier, dataType identifier,...


Method Call

The syntax to call a value-returning method is:

methodName(actual parameter list)


Syntax: Actual Parameter List

The syntax of an actual parameter list is:

expression or variable, expression or variable, ...

A method’s formal parameter list can be empty, but the parentheses are still needed. If the formal parameter list is empty in a method call, the actual parameter list is also empty.

In a method call, the number of actual parameters, together with their data types, must match the formal parameters in the order given.

Teaching Tip

A static method cannot call a nonstatic method of the class.


return Statement

A value-returning method uses a return(s) statement to return its value;


Syntax: return Statement

The return statement has the following syntax:

return expr;

where expr is a variable, constant value, or expression. The expr is evaluated and its value is returned. The data type of the value that expr computes should be compatible with the return type of the method.

When a return statement executes in a method, the method immediately terminates and control goes back to the caller.


Final Program

You can put methods within a class in any order.

A value-returning method must return a value.


Programming Example: Palindrome Number

An integer is a palindrome if it reads backwards and forwards the same way.

The input to this program is an integer (positive or negative).  The output to this program is a message indicating whether the integer is a palindrome.

The solution to this program consists of writing a method isPalindrome.  The method returns a Boolean value.  Its only parameter is the integer string that needs to be checked.  The body of the method gets the length of the string and using a for loop compares the first half of the string to the last half one character at a time.  If the first and last character don’t match the method returns false. Otherwise, it increments the position of the first character being checked and decrements the position of the last character checked and compares them.  This is done until the characters no longer match.  If they match till the end of the loop the method returns true.


Flow of Execution

When the program executes, the execution always begins with the first statement in the method main.  User-defined methods execute only when they are called.  A call to a method transfers control from the caller to the called method.  In a method call statement, you specify only the actual parameters, not their data type or the method type.  When a method exits, the control goes back to the caller.


Programming Example: Largest Number

The input to this program is a set of 10 numbers and the output is the largest of the numbers. The program can be easily modified to accommodate any set of numbers. 



The solution to this program consists of writing a method that compares two numbers and returns the larger of the two.  This method is then called in a for loop in the main method of the program.  The first number entered is stored as the maximum, and as each new number is entered it is compared to the current maximum.  The maximum is then replaced if the new number is larger than the current maximum.


Void Methods

Void methods do not have a data type.  Because a void method does not have a data type, returnType in the heading part and the return statement in the body of the void method are meaningless. However, in a void method, you can use the return statement without any value; it is typically used to exit the method early.

Because void methods do not have a data type, they are not used in an expression. A call to a void method is a stand-alone statement.


Void Methods without Parameters


Method Definition

The general form (syntax) of a void method without parameters is as follows:

modifier(s) void methodName()
{
statements
}


Method Call (Within the Class)

A method call has the following syntax:

methodName();

Because these methods do not have parameters, within a class such methods are usually good for displaying information about the program or for printing statements.


Void Methods with Parameters

Parameters provide a communication link between the calling method and the called method. They enable methods to manipulate different data each time they are called.


Method Definition

The definition of a void method with parameters has the following syntax:

modifier(s) void methodName(formal parameter list)
{
statements
}


Formal Parameter List

A formal parameter list has the following syntax:

dataType variable, dataType variable, ...


Method Call

A method call has the following syntax:

methodName(actual parameter list);


Actual Parameter List

An actual parameter list has the following syntax:

expression or variable, expression or variable, ...

As with value-returning methods, in a method call the number of actual parameters, together with their data types, must match the formal parameters in the order given.


Primitive Data Type Variables as Parameters

When a method is called, the value of the actual parameter is copied into the corresponding formal parameter. If a formal parameter is a variable of a primitive data type, then after copying the value of the actual parameter, there is no connection between the formal parameter and the actual parameter; a formal parameter of the primitive type cannot pass any result back to the calling method. When the method executes, any changes made to the formal parameters do not in any way affect the actual parameters. The actual parameter has no knowledge of what is happening to the formal parameter. Thus, formal parameters of the primitive data types cannot pass information outside the method. Formal parameters of the primitive data types provide only a one-way link between actual parameters and formal parameters.


Reference Variables as Parameters

A reference variable contains the address (memory location) of the actual data; both the formal and the value parameters refer to the same object. Therefore, reference variables can pass one or more values from a method and can change the value of the actual parameter.

Reference variables, as parameters are useful in three situations:

  1. When you want to return more than one value from a method

  1. When the value of the actual object needs to be changed

  1. When passing the address would save memory space and time, relative to copying a large amount of data


Parameters and Memory Allocation

When a method is called, memory for its formal parameters and variables declared in the body of the method, called local variables, is allocated in the method data area. The value of the actual parameter is copied into the memory cell of its corresponding formal parameter. If the parameter is an object (of a class type), both the actual parameter and the formal parameter refer to the same memory space.




Reference Variables of the String Type as Parameters: A Precaution

In the case of reference variables of the type String, we can use the assignment operator to allocate memory space to store a string and assign the string to a String variable.  If you pass a String variable (a reference variable of the String type) as a parameter to a method, and within the method you use the assignment operator to change the string, the string assigned to the actual parameter does not change; a new string is assigned to the formal parameter.

Teaching Tip

Illustrate the above concept with the example and figures on pages 396-400 in the test, or a similar example with illustrations.


class StringBuffer

If you want to pass strings as parameters to a method and want to change the actual parameter, you can use the class StringBuffer, where strings assigned to StringBuffer variables can be altered using various methods provided to manipulate strings (e.g. append, delete).


Scope of an Identifier Within a Class

The scope of an identifier refers to what other parts of the program can “see” an identifier; where it is accessible (visible).

A local identifier is an identifier declared within a method or block that can be accessed only by code within that same method or block.  Java does not allow the nesting of methods. That is, you cannot include the definition of one method in the body of another method.

The following should be noted:

  • Java does not allow the nesting of methods.

  • Within a method or a block, an identifier must be declared before it can be used. Note that a block is a set of statements enclosed within braces. A method’s definition can contain several blocks. The body of a loop or an if statement also forms a block.


  • Within a class, outside every method definition (and every block), an identifier can be declared anywhere.

  • Within a method, an identifier used to name a variable in the outer block of the method cannot be used to name any other variable in an inner block of the method.

The following are scope rules of an identifier declared within a class and accessed within a method (block) of the class.

  • An identifier, say x, declared within a method (block) is accessible:

    • Only within the block from the point at which it is declared until the end of the block.

    • By those blocks that are nested within that block.

  • Suppose x is an identifier declared within a class and outside every method’s definition (block).

    • If x is declared without the reserved word static (such as a named constant or a method name), then it cannot be accessed within a static method.

    • If x is declared with the reserved word static (such as a named constant or a method name), then it can be accessed within a method (block), provided the method (block) does not have any other identifier named x.


Method Overloading: An Introduction

Method overloading is creating several methods, within a class, with the same name. 

Two methods are said to have different formal parameter lists if both methods have:

  • A different number of formal parameters, or

  • If the number of formal parameters is the same, then the data type of the formal parameters, in the order you list, must differ in at least one position.

To overload a method name, within a class, any two definitions of the method must have different formal parameter lists.

The signature of a method consists of the method name and its formal parameter list. Two methods have different signatures if they have either different names or different formal parameter lists.

If a method is overloaded, then in a call to that method the signature, that is, the formal parameter list of the method, determines which method to execute.

Teaching Tip

Detailed formal descriptions of Java’s scoping and overloading rules can be found in the Java Language Specification:


Key Terms

Ø      Actual parameter: a variable or expression listed in a call to a method.
Ø      Class libraries: organized collection of classes.
Ø      Formal parameter: a variable declared in the method heading.
Ø      Local identifier: an identifier declared within a method or block that can be accessed only by code within that same method or block.
Ø      Local variables: variables declared in the body of the method.
Ø      Method type: data type of the value returned by the method.
Ø      Modules: another name for methods.
Ø      Palindrome: integer or string that reads the same forwards and backwards.
Ø      Parameters: arguments of a method.
Ø      Predefined methods: methods that are already written and provided by Java.
Ø      Scope: refers to what other parts of the program can “see” an identifier.
Ø      User-defined methods: methods that the programmer creates.
Ø      Value-returning methods: methods that have a return type.


Void methods: methods that do not have a return type.





Do you want to know the secrets of Java Programming and use it for the advancement of your career in IT? Do you have problems in your Java course? Here is an instant solution for your problem. Avail the Java training package of Prof Erwin Globio and get free tips about Java Programming Secrets. For more free information about Java and Java Training visit the following sites:http://erwinglobio.sulit.com.ph/ http://erwinglobio.multiply.com/http://erwinglobio.wordpress.com/. You may contact the Java Trainer at 09393741359 or 09323956678. Call now and be one of the Java Experts.






4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Your design and pics of the blog is really nice. More over the content is also very productive. Information you have provided is really very beneficial.and keep posting about java training in noida
    .
    Thanks..

    ReplyDelete
  4. Nice Blog I need to read more on this topic...I admiring time and effort you put in your blog.

    Java Training In Noida

    ReplyDelete