0% found this document useful (0 votes)
10 views

Library Classes in Java

Chapter 6 covers the use of Java library classes, emphasizing the importance of understanding packages, method interfaces, and reading documentation. It discusses key packages like java.lang, java.util, and java.io, and introduces concepts such as parameterized classes and collections like Sets and Maps. The chapter also highlights the use of wrapper classes for primitive types and the concepts of autoboxing and unboxing.

Uploaded by

Judith Nelson
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Library Classes in Java

Chapter 6 covers the use of Java library classes, emphasizing the importance of understanding packages, method interfaces, and reading documentation. It discusses key packages like java.lang, java.util, and java.io, and introduces concepts such as parameterized classes and collections like Sets and Maps. The chapter also highlights the use of wrapper classes for primitive types and the concepts of autoboxing and unboxing.

Uploaded by

Judith Nelson
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

CHAPTER 6 M250 Object

Oriented
TUTORIAL Programming

6.0
MAIN
CONCEPTS
TO BE
COVERED
Using library classes
Reading
documentation

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL KÖLLING
Thousands of classes.

Tens of thousands of
THE methods.
JAVA Many useful classes that
CLASS make life much easier.

LIBRARY Library classes are often


inter-related.

Arranged into packages.

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL KÖLLING
PACKAGES
Packages:
Organized into packages like java.lang, java.util, java.io.
Key Packages:
java.lang: Basics (data types, exceptions).
java.util: Utilities (ArrayList, HashMap, Scanner).
java.io: Input/output (File, FileInputStream).
Common Functionality:
java.net: Networking.
java.awt / javax.swing: GUI.
java.time: Date/time.
Java.math: arbitrary-precision arithmetic.
java.util.concurrent: Concurrent programming.
Benefits:
Saves time, promotes code reusability
OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BL
UEJ, © DAVID J. BARNES, MICHAEL KÖLLING
JAVA UTIL PACKAGE

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BL


UEJ, © DAVID J. BARNES, MICHAEL KÖLLING
WORKING WITH
THE LIBRARY
•A competent Java programmer
must be able to work with the
libraries.
You should:
• know some important classes by name;
• know how to find out about other
classes.

Remember:
• we only need to know the interface, not
the implementation.

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ,


© DAVID J. BARNES, MICHAEL KÖLLING
METHOD INTERFACE
The method interface of a Java
class refers to the set of Example using nextInt() of
methods declared by the class. the Random class
It outlines the methods that
instances of the class can or
must have.
Components:
Method Signature: Random random = new Random();
// Generates a random integer between 0 and 100
Includes method name, return int randomNumber = random.nextInt(101);

type, and parameters.


Access Modifiers:
Determine method visibility
(public, private, protected).
OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BL
UEJ, © DAVID J. BARNES, MICHAEL KÖLLING
READING CLASS
DOCUMENTATION
Documentation of the
Java libraries in HTML
format;
Readable in a web
browser
Class API: Application
Programmers’ Interface
Interface description for
all library classes

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
API REFERENCE

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
INTERFACE VS
IMPLEMENTATION
The documentation includes
the name of the class;
a general description of the class;
a list of constructors and methods
return values and parameters for constructors
and methods
a description of the purpose of each
constructor and method

the interface of the class


OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
INTERFACE VS
IMPLEMENTATION
The documentation does not include

private fields (most fields are private)


private methods
the bodies (source code) of methods

the implementation of the


class OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
startsWith
 public boolean startsWith(String
prefix)
DOCUMENTATI
ON FOR Tests if this string starts with the
specified prefix.
STRING
METHOD Parameters:
STARTSWITH  prefix - the prefix.

Returns:
 true if the …; false otherwise

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL KÖLLING
METHODS FROM STRING
•contains
•endsWith
•indexOf
•substring
•toUpperCase
•trim
•Beware: strings are immutable!

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
USING LIBRARY
CLASSES
Classes organized into packages.
Classes from the library must be imported using an
import statement;
 except from the java.lang package.

They can then be used like classes from the current


project.

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
PACKAGES AND IMPORT
Single classes may be imported:
import java.util.ArrayList;

Whole packages can be imported:


import java.util.*;
Importation does not involve source code insertion.

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
ADDING RANDOM
BEHAVIOR
The library class Random can be used to generate
random numbers:

import java.util.Random;
...
Random rand = new Random();
...
int num = rand.nextInt();
int value = 1 + rand.nextInt(100);
int index = rand.nextInt(list.size());

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
SELECTING RANDOM
ENTRIES FROM A LIST
public Responder()
{
randomGenerator = new Random();
responses = new ArrayList<>();
fillResponses();
}

public void fillResponses()
{
fill responses with a selection of response strings
}

public String generateResponse()
{
int index = randomGenerator.nextInt(responses.size());
return responses.get(index);

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
PARAMETERIZED
CLASSES
•The documentation includes provision for a type
parameter:
 ArrayList<E>

•These type names reappear in the parameters and


return types of the methods of the class:
 E get(int index)
 boolean add(E e)

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
PARAMETERIZED
CLASSES
•The types in the documentation are placeholders for
the types we use in practice:
 An ArrayList<Track> actually has methods:
 Track get(int index)
 boolean add(Track e)

Track firstTrack = tracks.get(0);//retrieve a


Track

tracks.add(newTrack);//newTrack is an object of
type Track

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
REVIEW

Java has an extensive class library.


A good programmer must be
familiar with the library.
The documentation tells us what we
need to know to use a class (its
interface).
Some classes are parameterized
with additional types.
• Parameterized classes are also known
as generic classes or generic types.
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
Using library classes to implement some more advanced functionality

FURTHER LIBRARY
CLASSES
MAIN CONCEPTS TO BE
COVERED
Further library classes:
• Set – avoiding duplicates
• Map – creating associations

Writing documentation:
• javadoc

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
Compare

USING SETS: THE with code for


an
HASHSET
•Definition:
•A part of the Java Collections
ArrayList!
Framework.
•Implements Set Interface
•Stores unique elements with HashSet<String> mySet = new HashSet<>();

no specific order. mySet.add("one");
mySet.add("two");
•Uniqueness: mySet.add("three");
mySet.add("one");//wont work
•Does not allow duplicate ​
for(String element : mySet) {
elements. }
System.out.println(element);

•. ​

•Ordering:
•Does not maintain the order of
elements. one
•Iteration order is not two
guaranteed. three
•Use Cases:
•Efficient for membership
testing and eliminating
duplicates. OBJECTS FIRST WITH JAVA - A PRACTICAL
•Not suitable when order or
INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
USING SETS : THE
TREESET (SORTED SET)
•Definition:
•A component of the Java Collections
Framework.
•Implements the Set interface.
•Stores unique elements without a specific
order.
•Uniqueness: Set<String> sortedNames = new TreeSet<>();
sortedNames.add("Alice");
•Prohibits duplicate elements. sortedNames.add("Bob");
•Utilizes a natural ordering or a custom sortedNames.add("Charlie");

comparator.
•Ordering:
•Does not maintain the order of elements.
•Elements are stored in sorted order based on
natural order or one detailed in Comparable

Use Cases:
• Efficient for membership testing and eliminating
duplicates.
• Ideal when elements need to be sorted.

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BL


UEJ, © DAVID J. BARNES, MICHAEL KÖLLING
ode is designed to handle user input, extract unique words, and return them in a HashSet. The use of a HashS

TOKENISIN
G STRINGS public HashSet<String> getInput()
{
System.out.print("> ");
String inputLine =
The code on the
reader.nextLine().trim().toLowerCase(
RHS breaks the );
user input into an ​
array of words and String[] wordArray =
inputLine.split(" ");
then uses the HashSet<String> words = new
HashSet to store HashSet<String>();
only unique words ​
for(String word : wordArray) {
words.add(word);
}
return words;
}

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL
KÖLLING
Maps are collections that contain
pairs of objects.
Parameterized with two types.

MAPS Pairs consist of a key and a value.


Lookup works by supplying a key,
and retrieving a value.
Example: a contacts list.

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL KÖLLING
USING MAPS
A map with strings as keys and values

:HashMap

"Charles Nguyen" "(531) 9392 4587"

"Lisa Jones" "(402) 4536 4674"


"William H. Smith" "(998) 5488 0123"

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
USING MAPS
In the example on RHS
We are adding new key
value pairs to a Map

Names are used as keys


and numbers as values HashMap <String, String> contacts = new
HashMap<>();

contacts.put("Charles Nguyen", "(531) 9392 4587");
When we use get with the contacts.put("Lisa Jones", "(402) 4536 4674");
contacts.put("William H. Smith", "(998) 5488
key the value is 0123");

returned String number = contacts.get("Lisa Jones");
System.out.println(number);

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
•Alternative ways to group objects.

LIST, •Varying implementations available:


 ArrayList, LinkedList

MAP  HashSet, TreeSet (sorted)


 HashMap, TreeMap (sorted)

AND •But HashMap is unrelated to


SET HashSet, despite similar names.
•The second word reveals
organizational relatedness.

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL KÖLLING
LETTER COUNTER
CLASS DEMO
Fields:
private Map<String, Integer> letterCountMap;: This field holds a map where
keys are words (Strings) and values are the counts of unique letters in those words
(Integers).
Constructor:
public LetterCounter() { letterCountMap = new HashMap<String, Integer>(); }:
The constructor initializes the letterCountMap as a new HashMap when an instance of
LetterCounter is created.
getLetterCount Method:
public int getLetterCount(String word) { ... }:
This method takes a word as input and returns the count of unique letters in that
word.It checks if the word is already in the map (letterCountMap). If yes, it retrieves
the count from the map. If not, it calculates the count by creating a set of characters
and adding each character to the set. The size of the set represents the count of
unique letters.The calculated count is then stored in the map, and the count is
returned.
printAll Method:
public void printAll() { ... }: This method prints all entries in the map,
displaying each word along with its corresponding count of unique letters.
In summary, the LetterCounter class is designed to count and store the number of
unique letters in words. It uses a map to keep track of word counts and provides
methods to get the count for a specific word (getLetterCount) and print all word
counts (printAll).
OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BL
UEJ, © DAVID J. BARNES, MICHAEL KÖLLING
COLLECTIONS AND
PRIMITIVE TYPES
The generic collection classes can be used with all
class types ...
… but what about the primitive types: int, boolean,
etc.?
Suppose we want an ArrayList of int?

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
WRAPPER CLASSES
Primitive types are not objects types.
Primitive-type values must be wrapped
in objects to be stored in a collection!
Wrapper classes exist for all primitive
types:
simple type wrapper class
int Integer
float Float
char Character
... ...
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
WRAPPER CLASSES
wrap the value
int i = 18;
Integer iwrap = new Integer(i);
… unwrap it
int value = iwrap.intValue();

In practice, autoboxing and


unboxing mean we don't
often have to do this
explicitly

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
AUTOBOXING AND
UNBOXING
private ArrayList<Integer> markList;
...
public void storeMark(int mark)
{
markList.add(mark); autoboxin
} g

unboxin
int firstMark = markList.remove(0); g

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
Your own classes should be
documented the same way library
WRITING classes are.
CLASS Other people should be able to use
DOCUMEN your class without reading the
implementation.
TATION Make your class a potential 'library
class'!

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL KÖLLING
Documentation for a class should
include:
the class name
a comment describing the overall
purpose and characteristics of the class

ELEMENT a version number

S OF the authors’ names

DOCUMEN documentation for each constructor and


each method
TATION

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL KÖLLING
The documentation for each constructor
and method should include:
the name of the method
the return type
the parameter names and types
ELEMENTS a description of the purpose and
OF function of the method
DOCUMENT a description of each parameter
ATION a description of the value returned

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL
KÖLLING
JAVADOC
Class comment:

/**
* The Responder class represents a response
* generator object. It is used to generate an
* automatic response.
*
* @author Michael Kölling and David J. Barnes
* @version 1.0 (2016.02.29)
*/
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
JAVADOC
Method comment:

/**
* Read a line of text from standard input (the text
* terminal), and return it as a set of words.
*
* @param prompt A prompt to print to screen.
* @return A set of strings, where each String is
* one of the words typed by the user
*/
public HashSet<String> getInput(String prompt)
{
...
}
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
PUBLIC VS PRIVATE
Public elements are accessible to objects of other
classes:
• Fields, constructors and methods

Fields should not be public.


Private elements are accessible only to objects of the
same class.
Only methods that are intended for other classes
should be public.

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
CODE COMPLETION
•The BlueJ editor supports
lookup of methods.
•Use Ctrl-space after a
method-call dot to bring
up a list of available
methods.
•Use Return to select a
highlighted method.

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
CODE COMPLETION IN
BLUEJ

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
REVIEW
Java has an extensive class library.
A good programmer must be familiar with
the library.
The documentation tells us what we need to
know to use a class (interface).
The implementation is hidden (information
hiding).
We document our classes so that the
interface can be read on its own (class
comment, method comments).
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
CLASS VARIABLES
AND CONSTANTS
OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J.
BARNES, MICHAEL KÖLLING
•A class variable is shared between
all instances of the class.
•In fact, it belongs to the class and
CLASS exists independent of any
instances.
VARIAB •Designated by the static
LES keyword.
•Public static variables are accessed
via the class name; e.g.:
 Thermometer.boilingPoint

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL KÖLLING
CLASS VARIABLES

OBJECTS FIRST WITH JAVA - A PRACTICAL


INTRODUCTION USING BLUEJ, © DAVID J. BARNES,
MICHAEL KÖLLING
•A variable, once set, can have its
value fixed.
•Designated by the final keyword.

CONST
 final int SIZE = 10;

•Final fields must be set in their


ANTS declaration or the constructor.
•Combing static and final is
common.

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL KÖLLING
CLASS CONSTANTS
static: class variable
final: constant
private static final int gravity = 3;
Public visibility is less of an issue with final fields.
Upper-case names often used for class constants:
public static final int BOILING_POINT = 100;

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL KÖLLING
CLASS METHODS
A static method belongs to its class rather than the
instances:

public static int getDaysThisMonth()


Static methods are invoked via their class name:

int days = Calendar.getDaysThisMonth();

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BL


UEJ, © DAVID J. BARNES, MICHAEL KÖLLING
LIMITAT
IONS A static method exists independent
of any instances.
OF Therefore:
CLASS  They cannot access instance fields within
their class.

METHO  They cannot call instance methods within


their class.

DS

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL
KÖLLING
Class variables belong to their
class rather than its instances.
Class methods belong to their class
rather than its instances.
REVIEW Class variables are used to share
data among instances.
Class methods are prohibited from
accessing instance variables and
methods.

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL
KÖLLING
The values of final variables are
fixed.
They must be assigned at
declaration or in the constructor
REVIEW (for fields).
final and static are unrelated
concepts, but they are often used
together.

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL
KÖLLING
FURTHER ADVANCED
MATERIAL

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BL


UEJ, © DAVID J. BARNES, MICHAEL KÖLLING
POLYMO Different collection classes offer
similar interfaces; e.g.:
RPHIC  ArrayList and LinkedList
 HashSet and TreeSet
COLLEC Types exist which capture those
TION similarities:
 List
TYPES  Set

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL
KÖLLING
Polymorphism allows us to ignore
the more specific type in most
cases.
POLYMO We create objects of the specific
type, but ...
RPHIC … declare variables of the more
COLLEC general type:

TION List<Track> tracks = new


LinkedList<>();
TYPES Map<String, String>
responseMap =
new
HashMap<>();

OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J. BARNES, MICHAEL
KÖLLING

You might also like