Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Similar documents
Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 6 Methods. Dr. Hikmat Jaber

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

Chapter 5 Methods / Functions

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

CS110: PROGRAMMING LANGUAGE I

CS115 Principles of Computer Science

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Lecture 5: Methods CS2301

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

JAVA Programming Concepts

Benefits of Methods. Chapter 5 Methods

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Chapter 4 Mathematical Functions, Characters, and Strings

Methods. CSE 114, Computer Science 1 Stony Brook University

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Lecture #6-7 Methods

CS-201 Introduction to Programming with Java

CS1150 Principles of Computer Science Methods

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

CS1150 Principles of Computer Science Methods

CS-201 Introduction to Programming with Java

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Chapter 4. Mathematical Functions, Characters, and Strings

int sum = 0; for (int i = 1; i <= 10; i++) sum += i; System.out.println("Sum from 1 to 10 is " + sum);

Advanced Computer Programming

Methods. Eng. Mohammed Abdualal

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Module 4: Characters, Strings, and Mathematical Functions

Expressions and operators

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. and Java. Chapter 2 Primitive Data Types and Operations

AP CS Unit 3: Control Structures Notes

Lecture 2:- Functions. Introduction

DUBLIN CITY UNIVERSITY

Primitive Data Types: Intro

Top-down programming design

1.1 Your First Program

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Introduction to Computer Science Unit 2. Notes

DUBLIN CITY UNIVERSITY

Introduction to Computer Science Unit 2. Notes

1.1 Your First Program

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

Expanded Guidelines on Programming Style and Documentation

A Foundation for Programming

The Math Class. Using various math class methods. Formatting the values.

Using Free Functions

Java, Arrays and Functions Recap. CSE260, Computer Science B: Honors Stony Brook University

CT 229 Java Syntax Continued

M e t h o d s a n d P a r a m e t e r s

1.1 Your First Program! Naive ideal. Natural language instructions.

Lecture 1 Java SE Programming

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Supplement D: Expanded Guidelines on Programming Style and Documentation

Recapitulate CSE160: Java basics, types, statements, arrays and methods

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Programmierpraktikum

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Methods CSC 121 Spring 2017 Howard Rosenthal

Methods CSC 121 Fall 2016 Howard Rosenthal

Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Object Oriented Methods : Deeper Look Lecture Three

1.1 Your First Program

Classes. Classes as Code Libraries. Classes as Data Structures. Classes/Objects/Interfaces (Savitch, Various Chapters)

1.1 Your First Program

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Advanced Object Concepts

CS110D: PROGRAMMING LANGUAGE I

CS313D: ADVANCED PROGRAMMING LANGUAGE

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

Formatting Output & Enumerated Types & Wrapper Classes

Classes. Classes as Code Libraries. Classes as Data Structures

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Using Java Classes Fall 2018 Margaret Reid-Miller

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

1.1 Your First Program

Methods CSC 121 Fall 2014 Howard Rosenthal

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

Chapter 4 Mathematical Functions, Characters, and Strings

CONDITIONAL EXECUTION

x++ vs. ++x x=y++ x=++y x=0; a=++x; b=x++; What are the values of a, b, and x?

Transcription:

Chapter 5 Methods Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection Statements Chapter 4 Loops Chapter 5 Methods 19.1-19.3 in Chapter 19 Recursion Chapter 6 Arrays Chapter 23 Algorithm Efficiency and Sorting 1

Objectives To declare methods, invoke methods, and pass arguments to a method ( 5.2-5.4). To use method overloading and know ambiguous overloading ( 5.5). To determine the scope of local variables ( 5.6). To know how to use the methods in the Math class ( 5.8). To group classes into packages ( 5.11 Optional). 2

Introducing Methods A method is a collection of statements that are grouped together to perform an operation. Define a method Invoke a method method header method body modifier return value type method name formal parameters public static int max(int num1, int num2) { int result; parameter list if (num1 > num2) result = num1; else result = num2; return value return result; int z = max(x, y); actual parameters (arguments) 3

Introducing Methods, cont. Method signature is the combination of the method name and the parameter list. The variables defined in the method header are known as formal parameters. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. 4

Introducing Methods, cont. A method may return a value. The returnvaluetype is the data type of the value the method returns. If the method does not return a value, the returnvaluetype is the keyword void. For example, the returnvaluetype in the main method is void. 5

animation Calling Methods, cont. pass the value of i pass the value of j public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; public class TestMax{ public static void main(string [] args){ public static int max(int num1, int num2) { This program demonstrates calling a method max to return the largest of the int values TestMax 6

Call Stacks Space required for the main method k: j: 2 i: 5 Space required for the max method result: 5 num2: 2 num1: 5 Space required for the main method k: j: 2 i 5 Space required for the main method k: 5 j: 2 i: 5 i: 5 Stack is empty The main method The max method is The max method is is invoked. invoked. finished i and the return value is sent to k. The main method is finished. i Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 7

animation Trace Call Stack i is declared and initialized public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; i: 5 if (num1 > num2) result = num1; else result = num2; The main method is invoked. return result; Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 8

animation Trace Call Stack j is declared and initialized public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; The main method is invoked. j: 2 i: 5 return result; Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 9

animation Trace Call Stack Declare k public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); Space required for the public static int max(int num1, int num2) { int result; main method k: j: 2 i: 5 if (num1 > num2) result = num1; else result = num2; The main method is invoked. return result; Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 10

animation Trace Call Stack Invoke max(i, j) public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); Space required for the public static int max(int num1, int num2) { int result; main method k: j: 2 i: 5 if (num1 > num2) result = num1; else result = num2; The main method is invoked. return result; Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 11

animation Trace Call Stack pass the values of i and j to num1 and num2 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 return result; The max method is invoked. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 12

animation Trace Call Stack pass the values of i and j to num1 and num2 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; result: num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 return result; The max method is invoked. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 13

animation Trace Call Stack (num1 > num2) istrue public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; result: num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 return result; The max method is invoked. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 14

animation Trace Call Stack Assign num1 to result public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; Space required for the max method result: 5 num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 return result; The max method is invoked. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 15

animation Trace Call Stack Return result and assign it to k public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; Space required for the max method result: 5 num2: 2 num1: 5 Space required for the main method k:5 j: 2 i: 5 return result; The max method is invoked. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 16

animation Trace Call Stack Execute print statement public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); Space required for the public static int max(int num1, int num2) { int result; main method k:5 j: 2 i: 5 if (num1 > num2) result = num1; else result = num2; The main method is invoked. return result; Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 17

CAUTION A return statement is required for a nonvoid 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 sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return 1; //compile error should be public static int sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else return 1; To fix this problem, delete if (n<0) in the code. ในเมธอดแบบ void ม statement return ได หร อไม? 18

Void method with return public class Test { public static void main(string[] args) { int num= TestMax.max(2,20); System.out.println(num); printgrade(-78.5); public static void printgrade(double score) { if (score < 0 score > 100){ System.out.println("Invalid score"); return; if (score>=90.0) System.out.println("A"); else if (score >=80.0) System.out.println("B"); else if (score >=70.0) 0) System.out.println( println("c"); else if (score >=60.0) System.out.println("D"); else System.out.println("F"); Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 19

Reuse Methods from Other Classes NOTE: One of the benefits of methods is for reuse. The max method can be invoked from any class besides TestMax. If you create a new class Test, you can invoke the max method using ClassName.methodName() e.g., TestMax.max() public class TestMax{ public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; public class Test{ public static void main (String [] args){ int num = TestMax.max(2,20); System.out.println(num); 20

Passing Parameters public static void nprintln(int m, int n) { for (int i = 0; i < n; i++) System.out.println(m); Suppose you invoke the method using nprintln(5, 5); What is the output? Suppose you invoke the method using nprintln(15, Computer Science ); What is the output? Suppose you invoke the method using nprintln(15, 6, 5.6); What is the output? The arguments must match the parameter in order, number, and compatible type as defined in the method signature --int to double is ok. 21

public class TestPassByValue { /** Main method */ public static void main(string[] args) { // Declare and initialize variables int num1 = 1; int num2 = 2; System.out.println("Before invoking the swap method, num1 is " + num1 + " and num2 is " + num2); // Invoke the swap method to attempt to swap two variables swap(num1, num2); System.out.println("After invoking the swap method, num1 is " + num1 + " and num2 is " + num2); /** Swap two variables */ public static void swap(int n1, int n2) { // Swap n1 with n2 int temp = n1; n1 = n2; n2 = temp; System.out.println("\t\tAfter swapping n1 is " + n1 + " n2 is " + n2); 1 pass-by-value 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 TestPassByValue 22

Pass by Value, cont. The values of num1 and num2 are passed to n1 and n2. Executing swap does not affect num1 and num2. Space required for the swap method temp: n2: 2 n1: 1 Space required for the main method num2: 2 num1: 1 Space required for the main method num2: 2 num1: 1 Space required for the main method num2: 2 num1: 1 Stack is empty The main method The swap method The swap method The main method is invoked is invoked is finished is finished Primitive type เป นแบบ เปนแบบ pass-by-value 23

Overloading Methods Two methods have the same name but different parameter lists within one class. Order, number, data type Overload method must thave different parameter lists and cannot overload methods based on different modifiers or return types //Listing 5.3 Overloading the max Method public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; public static ti void m(int n, double d ) { public static void m(double d, int n){ public static int m(double d, int m){//no TestMethodOverloading ComputeTaxWithMethod 24

Ambiguous Invocation Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error. 25

Ambiguous Invocation: compile error 1 public class AmbiguousOverloading { 2 public static void main(string[] args) { 3 System.out.println(max(1, 2)); 4 5 6 public static ti double max(int num1, double num2) { 7 if (num1 > num2) 8 return num1; 9 else 10 return rn num2; 11 12 13 public static double max(double num1, int num2) { 14 if (num1 > num2) 15 16 17 18 19 20 return num1; else return num2; max(1, 5.6); max(6.7, 2); 26

Scope of Local Variables A local variable: a variable defined inside a method. Scope: the part of the program where the variable can be referenced. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used. 27

Scope of Local Variables, cont. You can declare a local variable with the same name multiple times in different nonnesting blocks in a method, but you cannot declare a local variable twice in nested blocks. for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) { for (int i = 0; ; i < 10; ; j++) { 28

Scope of Local Variables, cont. A variable declared in the initial action part of a for loop header has its scope in the entire loop. Bt But a variable ibl declared dinside id 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. The scope of i The scope of j public static void method1() {.. for (int i = 1; i < 10; i++) {.. int j;... 29

Scope of Local Variables, cont. It is fine to declare i in two non-nesting blocks public static void method1() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { x += i; for (int i = 1; i < 10; i++) { y += i; It is wrong to declare i in two nesting blocks public static void method2() { int i = 1; int sum = 0; for (int i = 1; i < 10; i++) sum += i; 30

Scope of Local Variables, cont. // With errors public static ti void incorrectmethod() th { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { int x = 0;//error x += i; 31

Class constants: PI E Class methods: The Math Class Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods 32

View java.lang.math Documentation You can view the complete documentation for the Math class online from http://www.oracle.com. 33

Eclipse Optional How to Set JavaDoc in Eclipse 1.Window Preference 2.แล วเล อก jre6 ป ม Edit 3.เล อกไฟล 3.เลอกไฟล rt.jar กดป ม กดป ม Javadoc Location 4. Browse ไปท directory ท ไฟล javadoc นามสก ล.zip และ browse ไปท path docs/api 34

Trigonometric Methods sin(double a) cos(double a) tan(double a) acos(double a) asin(double a) atan(double a) Examples: Math.sin(0) returns 0.0 Math.sin(Math.PI / 6) returns 0.5 Math.sin(Math.PI / 2) returns 1.0 Math.cos(0) returns 1.0 Math.cos(Math.PI / 6) returns 0.866 Math.cos(Math.PI / 2) returns 0 ส งเกตการใช งาน 35

Exponent Methods exp(double a) Examples: Returns e raised to the power of a. log(double a) Returns the natural logarithm of a. log10(double a) Returns the 10-based logarithm of a. pow(double a, double b) Returns a raised to the power of b. Math.exp(1) returns 2.71 Math.log(2.71) returns 1.0 Math.pow(2, 3) returns 8.0 Math.pow(3, 2) returns 9.0 Math.pow(3.5, 2.5) returns 22.91765 Math.sqrt(4) returns 2.0 Math.sqrt(10.5) returns 3.24 sqrt(double a) Returns the square root of a. ส งเกตการใช งาน 36

Rounding Methods static double ceil(double x) x rounded up to its nearest integer. This integer is returned as a double value. static double floor(double x) x is rounded down to its nearest integer. This integer is returned as a double value. double rint(double x) x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double. int round(float x) Return (int)math.floor(x+0.5). long round(double x) Return (long)math.floor(x+0.5). 37

min, max, and abs max(a, b)and min(a, b) Returns the maximum or minimum of two parameters. abs(a) Returns the absolute value of the parameter. random() Returns a random double value in the range [0.0, 1.0). Examples: Math.max(2, 3) returns 3 Math.max(2.5, 3) returns 3.0 Math.min(2.5, 3.6) returns 2.5 Math.abs( abs(-2) returns 2 Math.abs(-2.1) returns 2.1 ส งเกตการใช งาน 38

The random Method Generates a random double value greater than or equal to 0.0 and less than 1.0 (0 <= Math.random() < 1.0). double ran = Math.random() *1.0; Examples: (int)(math.random() * 10) 50 + (int)(math.random() * 50) Returns a random integer between 0 and 9. Returns a random integer between 50 and 99. In general, a + Math.random() * b Returns a random number between a and a + b, excluding a + b. 39

Optional Package There are three reasons for using packages: 1. To avoid naming conflicts. When you develop reusable classes to be shared by other programmers, naming conflicts often occur. To prevent this, put your classes into packages so that they can be referenced through package names. 2. To distribute software conveniently. Packages group related classes so that they can be easily distributed. 3. To protect classes. Packages provide protection so that the protected members of the classes are accessible to the classes in the same package, but not to the external classes. 40

Java Platform, Standard Edition 6 API Specification System, String java.lang JOptionPane javax.swing import import javax.swing. JOptionPane; import javax.swing.*; java.lang ไม ต อง import Demo with Java API 41

Package-Naming Conventions Packages are hierarchical, and you can have packages within packages. For example, java.lang.math indicates that Math is a class in the package lang and that lang is a package in the package java. Levels of nesting can be used to ensure the uniqueness of package names. Choosing a unique name is important because your package may be used on the Internet by other programs. Java designers recommend that you use your Internet domain name in reverse order as a package prefix. Since Internet domain names are unique, this prevents naming conflicts. Suppose you want to create a package named mypackage on a host machine with the Internet domain name prenhall.com. To follow the naming convention, you would name the entire package com.prenhall.mypackage. By convention, package names are all in lowercase. 42

Package Directories Java expects one-to-one mapping of the package name and the file system directory structure. For the package named com.prenhall.mypackage, you must create a directory, as shown in the figure. In other words, a package is actually a directory that contains the bytecode of the classes. com.prenhall.mypackage hll Format.class 43

Putting Classes into Packages Every class in Java belongs to a package. The class is added to the package when it is compiled. All the classes that you have used so far in this book were placed in the current directory (a default package) when the Java source programs were compiled. To put a class in a specific package, you need to add the following line as the first statement in the program: package packagename; Ex.. package mylib; public class A{ เวลาใช งานโดยคลาสอ นๆ import mylib.a; public class Test{.. temp mylib A.class 44

Listing 5.8 Putting Classes into Packages Problem This example creates a class named Format and places it in the package com.prenhall.mypackage. The Format class contains the format(number, numofdecimaldigits) method that returns a new number with the specified number of digits after the decimal point. For example, format(10.3422345, 2) returns 10.34, and format(-0.343434, 3) returns 0.343. Solution 1. Create Format.java as follows and save it into c:\book\com\prenhall\mypackage. // Format.java: Format number. //ช อไฟล ช อเด ยวก บคลาสท เป น public package com.prenhall.mypackage; public class Format { public static double format( double number, int numofdecimaldigits) { return Math.round(number * Math.pow(10, numofdecimaldigits)) / Math.pow(10, numofdecimaldigits); 2. Compile Format.java. Make sure Format.class is in c:\book\com\prenhall\mypackage. -c:\book>javac Format.java :หล งจากน นสร างไดเรกทอร ตามช อ package แล วย ายไฟล ไปใส เอง -c:\book>javac Format.java d. :สร างไดเรกทอร ตามช อ :สรางไดเรกทอรตามชอ package ให อ ตโนม ต ใหอตโนมต ตอจากไดเรกทอรปจจ บน ต อจากไดเรกทอร ป จจบ น 45

Setting classpath Environment Format.class The com directory does not thave to be the root tdirectory. In order for Java to know where your package is in the file system, you must modify the environment variable classpath so that it points to the directory in which your package resides. Suppose the com directory is under c:\book. The following line adds c:\book into the classpath: classpath=.;c:\book; The period (.) indicating the current directory is always in classpath. The directory c:\book is in classpath so that you can use the package com.prenhall.mypackage in the program. 46

Using Classes from Packages There are two ways to use classes from a package. One way is to use the fully qualified name of the class. For example, the fully qualified name for JOptionPane is javax.swing.joptionpane., For Format in the preceding example, it is com.prenhall.mypackage.format. This is convenient if the class is used a few times in the program. The other way is to use the import statement. For example, to import all the classes in the javax.swing package, you can use import javax.swing.*; An import that uses a * is called an import on demand declaration. You can also import a specific class. For example, this statement imports javax.swing.joptionpane: import javax.swing.joptionpane; The information for the classes in an imported package is not read in at compile time or runtime unless the class is used in the program. The import statement simply tells the compiler where to locate the classes. 47

Listing 5.9 Using Packages Problem This example shows a program that uses the Format class in the com.prenhall.mypackage.mypackage package. Solution 1. Create TestFormatClass.java as follows and save it into c:\book. The following code gives the solution to the problem. // TestFormatClass.java: Demonstrate using the Format class import com.prenhall.mypackage.format; public class TestFormatClass tcl { /** Main method */ public static void main(string[] args) { System.out.println(Format.format(10.3422345, ( 2)); System.out.println(Format.format(-0.343434, 3)); 48