Chapter 3: Using Classes and Objects

Overview

DrJava

(3.1) Creating Objects

Calling Methods of Objects

Deleting Objects

(3.2) String methods

See Figure 3.1. Examples—evaluate:

String s = "Mississippi";
s.charAt(0)
s.charAt(2)
s.compareTo("Alabama")
"cat".concat("dog")
"cat".equals("dog")
"cat".equalsIgnoreCase("Cat")
s.length()
s.replace('s', 't')
s.replace('s', 't').replace('p', 'q').replace('i', 'j').replace('M', 'N')
s // unchanged
s.substring(0, 4)
s.substring(4, 8)
s.toLowerCase()
s.toUpperCase()

Discussion

Compare Java and Python string operations

Example

(3.3) Packages

The Unnamed Package

When you're writing your program, and you don't make a package declaration, by default you're writing for the unnamed package.

The import Statement

APIs

(3.4) Random and its methods

Example

Listing 3.2: RandomNumber

(3.5) Math and its methods

Math methods

Examples:

Math.abs(-7)
Math.floor(7.9)
Math.floor(-7.9)
Math.ceil(7.1)
Math.ceil(-7.1)
Math.pow(2, 8)
Math.exp(8)  // e to the 8th power
Math.sqrt(2.0)
Math.cos(0);

Details: Fig. 3.5

Example

(3.6) Formatting Output

The NumberFormat Class

Examples

import java.text.NumberFormat;
NumberFormat nf;
nf = NumberFormat.getCurrencyInstance();
nf.format(12345.6789)
nf = NumberFormat.getPercentInstance();
nf.format(12345.6789)
nf = NumberFormat.getNumberInstance();
  // or getInstance()
nf.format(12345.6789)

Why Not "new"?

Locales

Example

Listing 3.4 Purchase

The DecimalFormat Class

Examples

import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("0.###");
df.format(123.4)
df.format(123.456789)

Example

Listing 3.5 CircleStats

(3.7) Enumerated Types

Declaring

Methods of Enumerated Types

Example

Listing 3.6 IceCream

(3.8) Wrapper Classes

The Nine Wrapper Classes

Byte
Short
Integer // int
Long
Float
Double
Character // char
Boolean
Void // what's this?

Example

Integer w = new Integer(67);
int i = w.intValue(); // 67

Wrapper Utilities

Conversion methods to and from String

Examples: Integer.parseInt, Integer.toString

Examples using base ≠ 10

Autoboxing and Unboxing

Data Conversion

Graphics

(3.9) Components and Containers

Two container classes

Another Component

Layout Managers

Example

Listing 3.7 Authority

(3.10) Nested Panels

(3.11) Images

Creating Images

import javax.swing.ImageIcon;

ImageIcon icon = new ImageIcon("IMAGEFILE"); 
                 // gif, jpeg, png

Rendering Images

Images in JLabels (1)

new JLabel(TEXT, ICON, POSITION)

where

Images in JLabels (2)

Setting position of text in label:

label.setHorizontalTextPosition(HPOSITION);
label.setVerticalTextPosition(VPOSITION);

where VPOSITION allows SwingConstants.TOP|CENTER|BOTTOM.

Example

Listing 3.9 LabelDemo

Lab

Overview of Lab 3