Java library

Alberto Ferrari
Ingegneria dell'Informazione, UniPR

Concepts

  • using library classes
  • reading documentation
  • writing documentation

Java library

  • The Java standard class library contains many classes that are very useful
  • This documentation is available in HTML format
  • The Java class library documentation shows details about all classes in the library

Oracle documentation

Interface

  • The interface of a class describes what a class does and how it can be used without showing the implementation
  • Interface:
    • name of the class
    • general description of the purpose of the class
    • list of constructors and methods
    • parameters and return types for each constructor and method
    • description of the purpose of each constructor and method.
  • The complete source code that defines a class is called the implementation of that class

Signature

  • The signature of a method includes:
    • an access modifier
    • the return type
    • the method name
    • a list of parameters

Immutable Objects

  • An object is said to be immutable if its contents or state cannot be changed once it has been created
  • Strings are an example of immutable objects

Example

method trim in class java.lang.String

  • public String trim()
  • ...
  • Returns:
    • A string whose value is this string, with any leading and trailing white space removed, or this string if it has no leading or trailing white space.
String Str1 = new String("   Object Oriented Programming in Java   ");
String Str2 =  Str1.trim();

Checking string equality

  • Comparing strings with the = = operator can lead to unintended results
    • string1 == string2 is true if string1 and string2 are the same string
  • As a general rule, strings should almost always be compared with equals, rather than with the = = operator
    • string1.equals(string2) is true if string1 and string2 have the same value

Random number

import java.util.Random;
...
Random randomGenerator;
randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt();
System.out.println(randomNumber);

Exercise

  • method nextInt() generate a random number from the whole range of Java integers (–2147483648 to 2147483647)
  • Find the nextInt method in class java.util.Random that allows the target range of random numbers to be specified
  • Create a new project TestRandom with class RandomTester
  • Write a method in RandomTester class called throwDice that returns a random number between 1 and 6 (inclusive)
  • Write a method getResponse that randomly returns one of the strings "yes", "no", or "maybe"
  • Write a method getMyResponse method so that it uses an ArrayList to store an arbitrary number of responses and randomly returns one of them
  • Write a method randomBetween that takes two parameters, min and max, and generates a random number in the range min to max (inclusive)

Map

  • A map is a collection that stores key/value pairs as entries
  • Values can be looked up by providing the key
  • A map can store a flexible number of entries
  • HashMap is a particular implementation of Map
  • The most important methods of the HashMap class are put and get
  • Example:
HashMap<String, String> phoneBook = new HashMap<String, String>();
phoneBook.put("Alberto Ferrari", "0521-1234567");
phoneBook.put("Giacomo Brambilla", "0521-7654321");
String number = phoneBook.get("Alberto Ferrari");
System.out.println(number);

Exercise

  • Create a new project TestMap with class MapTester
  • Use a HashMap to implement a phone book similar to the one in the example above
  • Implement two methods:
    • public void enterNumber(String name, String number)
    • public String lookupNumber(String name)
  • What happens when you try to look up a value and the key does not exist in the map?
  • Write the method bookEntry to check how many entries are contained in the map
  • Write the method printAll that print out all keys currently stored in the map

set

  • A set is a collection that stores each individual element at most once
  • It does not maintain any specific order, entering an element a second time simply has no effect
  • HashSet is an implementation of set
import java.util.HashSet;
...
HashSet<String> mySet = new HashSet<String>();
mySet.add("one");
mySet.add("two");
mySet.add("three")

Class documentation

  • The documentation of a class should be detailed enough for other programmers to use the class without the need to read the implementation
  • Java include a tool called javadoc that can be used to generate documentations for classes
  • The standard library documentation was created from the classes’ source files by javadoc
  • Documentatio in Bluej
    • Documentation for a single class by using Toggle Documentation View from the editor’s Tools menu
    • Project Documentation function from the main window’s Tools menu to generate documentation for all classes in the project

javadoc comments

/**
This is a javadoc comment.
*/
  • key symbols:
    • @version
    • @author
    • @param
    • @return

Access modifiers

  • Access modifiers define the visibility of a field, constructor, or method
    • public elements are accessible from inside the same class and from other classes
    • private elements are accessible only from within the same class

Information hiding

  • A programmer making use of a class should not need to know the internals and should not be allowed to know the internals
  • Coupling
    • weak coupling (loose coupling)
    • changes in one part of a program do not make it necessary to make changes in another part of the program

Exercise

  • In bouncing-balls project change the method bounce in class BallDemo to let the user choose how many balls should be bouncing (use a collection to store the balls)
  • Change the bounce method to place the balls randomly anywhere in the top half of the screen
  • Write a new method named boxBounce. This method draws a rectangle (the “box”) on screen and one or more balls inside the box. For the balls, do not use BouncingBall, but create a new class BoxBall that moves around inside the box, bouncing off the walls of the box so that the ball always stays inside. The initial position and speed of the ball should be random. The boxBounce method should have a parameter that specifies how many balls are in the box.
  • Give the balls in boxBounce random colors.

Class variables

  • Classes can have fields (class variables or static variables)
  • Exactly one copy exists of a class variable at all times, independent of the number of created instances.
public class BouncingBall {
  private static final int GRAVITY = 3;
  ...
}
  • Java also supports class methods (static methods), which are methods that belong to a class

Class variables

Class variables

Constants

  • Constants cannot change their value during the execution of an application
  • In Java, constants are defined with the keyword final
  • Constants they include the keyword final before the type name and must be initialized with a value at the point of declaration
private final int SIZE = 10;

Concept summary (1)

  • Java library contains many useful classes
  • library documentation shows details about all classes in the library
  • interface of a class describes what a class does and how it can be used without showing the implementation
  • implementation: the source code that defines a class
  • immutable object: its contents or state cannot be changed once it has been created
    • Strings are an example of immutable objects
  • map is a collection that stores key/value pairs as entries
    • values can be looked up by providing the key
  • set is a collection that stores each individual element at most once
    • it does not maintain any specific order

Concept summary (2)

  • documentation of a class should be detailed enough for other programmers to use the class without the need to read the implementation (javadoc)
  • access modifier define the visibility of a field, constructor, or method
    • public elements are accessible from inside the same class and from other classes
    • private elements are accessible only from within the same class
  • information hiding is a principle that states that internal details of a class’s implementation should be hidden from other classes
  • class variable, static variable fields of a classes
    • exactly one copy exists of a class variable at all times, independent of the number of created instances

Alberto Ferrari
Ingegneria dell'Informazione, UniPR
www.ce.unipr.it/~aferrari/