CST141 Java Class Library and Documentation Page 1

Similar documents
Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Lecture 5: Java Fundamentals III

CS 106 Introduction to Computer Science I

Computer Programming I

AP Computer Science Java Subset

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Java Interview Questions and Answers

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Chapter 2: Elements of Java

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Introduction to Java. CS 3: Computer Programming in Java

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

WRITING DATA TO A BINARY FILE

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

java Features Version April 19, 2013 by Thorsten Kracht

An Overview of Java. overview-1

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Introduction to Java Applets (Deitel chapter 3)

AP Computer Science Java Mr. Clausen Program 9A, 9B

Variables, Constants, and Data Types

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

CS 106 Introduction to Computer Science I

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Introduction to Java

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Object-Oriented Programming in Java

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

13 File Output and Input

Java Programming Fundamentals

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Java Application Developer Certificate Program Competencies

Pemrograman Dasar. Basic Elements Of Java

CS106A, Stanford Handout #38. Strings and Chars

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

6.1. Example: A Tip Calculator 6-1

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Using SQL Server Management Studio

CSE 308. Coding Conventions. Reference

Fundamentals of Java Programming

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

10 Java API, Exceptions, and Collections

Contents. 9-1 Copyright (c) N. Afshartous

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Basic Programming and PC Skills: Basic Programming and PC Skills:

Install Java Development Kit (JDK) 1.8

Java (12 Weeks) Introduction to Java Programming Language

Aras Corporation Aras Corporation. All rights reserved. Notice of Rights. Notice of Liability

Unit 6. Loop statements

Moving from CS 61A Scheme to CS 61B Java

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Java CPD (I) Frans Coenen Department of Computer Science

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Visual Basic Programming. An Introduction

First Bytes Programming Lab 2

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

CS506 Web Design and Development Solved Online Quiz No. 01

What s Wrong with This?

Chapter 3. Input and output. 3.1 The System class

8.1. Example: Visualizing Data

SQL Server An Overview

Software Development (CS2500)

3 Improving the Crab more sophisticated programming

Introduction to Java Lecture Notes. Ryan Dougherty

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

C++ INTERVIEW QUESTIONS

Chapter 2 Introduction to Java programming

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Table and field properties Tables and fields also have properties that you can set to control their characteristics or behavior.

C++ Language Tutorial

Specialized Programme on Web Application Development using Open Source Tools

LabVIEW Day 6: Saving Files and Making Sub vis

Windows PowerShell Essentials

What's New in ADP Reporting?

VB.NET Programming Fundamentals

Exercise 1: Python Language Basics

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

UML for C# Modeling Basics

Field Properties Quick Reference

Software documentation systems

Chapter 1 Java Program Design and Development

Text file I/O and simple GUI dialogues

Java Basics: Data Types, Variables, and Loops

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

CS 111 Classes I 1. Software Organization View to this point:

TATJA: A Test Automation Tool for Java Applets

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

Number Representation

Ohio University Computer Services Center August, 2002 Crystal Reports Introduction Quick Reference Guide

Excel: Introduction to Formulas

How to Install Java onto your system

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Transcription:

CST141 Java Library and Documentation Page 1 1 2 3 4 5 6 7 8 Java Library and Documentation CST141 The Java Library 1) The Java Library contains thousands of classes with tens of thousands of methods Makes programming much easier The competent Java programmer must be able to work with the libraries: Know the most important classes by name Be able to find out about other classes The Java Library 2) It is not necessary to view the code for library methods or see how they are implemented You just need to know the class name, understand its methods and what they do, as well as their parameters and return types This information is available by reading the on-line documentation for each class Programming in Teams Programmers working on large projects develop different parts of the application Just like with the Java class library, each developer does not need to understand details of every section Just the class methods and what they do, as well as the parameters and return types Team members must know how to write class documentation similar to Java s The Java API Application Programmers Interface documentation for the Java libraries written in HTML format and readable in a web browser Interface description for all library classes Can be found either: In the BlueJ Help menu by selecting the command Java Libraries ; or at http://download.oracle.com/javase/6/docs/api/index.html Interface vs. Implementation 1) The documentation (which is the interface of the class) includes: The name of the class A general description of the class A list of constructors and methods The return values and parameters for constructors and methods The description of the purpose of each constructor and method The constants and any other components Interface vs. Implementation 2) The documentation does not include the implementation of the class which includes: The private fields (most fields are private) Any public methods The bodies (source code) for each method

7 CST141 Java Library and Documentation Page 2 8 9 10 11 12 13 14 The JOptionPane 1) from the Java class library providing simple to use popup dialogs to prompt users for a value or to display information JOptionPane class can seem complex, but most methods are one-line calls to one of the four (4) showxxxdialog methods The JOptionPane 2) Two of the methods are: showinputdialog prompts for some input showmessagedialog tells the user about something that has happened Objects do not need to be instantiated for these methods (syntax uses the class name in place of an object name), i.e. input = JOptionPane.showInputDialog( "Tell me more..." ); The showmessagedialog Method 1) Displays output in a message dialog window The showmessagedialog is a method of the predefined JOptionPane class contained in the Java class library Alternative to println method which instead creates GUI (graphical user interface) output The showmessagedialog Method 2) Takes two required parameters: The first is the keyword null The second is the output object (String, etc.) JOptionPane.showMessageDialog(null, outputobject); JOptionPane.showMessageDialog(null, "Nice talking to you. Bye..."); The showmessagedialog Method 3) The third and fourth arguments are optional Third argument is a string displayed in the title bar of the dialog box Fourth argument is an int value representing the type of icon displayed in dialog box Use both (four, not three arguments) or neither (it is an overloaded method) The showmessagedialog Method 4) JOptionPane.showMessageDialog(null, outputobject, titlebarstring, messagedialogtype); JOptionPane.showMessageDialog(null, "Nice talking to you. Bye...", "DodgySoft Technical Support System", JOptionPane.INFORMATION_MESSAGE); The showmessagedialog Method 5) Java constant expressions that represent icons displayed in the dialog box

import JOptionPane.INFORMATION_MESSAGE); javax.swing.joptionpane; import statements come before class header The showmessagedialog Method 5) Example to import an entire package: Java import constant javax.swing.*; expressions that represent icons displayed in the dialog box JOptionPane.ERROR_MESSAGE Package JOptionPane.INFORMATION_MESSAGE Names Java JOptionPane.ERROR_MESSAGE JOptionPane.WARNING_MESSAGE classes located in API are organized into related groups called packages Each JOptionPane.INFORMATION_MESSAGE JOptionPane.QUESTION_MESSAGE piece of package name is actually a folder (directory) where class is located, i.e. JOptionPane.WARNING_MESSAGE JOptionPane.PLAIN_MESSAGE The JOptionPane class is located in the javax.swing package (folder) JOptionPane.QUESTION_MESSAGE (No icon is displayed) JOptionPane.PLAIN_MESSAGE import javax.swing.joptionpane; The (No import icon Statement is displayed) 1) The es A Partial import from Java Statement the Java Library class library Directory must Structure 1) be imported using an import statement es The Except showinputdialog classes from the from the Java class Method java.lang library package must 1) which are fundamental to the be imported using an import statement Accepts development Except String classes typed of Java from input programs the java.lang from users (i.e. System, package in a textbox String, which within Math, are fundamental the etc.) dialog window to the They The development showinputdialog then can be used like other classes from the current project of Java is programs a method (i.e. of the System, JOptionPane String, class Math, etc.) They import showinputdialog then can Statement be used Method like other classes 2) 2) from the current project The import only required Statement argument is a prompt 2) import packagename.name; A message displayed that tells the user what value should be keyed into the import textbox packagename.name; import javax.swing.joptionpane; The return value of the method is a String that is usually assigned to a variable import statements come before class header import javax.swing.joptionpane; Example to import entire package: JOptionPane.showInputDialog( import statements come before promptstring class header ); import javax.swing.*; to import an entire package: Package import input = javax.swing.*; Names JOptionPane.showInputDialog("That sounds interesting. Tell me more..."); Package Java Calendar classes Names located in API are organized 1) into related groups called packages Each piece of package name is actually a folder (directory) where class is located, i.e. Java Calendar classes located in API are organized into related groups called packages The JOptionPane class is located in 2) the javax.swing package (folder) Each piece of package name is actually a folder (directory) where class is located, i.e. Calendar The JOptionPane class is located in 3) the javax.swing package (folder) import javax.swing.joptionpane; Calendar 4) A Partial import javax.swing.joptionpane; Java Library Directory Structure Calendar 5) The showinputdialog Method 1) Calendar 6) Accepts String typed input from users in a textbox within the dialog window The Calendar showinputdialog is a method of the 7) JOptionPane class CST141 Java Library and Documentation Page 3 14 14 17 15 18 15 19 16 20 16 17 17 21 22 23 24 18 25 18 19 26 19 27 20 28 20 21 29 21 22 22 23 23 24 30 24 25 25 26 26 27 27 28 The Mini-Quiz showinputdialog No. 1 Method 2) The Create only a new required BlueJargument project named is a prompt joptionpane Create A message a new displayed class named that InAndOut tells the user what value should be keyed into the Declare textbox a private String field named mystring The In the return Constructor, value of assign the method an empty is a String string that to the is field usually assigned to a variable Write a void method named input() with a showinputdialog() with any promp that returns JOptionPane.showInputDialog( and assigns a string that promptstring is assigned to ); the String field Write a void method name output() with a showmessagedialog() that displays the contents input = JOptionPane.showInputDialog("That of that String variable sounds interesting. Tell me more..."); Calendar Wrapper es 1) Calendar Java s primitive data types (int, double, 2) boolean, char, etc.) are separate (different) from objects Calendar Normally not possible to insert them into 3) collections such as ArrayList Calendar Solution to this is wrapper classes, which 4) allow primitives to be treated like objects Wrapper es 2) Calendar 5) Wrapper classes exist for every primitive: Calendar I.e. Byte, Short, Integer, Long, Float, 6) Double, and Character Calendar A wrapper object is instantiated and then 7) can hold and manipulate a primitive value Mini-Quiz No. 1

Solution to this is wrapper classes, which allow primitives to be treated like objects CST141 Java Library and Documentation Page 4 30 30 31 31 32 32 33 33 34 34 35 36 35 37 36 37 Wrapper es 2) Wrapper classes exist for every primitive: I.e. Byte, Short, Integer, Long, Float, Double, and Character A wrapper object is instantiated and then can hold and manipulate a primitive value Wrapper classes exist for every primitive: Integer I.e. Byte, intobj Short, = new Integer, Integer(intVar); Long, Float, Double, and Character A wrapper object is instantiated and then can hold and manipulate a primitive value The Integer.parseInt Method A static method from wrapper class Integer that converts String values to int (integer) Integer intobj = new Integer(intVar); data type The Necessary Integer.parseInt because the Method showinputdialog function only returns String values A parseint static method is a method from of wrapper the Integer class class Integer that converts String values to int (integer) data type Necessary Integer.parseInt(String) because the showinputdialog function only returns String values parseint is a method of the Integer class int appointmentnumber = Integer.parseInt(stringNumber); Integer.parseInt(String) Other Parse Methods All Java wrapper classes (except Character) have static parse methods which can int appointmentnumber = Integer.parseInt(stringNumber); convert String format of a number to numeric value: Other Byte.parseByte(string) Parse Methods All Short.parseShort(string) Java wrapper classes (except Character) have static parse methods which can convert Integer.parseInt(string) String format of a number to numeric value: Byte.parseByte(string) Long.parseLong(string) Short.parseShort(string) Float.parseFloat(string) Integer.parseInt(string) Double.parseDouble(string) Long.parseLong(string) Return Values as Arguments to Another Method 1) Float.parseFloat(string) When the return value (result) of one method will serve as an argument to the next Double.parseDouble(string) method Return Rather Values than storing as Arguments the return to value Another in a separate Method variable 1) When A common the return programmer value (result) practice of to one insert method the entire will serve first as method an argument call into to the the next method argument parentheses of the second method Rather Return Values than storing as Arguments the return to value Another in a separate Method variable 2) A common programmer practice to insert the entire first method call into the Instead of: argument parentheses of the second method String stringnumber = Return JOptionPane.showInputDialog Values as Arguments to Another Method 2) Instead ("Enter of: appointment number"); String stringnumber = int JOptionPane.showInputDialog appointmentnumber = Integer.parseInt(stringNumber); ("Enter appointment number"); Rather: appointmentnumber = Integer.parseInt( = Integer.parseInt(stringNumber); JOptionPane.showInputDialog( Rather: "Enter appointment number") ); appointmentnumber = Integer.parseInt( JOptionPane.showInputDialog as Argument to Integer.parseInt JOptionPane.showInputDialog( JOptionPane.showInputDialog "Enter appointment number") as Argument ); to Integer.parseInt The JTextArea A GUI (graphical user interface) component which concatenates (joins) together multiple lines of text The accumulated text string then can be displayed inside a showmessagedialog() dialog window Found in the javax.swing package, i.e. import javax.swing.jtextarea;

The new object begins as a null string (assuming neither constructor that takes is CST141 Java 36 Library and Documentation Page 5 String is called) 37 jtextareaobject.append(text_elements); The message.append(date accumulated text string + "\t" then + appointment can be displayed + "\n"); inside a showmessagedialog() dialog window 40 Outputting a JTextArea Object Found in the javax.swing package, i.e. The import JTextArea javax.swing.jtextarea; object s content may be displayed in showmessagedialog method References the string to which object points 38 Declaring a JTextArea Object Optional JOptionPane.showMessageDialog(null, arguments determine size (in rows jtextareaobject); and columns of text) of the JTextArea object when it is displayed JOptionPane.showMessageDialog(null, message); JTextArea jtextareaobject = new JTextArea( [rows, cols] ); 41 Examples: Escape Sequences Special JTextArea character message sequences = new JTextArea(); within a string: JTextArea Begin with message a backslash = new (\) JTextArea(10, and 25); Modify the format of printed output 39 The Some append common Method escape sequences: Concatenates \n New more line (carriage text to end return of the and string line already feed) stored in the JTextArea object The \t newtab object begins as a null string (assuming neither constructor that takes is String \\ is Backslash called) (to print \ character) \" Double quote (to print the " character) jtextareaobject.append(text_elements); \unnnn A Unicode character as a hexadecimal value 42 Mini-Quiz message.append(date 2: The Random + "\t" + appointment 1) + "\n"); Create a new BlueJ project name random-practice 40 Outputting a JTextArea Object Create a new class named RandomInt The Find JTextArea the documentation object s content for the may Random be displayed class from in the showmessagedialog Java API website method Find References the documentation the string to for which the import object statement points and write the statement to import the class JOptionPane.showMessageDialog(null, import java.util.random; jtextareaobject); Find the documentation for the first constructor and write a statement to instantiate the JOptionPane.showMessageDialog(null, object rnd message); 41 Escape Random Sequences rnd = new Random(); 43 Special Mini-Quiz character 2: The Random sequences within a string: 2) Which Begin method with a is backslash used to generate (\) and random integers within a specific range? Modify nextint(int the format n) of printed output Some Write a common statement escape to return sequences: a random integer between zero (0) and 99, and assign it to \n a variable: New line (carriage return and line feed) \trandomint Tab= rnd.nextint(100); \\ Backslash (to print \ character) 44 CoinFlip 1) \" Double quote (to print the " character) 45 CoinFlip \unnnn A Unicode character as a hexadecimal 2) value 42 46 47 43 Random Objects instantiated from the Random class generate a stream of random (pseudorandom) numbers Format to instantiate object: Random randomobject = new Random(); Example to instantiate object Random rnd = new Random(); Found in the java.util package, i.e. import java.util.random; The nextint Method of Random Returns a random integer between:

CST141 Java Library and Documentation Page 6 47 48 49 50 51 52 53 Found in the java.util package, i.e. import java.util.random; The nextint Method of Random Returns a random integer between: Zero (0) (inclusive) And the specified value (exclusive) randomobject.nextint(int); randomint = rnd.nextint(11); Generates random number between zero (0) and ten (10) Documentation Document everything Write your comments first Before you write the method If you do not know what to write, you probably do not understand fully what the method is supposed to do Writing Documentation Your own classes should be documented the same way as are Java API library classes Use your classes to create a library class Other people should be able to use your classes by reading the documentation interface without reading the implementation Elements of Documentation 1) Documentation for a class should include: The class name (and inheritance hierarchy) A comment describing the overall purpose, function, and characteristics of the class A version number The name of the author or authors Documentation for each constructor and each method in the class Elements of Documentation 2) The documentation for the methods (each constructor and all methods) should include: The method name, as well as a comment describing its purpose and function The parameter names and types, including a description The return type, including a description The Javadoc Utility 1) Javadoc.exe is a standard, convenient tool to document Java code Requires special formatting for the comments This utility application reads the formatted comments, and generates an HTML document based on the comments HTML files provide convenience of hyperlinks from one document to another, as well as within each document The Javadoc Utility 2)

CST141 Java Library and Documentation Page 7 53 53 54 54 55 55 56 56 57 57 58 58 59 59 60 60 HTML files provide convenience of hyperlinks from one document to another, as well as within each document The Javadoc Utility 2) Two kinds of Javadoc comments: -level comments provides overall description of the classes Two kinds of Javadoc comments: Member-level comments describes the purpose(s) of the members (i.e. usually the -level comments provides overall description of the classes methods) Member-level comments describes the purpose(s) of the members (i.e. usually the Both types of comments start with the characters /** and end with */. methods) Both -Level types Comments of comments start with the 1) characters /** and end with */. -Level The class-level Comments comments provide an overall 1) description of the class Placed right above class signature (header) The class-level comments provide an overall description of the class May not be followed by any other elements before the class header (i.e. import) Placed right above class signature (header) Generally contain author and version number tags, and a description of the class May not be followed by any other elements before the class header (i.e. import) Generally -Level contain Comments author and version 2) number tags, and a description of the class -Level Example class-level Comments comment: 2) /** Example class-level comment: * Stores and displays the current time /** * field as either Standard or Daylight Stores and displays the current time * Time. Users may update time field by field as either Standard or Daylight * calling method settime(string time). Time. Users may update time field by * calling method settime(string time). * @author Carl B. Struck * @version 1.0 @author Carl B. Struck */ * @version 1.0 public class Time */ { public class Time -Level { Comments 3) -Level Tags are formatting Comments elements that start 3) with ampersand (@) character and are formatted in the documentation by the Javadoc.exe utility Tags are formatting elements that start with ampersand (@) character and are The @author tag describes the author(s) formatted in the documentation by the Javadoc.exe utility I.e * @author Carl B. Struck The @author tag describes the author(s) The @version tag describes the version number or similar information I.e * @author Carl B. Struck I.e. * @version 1.0 The @version tag describes the version number or similar information I.e. Time * @version 1.0 (Documentation) Member-Level Comments 1) Member-level comments describe the fields, methods, and constructors Placed directly above method signature (header) May contain tags that describe: The parameters of the method The method s return values Member-Level Comments 2) The @param tag describes each of the method s required parameters There may be more than one @param for a method First word always is the parameter variable name and it will be followed by a hyphen (-) in the documentation I.e * @param time the current time The @return tag describes the return value of a non-void method I.e. * @return Current time as a String Member-Level Comments 3) An member-level comment with a @param tag: /** * Updates the current 'time' field as

hyphen (-) in the documentation CST141 Java 63 Member-Level Library I.e * @param and Comments-- Documentation time the current @param time Tag Page 8 64 60 65 60 66 67 68 61 69 61 62 62 70 63 71 63 64 64 65 65 66 72 66 67 67 68 68 73 69 74 69 70 70 75 The @return tag describes the return value of a non-void method I.e. Time * @return Current time as a String 1) Member-Level Time Comments 3) 2) Member-Level An member-level Time Comments comment with a @param 3) 3) tag: /** An member-level Time comment with a @param 4) tag: * Updates the current 'time' field as /** Mini-Quiz * a String No. 3 1) Updates the current 'time' field as Create a String a new BlueJ project name javadoc-practice Create * @param a new time class the named current Ball time with as two fields: * a String size @param a float time the current time as */ * color a a String String Define public void settime(string time) */ the constructor for Ball that takes parameters for the size and color fields Define { public void a set settime(string method for size time) that takes a single parameter size Member-Level Define { a set method Comments-- for color @param that takes Tag a single parameter color Member-Level Mini-Quiz No. 3 Comments 4) 2) A Define member-level a get method comment for size with that a @return returns the tag: float size Define /** a get method for color that returns the String color Do * Displays not implement the current the class 'time' methods field as (leave them blank except for the get methods) Mini-Quiz * a String, No. and 3 as either Standard 3) Write * Time all or the Daylight class documentation Time in Javadoc format: At the beginning a general comment that describes the class function * The @return @author The (include current time the names as a String of all members of your group in this tag) and */ @version tags public Comments String that gettime() specify constructor and each of the methods { The @param and @return tags where appropriate Member-Level Information hiding Comments-- @param Tag Data Time belonging to one object should be hidden 1) from other objects It is only important to know what an object can do, not how it does it Information Time hiding increases the level of independence 2) Independence Time of modules is important for large 3) systems and maintenance Public Time vs. Private 1) 4) The keywords public and private are called access modifiers Mini-Quiz Attributes No. that 3 are public including fields, 1) constructors, methods are accessible to Create methods a in new other BlueJ classes project name javadoc-practice Create a new class named Ball with two fields: Public vs. Private 2) size a float Attributes that are private are accessible only within the same class color a String Instance variables should not be declared public so that they cannot be Define the constructor for Ball that takes parameters for the size and color fields manipulated directly from other classes Define a set method for size that takes a single parameter size Only methods and fields that are intended for access from within other classes should Define be public a set method for color that takes a single parameter color Mini-Quiz Constants No. 3 2) Define A constant a get is method a programmer-named for size that returns identifier the float whose size value cannot change as a result Define of some a program get method action for color that returns the String color Do not implement the class methods (leave them blank except for the get methods) Mini-Quiz public static No. final 3 String STANDARD = 3) " Standard Time"; Write In which: all the class documentation in Javadoc format: At public: the beginning access a modifier, general comment as usual that describes the class function The static: @author gives (include is class the scope names of all members of your group in this tag) and @version final: says tagsthat it is a constant Time.java public Comments that specify final Fields constructor (Source and Code) each of the methods The @param and @return tags where appropriate

A public constant static is final a programmer-named String STANDARD identifier = " Standard whose Time"; value cannot change as a result CST141 Java Library and Documentation Page 9 75 76 77 75 76 75 77 78 76 77 78 79 78 79 79 80 80 80 81 81 81 82 83 84 82 85 83 82 84 83 85 86 84 85 86 86 final: says that it is a constant Time.java public of In some which: program action final Fields (Source Code) public: access modifier, as usual Time.java public final Fields (Documentation) public static: gives final String is class STANDARD scope = " Standard Time"; In HashMap final: which: says that it is a constant 1) public: access modifier, as usual Time.java public A map allows the storing final Fields of elements, (Source where Code) each element is a key/value pair Unlike static: an array gives where is class values scope are stored at a particular index, the map determines the Time.java public index final: itself on says the that hash final it is Fields value a constant (Documentation) the key Time.java public HashMap final Fields (Source Code) 1) 2) Time.java public An map example allows of the a map storing final with Fields of strings elements, (Documentation) as keys where and each values: element is a key/value pair Unlike Key provides an array where information values for are the stored lookup at a particular index, the map determines the index Value the HashMap itself on data the hash returned value when on lookup the keymatches 1) the key A map allows the storing of elements, where each element is a key/value pair HashMap 2) 3) Unlike an array where values are stored at a particular index, the map determines the An Format example index itself to instantiate of a map on the hash object: with strings as keys and values: value on the key HashMap<keyType, Key provides information valuetype> for the hashmapobject lookup = new HashMap<keyType, Value the valuetype>(); HashMap data returned when lookup matches 2) the key An example of a map with strings as keys and values: Example HashMap to instantiate object 3) HashMap<String, Key provides information String> sodamap for the = lookup new HashMap<String, String>(); Format to instantiate object: Found Value the in java.util data returned package, when i.e. lookup matches the key HashMap<keyType, valuetype> hashmapobject = new HashMap<keyType, import valuetype>(); HashMap java.util.hashmap; 3) Format Example The put Method to to instantiate of object: HashMap Stores HashMap<keyType, HashMap<String, a new entry String> into valuetype> a HashMap sodamap hashmapobject object = new HashMap<String, = new HashMap<keyType, String>(); Found valuetype>(); Adds in and the associates java.util package, a specified i.e. value with the specified key in this map (arguments Example import for both java.util.hashmap; to required) instantiate object HashMap<String, String> sodamap = new HashMap<String, String>(); The Format put Method of HashMap Found hashmapobject.put(key, in the java.util package, value); i.e. Stores a new entry into a HashMap object import java.util.hashmap; Adds and associates a specified value with the specified key in this map (arguments The phonebook.put("charles", for put both Method required) of HashMap "531-939-4587"); Stores Format The get Method a new entry of into a HashMap object Returns hashmapobject.put(key, Adds and the associates value to which a specified value); the corresponding value with the key specified is mapped key in in the this map map (arguments for Returns both null required) if map contains no mapping for this key Format phonebook.put("charles", "531-939-4587"); hashmapobject.put(key, value); The hashmapobject.get(key); Method of HashMap Returns the value to which the corresponding key is mapped in the map phonebook.put("charles", "531-939-4587"); response Returns = null phonebook.get("lisa"); if map contains no mapping for this key The Format get PhoneList Method of HashMap 1) Returns hashmapobject.get(key); the value to which the corresponding key is mapped in the map PhoneList 2) Returns null if map contains no mapping for this key Format response PhoneList = phonebook.get("lisa"); 3) hashmapobject.get(key); The tolowercase PhoneList Method of String 1) 1) Returns response PhoneList a String with all the alphabetic = phonebook.get("lisa"); 2) characters in the String object converted to lower case Adds PhoneList binary 1 to 11th bit from left 1) 3) The Effects tolowercase PhoneList only alphabetic Method characters of String 2) 1) Returns The tolowercase PhoneList a String with Method all the of alphabetic String 3) characters in the String object 2) converted to lower case The stringobject.tolowercase() Adds tolowercase binary 1 to Method 11th bit of from left String 1) Returns Effects There a are String only no alphabetic arguments with all the characters to alphabetic the method characters in the String object converted to lower case The tolowercase Method of String 2) Adds binary 1 11th bit from left String s2 = s1.tolowercase(); Effects only alphabetic characters stringobject.tolowercase() If s1 = "Hello" the string s2 = "hello The There Although tolowercase are the no lower arguments Method case characters to of the method String are returned, the original String 2) object is unchanged

Effects only alphabetic characters Create String s2 a new = s1.touppercase(); class named CreditAccounts CST141 Java Library and Documentation Page 10 86 89 90 87 88 90 91 92 89 91 92 93 90 93 94 91 94 95 92 The Declare If tolowercase s1 = a "Hello" private HashMap Method the string of object s2 = field "HELLO String of subtype <String, String> named 2) accounts which Although contains the a upper credit case account characters number are and returned, a customer the original name String object is In stringobject.tolowercase() the unchanged constructor, instantiate the accounts object and put the following key and value There entries are into no arguments it: to the method Mini-Quiz No. 4 1) 11111, Jason Wilson Create String 22222, a new s2 = Sally BlueJ s1.tolowercase(); Feldman project named hash-map-demo Create If 33333, a new s1 = "Hello" Thomas class named the Hendricks CreditAccounts string s2 = "hello Declare Although 44444, a private Nancy HashMap the lower Jones object field of subtype <String, String> named accounts case characters are returned, the original String object is which contains a credit account number and a customer name unchanged In Mini-Quiz the constructor, No. 4 instantiate the accounts 2) object and put the following key and The Write value touppercase entries a String into method it: Method named of lookupaccount() String that takes a String parameter 1) Returns accountnumber 11111, a String Jason with Wilson all the alphabetic characters in the String object converted to upper 22222, Convert casethe Sally accountnumber Feldman parameter to lower case Subtracts 33333, Use it to look Thomas binary up 1 the from Hendricks key11th in the bit accounts from left hash map object Effects 44444, Then return only Nancy alphabetic the Jones value from characters the hash map The Write touppercase a void method Method named of displayaccounts() String that prints the contents 2) of the Mini-Quiz No. 4 2) accounts hash map object to the terminal window Write Document a String using method the Javadoc named standard lookupaccount() that takes a String parameter accountnumber stringobject.touppercase() The There Convert startswith are the no accountnumber Method arguments of to the parameter method String to lower case 1) Tests Use to it to see look if this up String the keyobject in the starts accounts with the hash specified map object String A String Boolean Then s2 return = method s1.touppercase(); the that valuereturns: from the hash map Write If true s1 a if = void the "Hello" argument method the named is string a prefix displayaccounts() s2 = of "HELLO the character that sequence prints the represented contents of by the this String accounts Although false otherwise hash map upper object case characters to the terminal are returned, window the original String object is Document The startswith unchanged using Method the Javadoc of standard String 2) Mini-Quiz The startswith No. 4 Method of String 1) 1) Create Tests stringobject.startswith(stringargument); to a see new if BlueJ this String project object named starts hash-map-demo with the specified String Create A Boolean The a stringobject new method class that named and/or returns: the CreditAccounts stringargument may be a string constant or string Declare true variable if a the private argument HashMap is a object prefix of field the of character subtype sequence <String, String> represented named by accounts this String Example which false contains otherwise 1: a credit account number and a customer name In boolean the constructor, istrue = "firststring".startswith("first"); instantiate the accounts object and put the following key and The startswith Method of String 2) value The entries condition into above it: which uses string constants always will be true 11111, Jason Wilson The stringobject.startswith(stringargument); startswith Method of String 3) 22222, Sally Feldman 33333, The stringobject Thomas and/or Hendricks the stringargument may be a string constant or string stringobject.startswith(stringobject); variable 44444, Nancy Jones Example 1: 2: Mini-Quiz boolean String input istrue No. = 4 JOptionPane.showInputDialog(prompt); = "firststring".startswith("first"); 2) Write if The ( input.startswith("bye") a condition String method above named which ) { uses lookupaccount() string constants that takes alwaysa String will be parameter true accountnumber The trim startswith Method Method of of String String 3) Convert the accountnumber parameter to lower case Returns Use it a to string look up with the all key leading in the and accounts trailing hash blank map spaces object stripped from the String object stringobject.startswith(stringobject); Then return the value from the hash map Write Example a void 2: method named displayaccounts() that prints the contents of the accounts String stringobject.trim() input hash = JOptionPane.showInputDialog(prompt); map object to the terminal window Document if There ( input.startswith("bye") are using no arguments the Javadoc to ) { standard the method The trim startswith Method Method of of String String str2 = str1.trim(); String 1) Tests Returns to a see string if this with String all leading object and starts trailing with the blank specified spaces String stripped from the String If str1 = " hello " the string str2 = "hello A object Boolean Although method a String that trimmed returns: at the beginning and end is returned, the original String true object if the is unchanged argument is a prefix of the character sequence represented by this String stringobject.trim() false otherwise The There equals are Method no arguments of to String the method 1) The Methods startswith of the Method String class of that compare String one string object to another 2) string to see if they String are str2 identical = str1.trim(); stringobject.startswith(stringargument); If Comparing str1 = " Strings hello " with the the equal str2 to = (==) "hello operator can have unexpected results A Boolean The Although stringobject method a String that and/or trimmed returns: the at stringargument the beginning and may end be is a returned, string constant the original string String

false otherwise The String equals str2 Method = str1.trim(); of String 2) If str1 = " hello " the string str2 = "hello stringobject.equals(stringargument) Although a String trimmed at the beginning and end is returned, the original String object is unchanged The String equals input Method = JOptionPane.showInputDialog(prompt); of String 1) Methods if ( input.equals("bye") of the String class ) { that compare one string object to another string to see if Logically they are identical equivalent to: if Comparing (input == "bye") Strings with the equal to (==) operator can have unexpected results A Boolean However method this is invalid that returns: syntax String true Comparison if argument is Processing identical to the character sequence represented by this String Made false character otherwiseby character, from lef to right, in accordance with the computer's The collating equals sequence Method of String 2) Unicode (ANSI/ASCII), EBCDIC or some other code The stringobject.equals(stringargument) binary value of the leftmost character of one factor is compared to the binary value of the leftmost character of the other If String they input are equal, = JOptionPane.showInputDialog(prompt); the comparisons continue with each succeeding character position String if ( input.equals("bye") Comparison Examples ) { Logically Example 1: equivalent to: if "java" (input == "bye") However Binary: this 0110 is 1010 invalid (106) syntax / 0110 0001 (97) String "jello" Comparison Processing Made Binary: character 0110 by 1010 character, (106) / from 0110 lef 0101 to right, (101) in accordance with the computer's Example collating sequence 2: Unicode "hello" (ANSI/ASCII), EBCDIC or some other code The binary Binary: value 0110 of 1000 the (104) leftmost / 0110 character 0101 of (101) one factor is compared to the binary value "Howdy" of the leftmost character of the other If they Binary: are equal, 0100 1000 the comparisons (72) / 0110 continue 1111 (111) with each succeeding character position CST141 Java Library and Documentation Page 11 96 95 97 96 98 97 98 99 100 101 102 103 104 105 106 107 99 100 101 102 103 108 104 105 106 107 String SodaLookup: Comparison Examples 1) Example SodaLookup: 1: 2) "java" SodaLookup: Binary: 0110 1010 (106) / 0110 3) 0001 (97) "jello" SodaLookup: 4) Binary: 0110 1010 (106) / 0110 0101 (101) SodaLookup: 5) Example 2: "hello" SodaInventory: 1) Binary: 0110 1000 (104) / 0110 0101 (101) SodaInventory: 2) "Howdy" SodaInventory: Binary: 0100 1000 (72) / 0110 1111 3) (111) The main() SodaLookup: Method 1) Every SodaLookup: Java application must have a single 2) method named main() Method may be in any class, but usually is found in the application s controlling class Normal SodaLookup: execution of an application starts 3) and ends with the main() method Method SodaLookup: main() then directly or indirectly 4) calls all the other methods in the application SodaLookup: 5) The main() Method 2) The SodaInventory: method always has the same header: 1) public SodaInventory: static void main (String[] args) 2) { Not necessary to completely understand it at this time although SodaInventory: It has public access (although it never 3) is called from another method) The main() It is static Method and therefore never instantiated 1) Every It Java is void application and never must returns have a a value single method named main() Method The may parameter be in any args class, is a String but usually arrayis found in the application s controlling class

Method main() then directly or indirectly calls all the other methods in the CST141 Java Library application and Documentation Page 12 108 109 110 The main() Method 2) The method always has the same header: public static void main (String[] args) { Not necessary to completely understand it at this time although It has public access (although it never is called from another method) It is static and therefore never instantiated It is void and never returns a value The parameter args is a String array The System.exit Method Applications using graphical user interfaces (i.e. showmessagedialog) may leave the command window open after execution The exit() method of class System lets the user Press any key to close the terminal (command) window as follows: System.exit(0); The argument 0 indicates to the operating system that the application ended normally Application1 (tech-support-gui) 111 112 113 114 115 116 SupportSystem (tech-support-gui) 1) SupportSystem (tech-support-gui) 2) Responder (tech-support-gui) 1) Responder (tech-support-gui) 2) Responder (tech-support-gui) 3) Project 7 Alternative: Exercise 5.61 (p. 167) 117