Quick Java — Code Section Inventory

1.2 First Glimpse: The Circle Class2 fragments

Fragment 1 of 2
package examples.shapes;

public class Circle {
    private int radius;

    public Circle(int r) {
        radius = r;
    }

    public double area() {
        return Math.PI * Math.pow(radius, 2);
    }
}
Fragment 2 of 2
package examples.shapes;

public class CircleApp {

    public static void main(String[] args) {
        int size = 10;
        Circle c = new Circle(size);
        double area = c.area();
        System.out.printf(
            "The area of a circle " +
            "with radius %d is %7.2f",
            size, area);
    }
}

1.3 Data2 fragments

Fragment 1 of 2
int count;     // declaration
count = 0;     // definition
int count = 0; // declaration + definition
Fragment 2 of 2
int[] numbers = new int[100];

1.5 Program Structure2 fragments

Fragment 1 of 2
package teamMaker;
import java.util.HashSet;
Fragment 2 of 2
public static double Avogadro = 6.0221409e+23;

1.6 Statements3 fragments

Fragment 1 of 3
if (2 + 2 == 4) {
    System.out.println("All is well.");
} else {
    System.out.println("What??");
}
Fragment 2 of 3
int count = 10;
while (count > 0) {
    System.out.println(count);
    count = count - 1;
}
System.out.println("Blast off!");
Fragment 3 of 3
for (int i = 10; i > 0; i = i - 1) {
    System.out.println(i);
}
System.out.println("Blast off!");

1.7 Program Execution1 fragment

Fragment 1 of 1
public static void main(String[] args) {

1.8 Hello World1 fragment

Fragment 1 of 1
public class MyClass {
    String hello = "Hello World";

    public static void main(String[] args) {
        new MyClass().doSomething();
    }

    void doSomething() {
        System.out.println(hello);
    }
}

2.2 Comments and Tags1 fragment

Fragment 1 of 1
/**
 * Returns the sum of two numbers.
 * @param a The first number.
 * @param b The second number. Cannot be negative.
 * @return the sum of the two numbers.
 * @throws AssertionError if b is negative.
 */
int add(int a, int b) {
    assert b >= 0; // ignored unless -ea is set
    while (b > 0) {
        // Move a 1 from b into a
        b -= 1;
        a += 1;
    }
    return a;
}

3.2.2 Arrays5 fragments

Fragment 1 of 5
int[] scores;
Fragment 2 of 5
int[] ary = new int[] {3, 1, 4, 1, 6};
Fragment 3 of 5
int[] ary2 = {3, 1, 4, 1, 6};
Fragment 4 of 5
double elevation[][]; // declaration

elevation = new double[50][75]; // definition

elevation[49][74] = 123.45;
Fragment 5 of 5
int[] triangle = new int[10];
for (int i = 0; i < triangle.length; i++) {
    triangle[i] = new int[i + 1];
}

3.2.3 Strings5 fragments

Fragment 1 of 5
""       // an empty string
"hello"  // a string containing five characters
Fragment 2 of 5
"He said, \"Don't go.\""
Fragment 3 of 5
String name = "We're doing Java";
Fragment 4 of 5
String fullName = firstName + " " + lastName;
Fragment 5 of 5
String message = "There are " + count + " errors.";

3.2.6 Declarations and Casting2 fragments

Fragment 1 of 2
int i = 0;
double d = 2.71828;
i = (int)d;
System.out.println(i);  // prints 2
Fragment 2 of 2
char ch = (char)('a' + 1); // result is 'b'

3.2.7 Constants2 fragments

Fragment 1 of 2
final int DAYS_IN_A_WEEK = 7;
Fragment 2 of 2
final int TWELVE = 12;

3.2.8 Methods3 fragments

Fragment 1 of 3
/**
 * A leap year is a year divisible by 4 but not
 * by 100, unless it is also divisible by 400.
 */
boolean isLeapYear(int year) {
    if (year % 4 != 0) return false;
    if (year % 100 != 0) return true;
    return year % 400 == 0;
}
Fragment 2 of 3
int count = 0;
Fragment 3 of 3
public static void main(String[] args) {...}

3.2.9 Methods Calling Methods1 fragment

Fragment 1 of 1
public void printLengthOfYear(int year) {
    int days = 365;
    if (isLeapYear(year)) { // "this." omitted
        days = 366;
    }
    System.out.println(year + " has " +
                       days + " days.");
}

3.2.11.1 Variables Declared in Classes1 fragment

Fragment 1 of 1
public class MyClass {
    int x = 5;
    int y = x + 1; // can use x here
    int z = w + 1; // but this is illegal
    // now we can use x, y, and z
    int w = 3;
    // now we can also use w
    ...
}

3.2.11.2 Variables Declared in Methods1 fragment

Fragment 1 of 1
public double average(double x, double y) {
    double sum = x + y;
    return sum / 2;
}

3.2.11.3 Variables Declared in Blocks1 fragment

Fragment 1 of 1
{
    x = 1; // illegal!
    int x; // scope of "x" starts here
    x = 2; // legal
} // scope of "x" ends here
x = 3; // illegal!

3.3.1.2 Assignment Statements2 fragments

Fragment 1 of 2
x = 5;
Fragment 2 of 2
x = 10;

3.3.1.3 Method Calls and Varargs1 fragment

Fragment 1 of 1
public double average(double... args) {
     double sum = 0;
     for (double arg : args) {
         sum += arg;
     }
     return sum / args.length;
}

3.3.1.4 If Statements4 fragments

Fragment 1 of 4
if (x < 0) {
    x = 0;
}
Fragment 2 of 4
if (x % 2 == 0) {
    x = x / 2;
}
else {
    x = 3 * x + 1
}
Fragment 3 of 4
if (x % 2 == 0) x = x / 2;
else x = 3 * x + 1;
Fragment 4 of 4
 if (x < 0) {
     System.out.println("x is negative");
 } else if (x > 0) {
     System.out.println("x is positive");
 } else {
     System.out.println("x is zero");
 }

3.3.1.5 While Loops1 fragment

Fragment 1 of 1
int countDigits(int number) {
    int count = 0;
    while (number != 0) {
        number = number / 10;
        count += 1;
    }
    return count;
}

3.3.1.6 Do-while Loops2 fragments

Fragment 1 of 2
Random rand = new Random();
int x;
do {
    x = rand.nextInt(1000);
} while (x % 7 != 0);
Fragment 2 of 2
do {
    int x = rand.nextInt(1000);
} while (x % 7 != 0); // error

3.3.1.7 Traditional For Loops2 fragments

Fragment 1 of 2
int[] ary = {3, 1, 4, 1, 6};
for (int i = 0; i < ary.length; i += 1) {
    System.out.println(ary[i]);
}
Fragment 2 of 2
for (int i = 1, j = 100; i < j; i = 2 * i, j -= 1) {
    System.out.println("i = " + i + ", j = " + j);
}

3.3.1.8 For-each Loop1 fragment

Fragment 1 of 1
for (String name : names) {
    System.out.println(name);
}

3.3.1.9 Classic switch Statements1 fragment

Fragment 1 of 1
int i = 3;
String s;

switch (i) {
    case 1:
        s = "one";
        break;
    case 2:
        s = "two";
        break;
    default:
        s = "many";
}

3.3.1.11 Break Statements1 fragment

Fragment 1 of 1
int i, j = 0;
int[] ary = {7, 30, 9, 20, 3, 5};
id: for (i = 0; i < ary.length; i += 1) {
    for (j = 0; j < ary.length; j += 1) {
        if (i != j && ary[i] == 10 * ary[j]) {
            break id;
        }
    }
}
System.out.println(ary[i] + ", " + ary[j]);

3.3.1.12 Continue Statements1 fragment

Fragment 1 of 1
int[] ary = {10, 20, 5, -1, 30, -12, 50};
double sum = 0;
int count = 0;

for (int i = 0; i < ary.length; i += 1) {
    if (ary[i] <= 0) continue;
    sum += ary[i];
    count += 1;
}
double average = sum / count;

3.3.1.13 Return Statements2 fragments

Fragment 1 of 2
int add(int a, int b) {
    return a + b;
}

void print(int x) {
    System.out.println(x);
    return; // superfluous
}
Fragment 2 of 2
return;

3.3.1.14 Empty Statements2 fragments

Fragment 1 of 2
for (n = 1; n < 1000; n = 2 * n) {}
Fragment 2 of 2
for (n = 1; n < 1000; n = 2 * n);

3.3.2.1 Assert Statements1 fragment

Fragment 1 of 1
assert i >= 0 && i < myArray.length :
    "Bad array index: " + i;

3.3.2.2 Print “Statements”1 fragment

Fragment 1 of 1
System.out.println("The sum is " + sum);

3.3.2.3 Switch Statements and Expressions1 fragment

Fragment 1 of 1
long nonsense = switch (i) {
    case 1 -> 1000000000000L;
    case 2 -> 17 * x;
    case 3, 4 -> 'a';
    case 5 -> {
        System.out.println("Five!");
        yield 55;
    }
    case 6 -> throw new RuntimeException();
    default -> -1;
};
System.out.println(nonsense);

3.3.2.4 Pattern Matching in switch Statements1 fragment

Fragment 1 of 1
String s = switch (shape) {
    case Rectangle r && r.width == r.height ->
        "It's a square";
    case Rectangle r ->
        "It's a rectangle";
    case Triangle t ->
        "It's a " + t.width + " by " +
        t.height + " triangle.";
    default -> "It's a shape.";
};
System.out.println(s);

3.3.2.6 Throw Statements2 fragments

Fragment 1 of 2
if (b < 0) {
    throw new Exception("b is negative");
}
Fragment 2 of 2
int myMethod(int a, int b) throws Exception {
    if (b < 0) {
        throw new Exception("b is negative");
    }
    // other stuff
}

3.3.4 Try With Resources2 fragments

Fragment 1 of 2
try (FileReader fr = new FileReader("/Users/dave/test.txt");
    BufferedReader br = new BufferedReader(fr);) {
    String line = br.readLine();
    System.out.println(line);
}
catch (IOException e) { }
Fragment 2 of 2
try (br; fr) {
    line = br.readLine();
    System.out.println(line);
}
catch (IOException e) { }

3.3.5 Writing to a File1 fragment

Fragment 1 of 1
try (FileWriter fw = new FileWriter(
           "/Users/dave/test2.txt")) {
    fw.write("Hello\n");
    fw.write("Goodbye");
} catch (IOException e) {}

3.4.1.1 String Objects2 fragments

Fragment 1 of 2
String language = "Java";
Fragment 2 of 2
int numChars = language.length();

3.4.1.2 StringBuilder Objects3 fragments

Fragment 1 of 3
StringBuilder builder = new StringBuilder("Java");
Fragment 2 of 3
builder.append("Script");
Fragment 3 of 3
language = builder.toString(); // now "JavaScript"

3.4.1.3 Using Scanner2 fragments

Fragment 1 of 2
import java.util.Scanner;
Fragment 2 of 2
Scanner scanner = new Scanner(System.in);

3.4.1.5 Objects, Generics, and Stacks5 fragments

Fragment 1 of 5
Stack stuff = new Stack();
stuff.push("abracadabra");
stuff.push(new File("abc.txt"));
File foo = (File)stuff.pop();
String spell = (String)stuff.pop();
Fragment 2 of 5
Stack<String> words = new Stack<String>();
words.push("abracadabra");
words.push(new File("abc.txt")); // not legal
Fragment 3 of 5
Stack<String> words = new Stack<>();
Fragment 4 of 5
String word = words.pop();
Fragment 5 of 5
int find(String target,
         Stack<String> words) {...}

3.4.1.6 Maps1 fragment

Fragment 1 of 1
HashMap<String, Integer> phones = new HashMap<>();
phones.put("Joan", 555_1212);

4.1.1 A Simple Class1 fragment

Fragment 1 of 1
public class Password {
    private String password;

    public Password(String password) {
        this.password = password;
    }

    public boolean matches(String attempt) {
        return attempt.equals(password);
    }

    boolean reset(String oldPassword,
                  String newPassword) {
        if (matches(oldPassword)) {
            password = newPassword;
        }
        return password.equals(newPassword);
    }
}

4.1.4 Fields1 fragment

Fragment 1 of 1
String name;
double length = 22.75;
private int count = 0;

4.1.5 Constructors I2 fragments

Fragment 1 of 2
public class Customer {
    String name;
    String address;
    double amountOwed = 0;

    /** Here is the constructor */
    Customer(String name, String address) {
        this.name = name;
        this.address = address;
    }
}
Fragment 2 of 2
Customer c = new Customer("Jane", "jane@aol");

4.1.6 Defining Methods1 fragment

Fragment 1 of 1
int count = 0;

4.1.7 Example: Bank Account2 fragments

Fragment 1 of 2
public class Account {
    private int funds = 0;

    void deposit(int amount) {
        if (amount > 0) {
            funds += amount;
        }
    }

    void withdraw(int amount) throws Exception {
        if (funds >= amount) {
            funds -= amount;
        } else {
            throw new Exception("Insufficient funds");
        }
    }

    int getBalance() {
        return funds;
    }

    void transferFrom(Account other, int amount)
            throws Exception {
        other.withdraw(amount);
        deposit(amount);
    }

    public static void main(String[] args)
            throws Exception {
        Account john = new Account();
        Account mary = new Account();
        john.deposit(100);
        mary.transferFrom(john, 75);
        System.out.println(john.getBalance());
    }
}
Fragment 2 of 2
john.funds = 1_000_000;

4.1.9 Constructors II1 fragment

Fragment 1 of 1
public class Customer extends Person {
    private double amountOwed = 0;
    private String otherInfo;

    /** Here is the constructor */
    Customer(String name, String address,
             String otherInfo) {
        super(name, address); // required
        this.otherInfo = otherInfo;
    }
}

4.1.10 Static3 fragments

Fragment 1 of 3
public class Customer {
    private String name;
    private String address;
    private double amountOwed = 0;
    private static int howMany = 0;

    Customer(String name, String address) {
        this.name = name;
        this.address = address;
        howMany += 1;
    }
}
Fragment 2 of 3
static int getHowMany() {
    return howMany;
}
...
int customers;
// All of the following lines are equivalent
customers = Customer.getHowMany();
customers = richGuy.getHowMany();
customers = poorGuy.getHowMany();
Fragment 3 of 3
static double feetToMiles(double feet) {
    return feet / 5280.0;
}

4.1.11 Escaping Static1 fragment

Fragment 1 of 1
public class MyClass {
    public static void main(String[] args) {
        new MyClass().run();
    }
    void run() {
        System.out.println("Hello World");
    }
}

4.1.12 The main Method4 fragments

Fragment 1 of 4
public class MyClass {
    public static void main(String[] args) {...}
Fragment 2 of 4
package myPackage;

public class MyClass {
    public static void main(String[] args) {
        System.out.println(args[0] + args[1]);
    }
}
Fragment 3 of 4
javac myPackage/MyClass.java
Fragment 4 of 4
java myPackage/MyClass abc 123

4.1.13 A More Complete Example2 fragments

Fragment 1 of 2
package tools;

/**
 * A simple counter class
 */
public class Counter {
    private int count; // a field

    /** Constructor to make a Counter
     * object with an initial value.
     */
    public Counter(int initial) {
        count = initial;
    }

    /** increments the counter by n. */
    public void bump(int n) {
        count += n;
    }


    /** increments the counter by 1. */
    public void bump() {
        bump(1);
    }

    /** returns the value of the counter. */
    public int getCount() {
        return count;
    }
}
Fragment 2 of 2
package toolUser;
import tools.*;

public class CounterTest {
    public static void main(String[] args) {
        Counter c1 = new Counter(0);
        Counter c2 = new Counter(100);
        c1.bump(2);
        c1.bump(8);
        c2.bump(100);
        c2.bump();
        System.out.println(c1.getCount() + ", " +
                           c2.getCount());
    }
}

4.2 Inheritance1 fragment

Fragment 1 of 1
class Person {...}
class Person extends Object {...}

4.3 Casting Objects4 fragments

Fragment 1 of 4
BirthdayCake myCake = new BirthdayCake();
Cake cake = myCake;
Object obj = myCake;

myCake = (BirthdayCake)cake;
myCake = (BirthdayCake)obj;
cake = (Cake)obj;
Fragment 2 of 4
myCake instanceof BirthdayCake // true
myCake instanceof Cake   // true
myCake instanceof Object // true
Fragment 3 of 4
if (obj instanceof BirthdayCake) {
    BirthdayCake bc = (BirthdayCake) obj;
    ... use bc here
}
Fragment 4 of 4
if (obj instanceof BirthdayCake bc) {
    ... use bc here
}

4.4.1 Overriding toString1 fragment

Fragment 1 of 1
@Override
public String toString() {
    return "My count is " + count;
}

4.4.2 Overriding equals1 fragment

Fragment 1 of 1
@Override
public boolean equals(Object obj) {
    if (obj == this) return true;
    if (! (obj instanceof Counter)) return false;
    Counter that = (Counter)obj;
    return this.count == that.count;
}

4.4.3 Overriding hashCode2 fragments

Fragment 1 of 2
@Override
public int hashCode() {
    return count;
}
Fragment 2 of 2
@Override
public int hashCode() {
    return name.hashCode();
}

5.1.2 Getters and Setters2 fragments

Fragment 1 of 2
public int getWeight() {
    return weight;
}

public void setWeight(int weight)
            throws IllegalArgumentException {
    if (weight < 0) {
        throw new IllegalArgumentException();
    }
    this.weight = weight;
}
Fragment 2 of 2
public double getPounds() {
    return kilograms / 2.2;
}

5.1.3 Private Constructors1 fragment

Fragment 1 of 1
public class OneScanner {

    static Scanner scanner = null;

    private OneScanner() { } // constructor

    static Scanner instanceOf() {
        if (scanner == null) {
            scanner = new Scanner(System.in);
        }
        return scanner;
    }

    void close() {
        scanner.close();
        scanner = null;
    }
}
...
Scanner myScanner = OneScanner.instanceOf();

5.2.1.1 Ordering1 fragment

Fragment 1 of 1
{
    x = 1; // not legal here
    int x;
    x = 2; // legal here
}
x = 3;     // not legal here

5.2.1.3 Var Declarations2 fragments

Fragment 1 of 2
int[] numbers = new int[100];
Fragment 2 of 2
var numbers = new int[100];

5.2.2.9 Multiline Strings2 fragments

Fragment 1 of 2
System.out.println("1234567");
String textBlock = """
            First line
        Middle line
            Last line
      """;
System.out.println(textBlock);
Fragment 2 of 2
1234567
      First line
  Middle line
      Last line

5.2.2.10 Formatter1 fragment

Fragment 1 of 1
Formatter f = new Formatter();
f.format("The value of %s is %7.4f", "pi", Math.PI);
f.format(" and %s is %6.4f.", "e", Math.E);
System.out.println(f);
f.close();

5.2.3 Collections1 fragment

Fragment 1 of 1
Set<Item> items = new HashSet<>();

5.2.3.1 Iterators1 fragment

Fragment 1 of 1
List list = new LinkedList();
list.add("one");
list.add("two");
list.add("three");

Iterator iter = list.iterator();

while (iter.hasNext()) {
    System.out.println(iter.next());
}

5.2.4.2 The Ternary Operator2 fragments

Fragment 1 of 2
larger = a > b ? a : b;
Fragment 2 of 2
String s = "n is " + (n % 2 == 0 ? "even" : "odd");

5.2.4.4 Increment and Decrement Operators1 fragment

Fragment 1 of 1
x = x++;

5.3.1 Generic Classes2 fragments

Fragment 1 of 2
import java.util.*;

public class Box<T> {
    private List<T> contents;

    public Box() {
        contents = new ArrayList<T>();
    }

    public void add(T thing) {
        contents.add(thing);
    }

    public T grab() {
        if (contents.size() > 0) {
            return contents.remove(0);
        }
        else return null;
    }
}
Fragment 2 of 2
Box<String> box = new Box<String>();

5.3.2 Interfaces II5 fragments

Fragment 1 of 5
List<String> names = new ArrayList<String>();
Fragment 2 of 5
List<String> names = new Stack<String>();
Fragment 3 of 5
interface Storage<T> {
    public void add(T thing); // no body
    public T grab(); // no body
}
Fragment 4 of 5
class Box<T> implements Storage<T> {...}
class Shelf<T> implements Storage<T> {...}
class Cabinet<T> implements Storage<T> {...}
Fragment 5 of 5
void method rearrange(Storage<T> storage) {
    // code that uses add and grab
}

5.3.3 Abstract Classes3 fragments

Fragment 1 of 3
public void clear() {
    T thing;
    do {
        thing = grab();
    } while (thing != null);
}
Fragment 2 of 3
abstract class Storage<T> {

    public abstract void add(T thing); // no body

    public abstract T grab(); // no body

    public void clear() {
        T thing;
        do {
            thing = grab();
        } while (thing != null);
    }
}
Fragment 3 of 3
class Box<T> extends Storage<T> {...}
class Shelf<T> extends Storage<T> {...}
class Cabinet<T> extends Storage<T> {...}

5.3.4 Final and Sealed Classes3 fragments

Fragment 1 of 3
public final class Human {
    final String species = "Homo sapiens";
    final String getSpecies() {
        return species;
    }
    // other methods...
}
Fragment 2 of 3
public sealed class Thing
    permits Animal, Vegetable, Mineral {…}
Fragment 3 of 3
final class Animal extends Thing {…}

sealed class Vegetable extends Thing
    permits Carrot {…}
final class Carrot extends Vegetable {…}

non-sealed class Mineral extends Thing {…}
class Quartz extends Mineral {…}

5.3.5.1 Member Classes1 fragment

Fragment 1 of 1
public class OuterClass {
    int outerVariable = 0;

    public OuterClass(int number) { // constructor
        outerVariable = number;
    }

    class MemberClass {
        int innerVariable = 20;

        int getSum(int parameter) {
            return outerVariable + innerVariable +
                   parameter;
        }
    }

    public static void main(String[] args) {
        OuterClass outer = new OuterClass(100);
        MemberClass inner = outer.new MemberClass();
        System.out.println(inner.getSum(3));
        outer.run();
    }

    void run() {
        MemberClass localInner = new MemberClass();
        System.out.println(localInner.getSum(4));
    }
}

5.3.5.2 Static Member Classes1 fragment

Fragment 1 of 1
public class OuterClass {
    int outerVariable = 100;
    static int staticOuterVariable = 200;

    static class StaticMemberClass {
        int innerVariable = 20;

        int getSum(int parameter) {
            // Cannot access outerVariable here
            return innerVariable +
                   staticOuterVariable + parameter;
        }
    }

    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        StaticMemberClass inner =
            new StaticMemberClass();
        System.out.println(inner.getSum(3));
        outer.run();
    }

    void run() {
        StaticMemberClass localInner =
            new StaticMemberClass();
        System.out.println(localInner.getSum(5));
    }
}

5.3.5.3 Local Inner Classes1 fragment

Fragment 1 of 1
public class OuterClass {
    int outerVariable = 10000;
    static int staticOuterVariable = 2000;

    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        System.out.println(outer.run());
    }

    Object run() {
        int localVariable = 666;
        final int finalLocalVariable = 300;

        class LocalClass {
            int innerVariable = 40;

            int getSum(int parameter) {
                // Cannot access localVariable here
                return outerVariable +
                       staticOuterVariable +
                       finalLocalVariable +
                       innerVariable + parameter;
            }

            @Override
            public String toString() {
                return "I'm an instance of LocalClass";
            }
        }
        LocalClass local = new LocalClass();
        System.out.println(local.getSum(5));
        return local;
    }
}

5.3.5.4 Anonymous Inner Classes1 fragment

Fragment 1 of 1
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class OuterClass extends JFrame {

    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        JButton button =
            new JButton("Don't click me!");
        button.addActionListener(
            new ActionListener() {
                public void actionPerformed(
                    ActionEvent event) {
                        System.out.println("Ouch!");
                }
        });
        outer.add(button);
        outer.pack();
        outer.setVisible(true);
    }
}

5.3.6 Enums2 fragments

Fragment 1 of 2
enum Weekday { SUN, MON, TUE, WED, THU, FRI, SAT }
Fragment 2 of 2
public enum Coin {
    private final int value;
    PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
    Coin(int value) { this.value = value; }
    public int value() { return value; }
}

5.3.7 Records2 fragments

Fragment 1 of 2
record Range(int min, int max) { }
Fragment 2 of 2
public Range {
    assert min <= max;
}

5.3.9 Modules2 fragments

Fragment 1 of 2
module giveModule {
	exports com.xyz.giver;
	exports com.xyz.secret to takeModule;
}
Fragment 2 of 2
module takeModule {
	requires transitive giveModule;
}

6.2 Functional Interfaces2 fragments

Fragment 1 of 2
void run(IntUnaryOperator fun, int n) {
    System.out.println(fun.applyAsInt(1n));
}
Fragment 2 of 2
import java.util.function.IntUnaryOperator;
import java.util.Arrays;

public class FunctionTest {

    public static void main(String[] args) {
        FunctionTest test = new FunctionTest();
        int[] a = new int[] {1, 2, 3, 4, 5};
        Mapper map = new Mapper();
        int[] b = map.apply(a, x -> x * x);
        System.out.println(Arrays.toString(b));
    }
}

@FunctionalInterface
interface ForEach {
    int[] apply(int[] a, IntUnaryOperator f);
}

class Mapper implements ForEach {
    public int[] apply(int[] a, IntUnaryOperator f) {
        int[] b = new int[a.length];
        for (int i = 0; i < a.length; i += 1) {
            b[i] = f.applyAsInt(a[i]);
        }
        return b;
    }
}

6.3 Implicit Functional Interfaces2 fragments

Fragment 1 of 2
myButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        doSomething();
}});
Fragment 2 of 2
myButton.addActionListener(e -> doSomething());

7.4 JUnit 5 Assertions1 fragment

Fragment 1 of 1
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.*;

7.5 Testing Exceptions2 fragments

Fragment 1 of 2
assertThrows(ArithmeticException.class,
             () -> divide(0, 0));
Fragment 2 of 2
try {
    divide(0, 0);
    Assertions.fail();
}
catch (ArithmeticException e) { }

7.7 Simple Test Example1 fragment

Fragment 1 of 1
package account;

import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;

public class AccountTest {
    Account account; // must be global

    @BeforeEach
    public void setup() {
        this.account = new Account(); // global
    }

    @Test
    public void openAnAccount() {
        assertEquals(0, account.getBalance());
    }

    @Test
    public void testDeposit() {
        account.deposit(100);
        assertEquals(100, account.getBalance());
        account.deposit(70);
        assertEquals(170, account.getBalance());;
    }

    @Test
    public void testIllegalDeposit() {
        account.deposit(-10000);
        assertEquals(0, account.getBalance());
    }

    @Test
    public void goodWithdrawal() throws Exception {
        account.deposit(100);
        account.withdraw(35);
        assertEquals(65, account.getBalance());
    }

    @Test
    @DisplayName("Exception test, old style")
    public void badWithdrawal() {
        try {
            account.withdraw(35);
            fail("Did not throw exception");
        }
        catch (Exception e) { }
    }

    @Test
    @DisplayName("Exception test, new style")
    public void badWithdrawal2() {
         assertThrows(Exception.class,
             () -> account.withdraw(35));
    }
}

8.2.1 Message Dialog1 fragment

Fragment 1 of 1
JOptionPane.showMessageDialog(parent,
        "This is a message dialog.");

8.2.2 Confirm Dialog1 fragment

Fragment 1 of 1
int yesNo = JOptionPane.showConfirmDialog(
        parent,
        "Do you really want to do that?");
if (yesNo == JOptionPane.YES_OPTION) {
      System.out.println("Action confirmed");
}

8.2.3 Input Dialog1 fragment

Fragment 1 of 1
String userName =
    JOptionPane.showInputDialog(
        parent, "What is your name?");

8.2.4 Option Dialog1 fragment

Fragment 1 of 1
Object[] options = new String[] {
    "Java", "Python", "C++"
};
int option = JOptionPane.showOptionDialog(
     parent,
     "Choose an option:",  // message
     "Option Dialog",      // title
     JOptionPane.YES_NO_OPTION,    // option type
     JOptionPane.QUESTION_MESSAGE, // message type
     null,     // icon
     options,  // array of strings or components
     options[0]); // initial selection

8.2.5 Color Chooser Dialog1 fragment

Fragment 1 of 1
JColorChooser colorChooser = new JColorChooser();
Color chosenColor =
    colorChooser.showDialog(parent,
                            "Choose a color:",
                            Color.WHITE);

8.2.6 Load File Dialog3 fragments

Fragment 1 of 3
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Load which file?");
Fragment 2 of 3
BufferedReader br = null;
int result = chooser.showOpenDialog(parent);
if (result == JFileChooser.APPROVE_OPTION) {
    File file = chooser.getSelectedFile();
    try {
        if (file != null) {
            String fileName = file.getCanonicalPath();
            FileReader fr = new FileReader(fileName);
            br = new BufferedReader(fr);
        }
    }
    catch (IOException e) { }
}
Fragment 3 of 3
String line = "";
try { line = br.readLine(); }
catch (IOException e) { }

8.2.7 Save File Dialog3 fragments

Fragment 1 of 3
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Save file as?");
Fragment 2 of 3
int result = chooser.showSaveDialog(parent);
PrintWriter pr = null;
if (result == JFileChooser.APPROVE_OPTION) {
    File file = chooser.getSelectedFile();
    String fileName;
    try {
        if (file != null) {
            fileName = file.getCanonicalPath();
            FileOutputStream stream =
                new FileOutputStream(fileName);
            pr = new PrintWriter(stream, true);
        }
    }
    catch (IOException e) { }
}
Fragment 3 of 3
pr.println("Test line");
pr.close();

8.2.8 Custom Dialog4 fragments

Fragment 1 of 4
JFrame parent = null;
boolean isModal = true;
JDialog myDialog =
    new JDialog(parent, isModal);
Fragment 2 of 4
myDialog.add(new JLabel(" Your text "),
             BorderLayout.CENTER);
JButton closeButton = new JButton("Close");
myDialog.add(closeButton, BorderLayout.SOUTH);
Fragment 3 of 4
closeButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        myDialog.setVisible(false);
    }
});
Fragment 4 of 4
myDialog.pack();
myDialog.setVisible(true);

9.2 The Event Dispatch Thread1 fragment

Fragment 1 of 1
import javax.swing.SwingUtilities;
import javax.swing.JFrame;

public class MyGUI extends JFrame implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new MyGUI());
    }

    public void run() {
        // add components to this JFrame
        pack();
        setVisible(true);
    }
}

9.4 Make a Container1 fragment

Fragment 1 of 1
JFrame frame = new JFrame(); // or
JFrame frame = new JFrame("Text for title bar");

9.8.1 JFrame and JPanel7 fragments

Fragment 1 of 7
public class Examples extends JFrame {...}
Fragment 2 of 7
JFrame myFrame = new JFrame();
Fragment 3 of 7
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Fragment 4 of 7
addWindowListener(new Closer());
private class Closer extends WindowAdapter {
   public void windowClosing(WindowEvent we) {
        update(); // your method
   }
}
Fragment 5 of 7
setLayout(new BorderLayout());
Fragment 6 of 7
add(controlPanel, BorderLayout.NORTH);
Fragment 7 of 7
pack();
setVisible(true);

9.8.2 JEditorPane6 fragments

Fragment 1 of 6
JEditorPane editor = new JEditorPane();
Fragment 2 of 6
JPanel content = new JPanel();
Fragment 3 of 6
JScrollPane scroller = new JScrollPane(editor);
Fragment 4 of 6
EditorKit kit =
	 JEditorPane.createEditorKitForContentType(
	     "text/html");
editor.setEditorKit(kit);
Fragment 5 of 6
content.setLayout(new BorderLayout());
content.add(scroller, BorderLayout.CENTER);
Fragment 6 of 6
editor.setText("This is <i>Sample</i> text");
String myText = editor.getText();

9.8.3 JScrollPane5 fragments

Fragment 1 of 5
JPanel content = new JPanel();
Fragment 2 of 5
JScrollPane scroller = new JScrollPane(content);
Fragment 3 of 5
scroller.setPreferredSize(new Dimension(600, 600));
Fragment 4 of 5
content.setLayout(new BorderLayout());
content.add(editor, BorderLayout.CENTER);
add(scroller); // to the JFrame
Fragment 5 of 5
editor.setCaretPosition(0);

9.8.4 JTabbedPane3 fragments

Fragment 1 of 3
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setPreferredSize(
    new Dimension(300, 150));
Fragment 2 of 3
ImageIcon smiley =
   new ImageIcon("Resources Root/smiley.png");

ImageIcon frowny =
   new ImageIcon("Resources Root/frowny.png");
Fragment 3 of 3
tabbedPane.addTab("Smile", smiley,
                  panel0, "Tooltip 0");

tabbedPane.addTab("Tab 1", null,
                  panel1, "Tooltip 1");

tabbedPane.addTab(null, frowny,
                  panel2, null);

9.8.5 JButton3 fragments

Fragment 1 of 3
private JButton myJButton =
    new JButton("This is a JButton");
Fragment 2 of 3
someJPanel.add(myJButton);
Fragment 3 of 3
myJButton.addActionListener(event ->
    handleEvent("JButton"));

9.8.6 JTextField6 fragments

Fragment 1 of 6
private JTextField myJTextField =
    new JTextField("Example JTextField");
Fragment 2 of 6
someJPanel.add(myJTextField);
Fragment 3 of 6
myJTextField.setToolTipText("My tooltip");
Fragment 4 of 6
myJTextField.setText("This is new text");
Fragment 5 of 6
String myText = myJTextField.getText();
Fragment 6 of 6
myJTextField.addActionListener(event ->
    handleEvent("JTextField"));

9.8.7 JTextArea7 fragments

Fragment 1 of 7
private JTextArea myJTextArea =
    new JTextArea(rows, columns);
Fragment 2 of 7
someJPanel.add(myJTextArea);
Fragment 3 of 7
myJTextArea.setText(
    "New text for the JTextArea,\n" +
    "and it may contain newlines.");
Fragment 4 of 7
myJTextArea.append("Ehh...that's all, folks!");
Fragment 5 of 7
String myText = myJTextArea.getText();
Fragment 6 of 7
myJTextArea.getDocument().addDocumentListener(
        new MyJTextAreaListener());
Fragment 7 of 7
public class MyJTextAreaListener
    implements DocumentListener {
        public void insertUpdate(
            DocumentEvent arg0) {
                handleEvent("JTextArea");
        }
        public void removeUpdate(
            DocumentEvent arg0) {
                handleEvent("JTextArea");
            }
        public void changedUpdate(
            DocumentEvent arg0) {
                handleEvent("JTextArea");
            }
    }

9.8.8 JCheckBox4 fragments

Fragment 1 of 4
private JCheckBox myJCheckBox =
    new JCheckBox("This is a JCheckBox");
Fragment 2 of 4
someJPanel.add(myJCheckBox);
Fragment 3 of 4
boolean checked = myJCheckBox.isSelected();
Fragment 4 of 4
myJCheckBox.addItemListener(event ->
    handleEvent("JCheckBox"));

9.8.9 JRadioButton7 fragments

Fragment 1 of 7
private JRadioButton myJRadioButton1 =
    new JRadioButton("radio 1");
private JRadioButton myJRadioButton2 =
    new JRadioButton("radio 2");
Fragment 2 of 7
private ButtonGroup myButtonGroup = new ButtonGroup();
Fragment 3 of 7
myButtonGroup.add(myJRadioButton1);
myButtonGroup.add(myJRadioButton2);
Fragment 4 of 7
someJPanel.setLayout(new GridLayout(2, 1));
someJPanel.add(myJRadioButton1);
someJPanel.add(myJRadioButton2);
Fragment 5 of 7
    myJRadioButton1.setSelected(true);
Fragment 6 of 7
boolean selected1 = myJRadioButton1.isSelected();
boolean selected2 = myJRadioButton2.isSelected();
Fragment 7 of 7
 myJRadioButton1.addItemListener(event ->
     handleEvent("JRadioButton1"));
myJRadioButton2.addItemListener(event ->
     handleEvent("JRadioButton2"));

9.8.10 JLabel3 fragments

Fragment 1 of 3
JLabel myJLabel = new JLabel("This is a JLabel");
Fragment 2 of 3
labelPanel.add(myJLabel);
Fragment 3 of 3
labelPanel.addMouseListener(
    new MouseAdapter() {
        @Override
        public void mouseClicked(
            MouseEvent e) {
                handleEvent("JLabel");
        }
    });

9.8.11 JComboBox3 fragments

Fragment 1 of 3
private JComboBox myJComboBox =
    new JComboBox(
        new String[]{"Java", "Python",
                     "JavaScript"} );
Fragment 2 of 3
someJPanel.add(myJComboBox);
Fragment 3 of 3
myJComboBox.addActionListener(event -> {
    String selection =
        (String) myJComboBox.getSelectedItem();
    handleEvent(selection);
});

9.8.12 JSlider6 fragments

Fragment 1 of 6
private JSlider myJSlider =
    new JSlider(SwingConstants.HORIZONTAL,
                0, 50, 20);
Fragment 2 of 6
someJPanel.add(myJSlider);
Fragment 3 of 6
myJSlider.setMajorTickSpacing(10);
myJSlider.setMinorTickSpacing(2);
myJSlider.setPaintTicks(true);
myJSlider.setPaintLabels(true);
Fragment 4 of 6
myJSlider.setValue(45);
Fragment 5 of 6
int temp = myJSlider.getValue();
Fragment 6 of 6
myJSlider.addChangeListener(event ->
    handleEvent("JSlider"));

9.8.13 JSpinner5 fragments

Fragment 1 of 5
int min = 10, max = 30, step = 2, initValue = 20;
SpinnerModel model =
    new SpinnerNumberModel(initValue, min,
                           max, step);
private JSpinner myJSpinner = new JSpinner(model);
Fragment 2 of 5
someJPanel.add(myJSpinner);
Fragment 3 of 5
myJSpinner.setValue(20);
Fragment 4 of 5
int value = (int)myJSpinner.getValue();
Fragment 5 of 5
myJSpinner.addChangeListener(event ->
    handleEvent("JSpinner"));

9.8.14 JProgressBar6 fragments

Fragment 1 of 6
JProgressBar myProgressBar =
        new JProgressBar(min, max);
Fragment 2 of 6
JProgressBar myProgressBar =
        new JProgressBar(); // 0 to 100
Fragment 3 of 6
myProgressBar.setStringPainted(true);
Fragment 4 of 6
someJPanel.add(myProgressBar);
Fragment 5 of 6
myProgressBar.setValue(20);
Fragment 6 of 6
int value = myProgressBar.getValue();

9.8.15 Menus4 fragments

Fragment 1 of 4
JMenuBar myJMenuBar = new JMenuBar();
JMenu myJMenu = new JMenu("Menu");
JMenuItem myJMenuItem = new JMenuItem("Menu Item");
Fragment 2 of 4
myJMenuBar.add(myJMenu);
myJMenu.add(myJMenuItem);
Fragment 3 of 4
this.setJMenuBar(myJMenuBar);
Fragment 4 of 4
myJMenuItem.addActionListener(event ->
    handleEvent("JMenuItem"));

9.8.16 Keyboard Input2 fragments

Fragment 1 of 2
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(300, 200));
JLabel label = new JLabel("Type here");
panel.add(label);
add(panel, BorderLayout.CENTER); // to JFrame
Fragment 2 of 2
KeyListener listener = new KeyListener() {
    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println(
            "Pressed " + e.getKeyCode());
    }
    @Override
    public void keyTyped(KeyEvent e) {
        System.out.println(
            " Typed: " + e.getKeyChar());
    }
    @Override
    public void keyReleased(KeyEvent e) {
        System.out.println(
            "  Released: " + e.getKeyCode());
    }
};
panel.setFocusable(true);
panel.addKeyListener(listener);

9.9 DiceRoller1 fragment

Fragment 1 of 1
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class DiceRoller extends JFrame {
    static Random rand = new Random();
    JButton rollButton;
    JTextField result;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new DiceRoller().createAndShowGUI();
            }
        });
    }

    void createAndShowGUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        rollButton = new JButton("Roll 'em!");
        getContentPane().add(rollButton, BorderLayout.NORTH);
        result = new JTextField("You haven't rolled yet.");
        getContentPane().add(result, BorderLayout.SOUTH);
        pack();
        setVisible(true);
        rollButton.addActionListener(event -> {
                int number = rand.nextInt(6) + 1;
                result.setText("You rolled a " + number);
            });
    }
}

10.1 Threads2 fragments

Fragment 1 of 2
try { Thread.sleep(1000); }
catch (InterruptedException e) { }
Fragment 2 of 2
boolean okToRun = true;
secondThread.start();

public void run() {
    while (firstThread.okToRun) {...}
}

10.3 Timers1 fragment

Fragment 1 of 1
Timer timer = new Timer(40, event -> doSomething());

10.5 SwingWorker2 fragments

Fragment 1 of 2
import java.math.BigInteger;
import javax.swing.SwingWorker;

class Worker extends SwingWorker<BigInteger, Void> {
    private BigInteger big;

    Worker(BigInteger big) { // constructor
        this.big = big;
    }

    @Override
    public BigInteger doInBackground() {
        return findFactor(big);
    }

    // Here is our long-running process
    BigInteger findFactor(BigInteger big) {
        if (big.mod(BigInteger.TWO).equals
           (BigInteger.ZERO)) {
            return BigInteger.TWO; // 2 is a factor
        }
        BigInteger divisor = new BigInteger("3");
        while (big.divide(divisor).compareTo(divisor) >= 0) {
            if (big.mod(divisor).equals(BigInteger.ZERO)) {
                return divisor;
             }
            divisor = divisor.add(BigInteger.TWO);
        }
        return BigInteger.ZERO;
    }
}
Fragment 2 of 2
import java.math.BigInteger;

public class FactorFinder {

    public static void main(String[] args) {
        new FactorFinder(args[0]);
    }

    public FactorFinder(String bignum) {
        BigInteger factor = BigInteger.ZERO;
        BigInteger big = new BigInteger(bignum);
        System.out.println("Trying to factor " + big);

        // Use the SwingWorker
        Worker worker = new Worker(big);
        worker.execute();
        while (!worker.isDone()) {
            twiddleThumbs();
        }
        try { factor = worker.get(); }
        catch (Exception e) { }

        // Show the results
        if (factor.equals(BigInteger.ZERO))
            System.out.println("\n" + big +
                               " is prime");
        else
            System.out.println("\n" + big + " = " +
                               factor +" x " +
                               big.divide(factor));
    }

    public void twiddleThumbs() {
        try { Thread.sleep(1000); }
        catch(InterruptedException e) {}
        System.out.print('.');
    }
}

10.6.2 Controller2 fragments

Fragment 1 of 2
model = new Model();
view = new View(model);
Fragment 2 of 2
this.addComponentListener(new ComponentAdapter() {
    @Override
    public void componentResized(ComponentEvent e) {
        model.setLimits(view.getWidth(),
                        view.getHeight());
    }
});

10.6.3 Model5 fragments

Fragment 1 of 5
private Point position = new Point(0, 0);
private int dx = 6; // change in x
private int dy = 4; // change in y
Fragment 2 of 5
timer = new Timer(40, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        makeOneStep();
    }
});
Fragment 3 of 5
position.x += dx;
if (position.x < 0 || position.x >= xLimit) {
    dx = -dx;
    position.x += dx;
}
Fragment 4 of 5
public PropertyChangeSupport pcs;
Fragment 5 of 5
this.pcs.firePropertyChange("position", null,
                            position);

10.6.4 View3 fragments

Fragment 1 of 3
public class View extends JPanel
    implements PropertyChangeListener {…}
Fragment 2 of 3
@Override
public void propertyChange(
        PropertyChangeEvent event) {
    position = (Point) event.getNewValue();
    repaint();
}
Fragment 3 of 3
model.pcs.addPropertyChangeListener(this);

Bouncing Ball - Controller1 fragment

Fragment 1 of 1
/**
 * This is an example of the basic "Bouncing
 * Ball" animation, making use of the Model-
 * View-Controller design pattern and the
 * Timer and PropertyChangeSupport classes.
 */

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.Timer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * The Controller sets up the GUI and handles
 * the controls (in this case, buttons).
 * @author David Matuszek
 */
public class Controller extends JFrame {
    JPanel buttonPanel = new JPanel();
    JButton runButton = new JButton("Run");
    JButton stopButton = new JButton("Stop");
    Timer timer;

    /**
     * The Model is the object that does all
     * the computations. It is independent
     * of the Controller and View objects.
     */
    Model model;

    /**
     * The View object displays what is
     * happening in the Model.
     */
    View view;

    /**
     * Runs the bouncing ball program.
     * @param args Ignored.
     */
    public static void main(String[] args) {
        Controller c = new Controller();
        c.init();
        c.display();
    }

    /**
     * Sets up communication between the
     * Model and the View.
     */
    private void init() {
        model = new Model();
        view = new View(model);
    }

    /**
     * Displays the GUI.
     */
    private void display() {
        layOutComponents();
        attachListenersToComponents();
        setSize(300, 300);
        setVisible(true);
        setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);
    }

    /**
     * Arranges the components in the GUI.
     */
    private void layOutComponents() {
        setLayout(new BorderLayout());
        this.add(BorderLayout.SOUTH, buttonPanel);
        buttonPanel.add(runButton);
        buttonPanel.add(stopButton);
        stopButton.setEnabled(false);
        this.add(BorderLayout.CENTER, view);
    }

    /**
     * Attaches listeners to the components
     * and schedules a Timer.
     */
    private void attachListenersToComponents() {
        // The Run button starts the Model
        runButton.addActionListener( event -> {
             runButton.setEnabled(false);
             stopButton.setEnabled(true);
             model.start();
        });
        // The Stop button pauses the Model
        stopButton.addActionListener(event -> {
            runButton.setEnabled(true);
            stopButton.setEnabled(false);
            model.pause();
        });
        // When the window is resized,
        // the Model is given the new limits
        this.addComponentListener(
                new ComponentAdapter() {
            @Override
            public void componentResized(
                    ComponentEvent arg0) {
                model.setLimits(view.getWidth(),
                               view.getHeight());
            }
        });
    }
}

Bouncing Ball - Model1 fragment

Fragment 1 of 1
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Point;
import javax.swing.Timer;
import java.beans.*;

/**
 * This is the Model class for a bouncing ball.
 * It defines a PropertyChangeSupport object.
 * @author David Matuszek
 */
public class Model {
    private Point position = new Point(0, 0);
    private int xLimit, yLimit;
    private int dx = 6;
    private int dy = 4;
    private Timer timer;
    public PropertyChangeSupport pcs;

    public Model() {
        pcs = new PropertyChangeSupport(this);
        position = new Point(0, 0);
        timer = new Timer(
                40, new ActionListener() {
            @Override
            public void actionPerformed(
                ActionEvent e) {
                    makeOneStep();
                }
        });
        timer.stop();
    }

    /**
     * Sets the "walls" that the ball should
     * bounce off from.
     * @param xLimit The right wall (in pixels).
     * @param yLimit The floor (in pixels).
     */
    public void setLimits(int xLimit,
                          int yLimit) {
        this.xLimit = xLimit - 20;
        this.yLimit = yLimit - 20;
        position =
           new Point(Math.min(position.x, xLimit),
                     Math.min(position.y, yLimit));
    }

    /**
     * @return The balls X position.
     */
    public Point getPosition() {
        return position;
    }

    /**
     * Tells the ball to start moving. This is
     * done by starting a Timer that periodically
     * tells the ball to make one "step."
     */
    public void start() {
        timer.start();
    }

    /**
     * Tells the ball to stop where it is.
     */
    public void pause() {
        timer.stop();
    }

    /**
     * Tells the ball to advance one step
     * in the direction that it is moving.
     * If it hits a wall, its direction
     * of movement changes. The method
     * then fires a PropertyChange event.
     */
    public void makeOneStep() {
        // Do the work
        position.x += dx;
        if (position.x < 0 ||
            position.x >= xLimit) {
          dx = -dx;
          position.x += dx;
        }
        position.y += dy;
        if (position.y < 0 ||
            position.y >= yLimit) {
          dy = -dy;
          position.y += dy;
        }
        this.pcs.firePropertyChange(
                "position", null, position);
    }
}

Bouncing Ball - View1 fragment

Fragment 1 of 1
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.beans.*;
import javax.swing.JPanel;

/**
 * The View displays what is going on in
 * the Model. In this example, the Model
 * is only a single bouncing ball.
 * @author David Matuszek
 */
public class View extends JPanel
        implements PropertyChangeListener {
    Point position = new Point(0, 0);
    /** This is what we will be viewing. */
    Model model;

    /**
     * Constructor. Adds a listener for
     * PropertyChange events.
     * @param model The Model whose working
     *              is to be displayed.
     */
    View(Model model) {
        this.model = model;
        model.pcs.addPropertyChangeListener(this);
    }

    /**
     * Displays what is going on in the Model.
     * Note: This method should NEVER be
     * called directly; call repaint() instead.
     * @param g The Graphics on which to paint.
     * @see javax.swing.JComponent#paint(
     *      java.awt.Graphics)
     */
    @Override
    public void paint(Graphics g) {
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(Color.RED);
        position = model.getPosition();
        g.fillOval(position.x, position.y, 20, 20);
    }

    /**
     * Repaints the JPanel when a
     * PropertyChangeEvents is received.
     * @param evt Contains the ball's position.
     */
    @Override
    public void propertyChange(
            PropertyChangeEvent evt) {
        position = (Point) evt.getNewValue();
        repaint();
    }
}