Lecture 3 - Java Programming - Methods
Lecture 3 - Java Programming - Methods
Topics
▪ Introduction
▪ Static Methods, Static Fields and Class Math
▪ Declaring a method with more than one parameter.
▪ Java API Packages
▪ Case Study: Random-Number Generation
▪ Method Overloading
1- Introduction
Experience has shown that the best way to develop and maintain a large program is to
construct
it from small, simple pieces, or modules. This technique is called divide and conquer. Methods
are used to facilitate the design, implementation, operation and maintenance of large
programs.
▪ Static methods.
▪ How to declare a method with more than one parameter.
▪ How local variables of methods are maintained in memory.
▪ How a method knows where to return after it completes execution.
▪ Methods overloading
To declare a method as static, the keyword static is placed before the return type in the
method’s declaration. For any class imported in the program, it is possible to call the class’s
static methods by specifying the name of the class in which the method is declared, followed
by a dot (.) and the method name, as follows:
Class Name . Method Name ( arguments )
Class Math provides a collection of methods that perform common mathematical calculations.
For example, to calculate the square root of 900.0 with the static method call, the following
statement is used.
Math.sqrt ( 900.0 )
The preceding expression evaluates to 30.0. Method sqrt takes an argument of type double
and returns a result of type double. To output the value of the preceding method call in the
command window, the following statement is written:
System.out.println ( Math.sqrt ( 900.0 ) ) ;
Static Fields:
Class Math declares two fields that represent commonly used mathematical constants Math.PI
and Math.E.
Math.PI is the ratio of a circle’s circumference to its diameter.
Math.E. is the base value for natural logarithms.
These fields are declared in class Math with the modifiers “public”, “final” and static” .
There are fields for which each object of a class does not have a separate instance of the field.
That’s the case with static fields, which are also known as class variables.
Note: In case of creation of objects for a class containing static fields, the objects of that class
share one copy of the class’s static fields. Together the class variables (i.e., static variables) and
instance variables represent the fields of a class.
3- Declaring a method with more than one parameter.
Methods often require more than one piece of information to perform their tasks. This section
considers how to write a method with multiple parameters. Listing 1 uses a method called
“maximum” to determine and return the largest of three double values.
Listing 1
1 import java.util.Scanner;
2
3 public class MaximumFinder
4 {
5 // obtain three floating-point values and locate the maximum value
6 public static void main( String[ ] args )
7 {
8 // create Scanner for input from command window
9
10 Scanner input = new Scanner( System.in );
11
12 // prompt for and input three floating-point values
13 System.out.print(“Enter three floating-point values separated by spaces: " );
14 double number1 = input.nextDouble( ); // read first double
15 double number2 = input.nextDouble( ); // read second double
16 double number3 = input.nextDouble( ); // read third double
17 // determine the maximum value
18 double result = maximum( number1, number2, number3 );
19 // display maximum value
20 System.out.println( "Maximum is: " + result ) ;
21 } // end main
22 // returns the maximum of its three double parameters
23 public static double maximum( double x, double y, double z )
24 {
25 double maximumValue = x; // assume x is the largest to start
26 // determine whether y is greater than maximumValue
27 if ( y > maximumValue )
28 maximumValue = y;
29 // determine whether z is greater than maximumValue
30 if ( z > maximumValue )
31 maximumValue = z;
32 return maximumValue;
33 } / / end method maximum
34 } // end class MaximumFinder
The first call to Math.max specifies arguments x and Math.max( y, z ). Before any method can
be called, its arguments must be evaluated to determine their values. If an argument is a
method call, the method call must be performed to determine its return value.
4- Java API Packages
Java contains many predefined classes that are grouped into categories of related classes
called packages. Together, these are known as the Java Application Programming Interface
(Java API), or the Java class library.
A great strength of Java is the Java API’s thousands of classes. Some key Java API packages are
described in the following:
Package Description
java.applet The Java Applet Package contains a class and several interfaces required to create Java applets
are programs that execute in web browsers.
The Java Abstract Window Toolkit Package contains the classes and interfaces required to
java.awt create and manipulate GUIs in early versions of Java. In current versions, the Swing GUI
components of the javax.swing packages are typically used instead
java.awt.event The Java Abstract Window Toolkit Event Package contains classes and interfaces that enable
event handling for GUI components in both the java.awt and javax.swing p
ackages.
java.awt.geom The Java 2D Shapes Package contains classes and interfaces for working
with Java’s advanced two-dimensional graphics capabilities.
java.io The Java Input/Output Package contains classes and interfaces that
enable programs to input and output data.
java.net The Java Networking Package contains classes and interfaces that
enable programs to communicate via computer networks like the Internet.
The Java Utilities Package contains utility classes and interfaces that enable such actions as date
java.util and time manipulations, random-number processing (class Random) and the storing and
processing of large amounts of data.
java.util. The Java Concurrency Package contains utility classes and interfaces for implementing
programs that can perform multiple tasks in parallel.
concurrent
The Java Media Framework Package contains classes and interfaces for working with Java’s
javax.media multimedia capabilities.
The Java Swing GUI Components Package contains classes and interfaces
javax.swing for Java’s Swing GUI components that provide support for portable GUIs.
javax. The Java Swing Event Package contains classes and interfaces that
enable event handling for GUI components in package javax.swing.
swing.event
javax.xml.ws The JAX-WS Package contains classes and interfaces for working with web services in Java.
5- Case Study: Random-Number Generation
Generally, two main methods can be used to get random numbers in Java, the first and most
direct approach is to use the static “random ( )” method from the “math” class. However, this
can produce only double values in the range 0.0 ≤ x < 1.0, where x i s the value returned by
method random.
The second approach is to use the “class Random” and by creating object of this class to
invoke methods for generating random numbers of different types.
Objects of class Random can produce random boolean, byte, float, double, int, long and
Gaussian values.
A new random-number generator object can be created as follows:
Random randomNumbers = new Random( );
The following code shows how create random integer using the object of Random class.
int random_Value = randomNumbers.nextInt( );
Random method nextInt generates a random int value in the range –2,147,483,648 to
+2,147,483,647, inclusive. If it truly produces values at random, then every value in the range
should have an equal chance (or probability) of being chosen each time nextInt is called.
The range of values produced directly by method nextInt generally differs from the range of
values required in a particular Java application. For example, a program that simulates coin
tossing might require only 0 for “heads” and 1 for “tails.” A program that simulates the rolling
of a six-sided die might require random integers in the range 1–6.
For cases like these, class Random provides another version of method nextInt that receives
an int argument and returns a value from 0 up to, but not including, the argument’s value. For
example, for coin tossing, the following statement returns 0 or 1.
Six-sided dice has the numbers 1–6 on its faces, not 0–5. So, the range of numbers produced is
shifted by adding a shifting value, in this case 1—to the previous result:
face = 1 + randomNumbers.nextInt( 6 ) ;
The shifting value (1) specifies the first v alue in the desired range of random integers. The
preceding statement assigns face a random integer in the range 1–6.
The code in listing 2 shows the generation of random numbers by exploiting the notions
discussed above:
Listing 2 Random_Integers.java
1 import java.util.Random; // program uses class Random
2
3 public class RandomIntegers
4 {
5 public static void main( String[ ] args )
6 {
7 Random randomNumbers = new Random( ); // random number
generator
8 int face; // stores each random integer generated
9
10 for ( int counter = 1; counter <= 20; counter++ )
11 {
12 // pick random integer from 1 to 6
13 face = 1 + randomNumbers.nextInt( 6 );
14
15 System.out.printf( "%d ", face ) ; // display generated value
17 if ( counter % 5 == 0 )
18 System.out.println( );
19 } // end for
20 } // end main
21} // end class RandomIntegers
Listing 3. RollDice.java
1 import java.util.Random ;
2 public class RollDice
3 {
4 public static void main( String[ ] args )
5 {
6 Random randomNumbers = new Random( ); // random number generator
7 int frequency1 = 0; // count of 1s rolled
8 int frequency2 = 0; rolled
// count of 2nd
9 int frequency3 = 0; rolled
// count of 3rd
10 int frequency4 = 0; // count of 4th rolled
11 int frequency5 = 0; // count of 5th rolled
12 int frequency6 = 0; // count of 6th rolled
13 int face; // most recently rolled value
14 for ( int roll = 1; roll <= 3000000; roll++ )
15 {
16 face = 1 + randomNumbers.nextInt( 6 ); // number from 1 to 6
17 switch(face)
18 {
19 case 1:
20 ++frequency1; break; // increment the 1s counter
21 case 2:
22 ++frequency2; counter
break; // increment the 2nd
23 case 3:
24 ++frequency3; counter
break; // increment the 3rd
25 case 4:
26 ++frequency4; counter
break; // increment the 4th
27 case 5:
28 ++frequency5; counter
break; // increment the 5th
29 case 6:
30 ++frequency6; counter
break; // increment the 6th
31 } // end switch
32 } // end for
33 System.out.println( "Face\tFrequency" ); // output headers
34 System.out.printf( "1\t%d\n 2\t%d\n 3\t%d\n 4\t%d\n 5\t%d\n 6\t%d\n",
35 frequency1, frequency2, frequency3, frequency4, frequency5,frequecy6);
36 } // end main
37} // end class RollDie
6- Method Overloading
Overloading of methods is declaration of methods of the same name in the same class as long
as they have different sets of parameters (determined by the number, types and order of the
parameters).
▪ When an overloaded method is called, the compiler selects the appropriate method by
examining the number, types and order of the arguments in the call.
▪ Method overloading is commonly used to create several methods with the same n ame
that perform the same or similar t asks, but on different types or different numbers o
f
arguments.
For example, Math methods abs, min and max are overloaded with four versions each:
Class MethodOverload in listing 4 includes two overloaded versions of “method square” one
that calculates the square of an int (and returns an int) and one that calculates the square of a
double (and returns a double).
Listing 4
1 public class MethodOverload
2{
3 public static void main( String[ ] args )
4 {
5 System.out.printf( "Square of integer 7 is %d\n", square( 7 ) );
6 System.out.printf( "Square of double 7.5 is %f\n", square( 7.5 ) );
7 } // end main
8 // square method with int argument
9 public static int square( int intValue )
10 {
11 System.out.printf( "\nCalled square with int argument: %d\n", intValue );