View page as slide show

Click presentation screen icon to the right to see the slide show.

Overview of Chapters 1, 2 and 4

Main concepts you should know.

Read through the chapters carefully by next time.

1.1-1.3: Java Fundamentals

Comments. javadoc See this Javadoc documentation by Oracle.

Primitive data types and wrapper classes. autoboxing and auto-unboxing

References

Named constants

Implicit and explicit type conversion

Arrays. multidimensional.

if, else, else if

switch, case, break, default, integral values

while, for, break, continue.

Let's do an example of for loops for arrays. Say we have an array of first names and want to print all of the elements.

1.4 Program Structure. Files

One class per .java file.

Each class should have a

    public static void main (String[] args) {
    }

package and import statments.

Each .java file is compiled into a .class file.

1.4 Program Structure. Class Declarations

public class MyClassName {    }      
 
abstract public class MyClassName {    }
 
final public class MyClassName {   }
 
class MyClassName {    }
 
public class MyClassName extends YourClassName {    }
 
public class MyClassName implements YourInterfaceName {    }

1.4 Program Structure. Class Data Fields

public class MyClassName {
 
    public int number;  // Available everywhere, if class is public.
    public static int number; // One variable shared by all class instances.
    public final int NUMBER;  // Constant. 
 
    private int number; // Only available in this class.
 
    protected int number; // Available in this class, subclasses, and package.
 
}

1.4 Program Structure. Class Methods

public class MyClassName {
 
    public int getCount() {     // Available everywhere, if class is public.
        return 42;
    }
 
    public static int getCount() {  // Can only access static member variables.
        return 42;
    }
 
    public final int getCount() {   // Cannot be overriden in a subclass.
        return 42;
    }
 
    public abstract int getCount(); // Must be overriden in a subclass.
 
    private int getCount() {     // Only available in the class.
        return 42;
    }
 
    protected int getCount() {     // Availabl in the class, subclasses and package.
        return 42;
    }
}

1.4 Program Structure. Class Constructors

If you do not define one, the compiler makes for you a no-argument, default constructor, like

    public MyClass() {
    }

Usually you will want to control initialization of member variables in the no-argument (default) constructor.

    public MyClass() {
        count = 0;
    }

Will probably want multiple constructors

  • different argument types
  • different numbers of arguments

Compiler will not make you a no-argument, default constructor if you define at least one constructor with arguments.

1.4 Program Structure. Class Inheritance

Remember the extends and super keywords.

public class Parent {
    protected String name;
 
    public Parent(String nameArg) {
        name = nameArg;
    }
}
public class Child extends Parent {
 
    public Child(String nameArg) {
 
        ... WHAT GOES HERE? ...
 
    }
}

1.4 Program Structure. Class Inheritance

Remember the extends and super keywords.

public class Parent {
    protected String name;
 
    public Parent(String nameArg) {
        name = nameArg;
    }
}
public class Child extends Parent {
 
    public Child(String nameArg) {
 
        super(nameArg);
 
    }
 
    public String getName() {
 
        ... AND WHAT GOES HERE? ...
}

1.4 Program Structure. Class Inheritance

Remember the extends and super keywords.

public class Parent {
    protected String name;
 
    public Parent(String nameArg) {
        name = nameArg;
    }
}
public class Child extends Parent {
 
    public Child(String nameArg) {
 
        super(nameArg);
 
    }
 
    public String getName() {
 
        return name;
}

1.5 Predefined Java Classes

  • Object All classes inherit from this.
    • public boolean equals(Object obj)
    • public String toString()
    • protected void finalize()
  • java.util.Arrays
    • static methods to be applied to java arrays
    • int[] bunch = new int[10];
    • Arrays.fill(bunch,-99);
    • Arrays.toString(bunch)

1.5 Predefined Java Classes

  • String Immutable
    • String string1 = “how boring ”;
    • int result = string1.compareTo(“what?”);
    • String result = “hello” + “world” + '!';
    • String result = string1.substring(4,7);
    • int index = string1.indexOf(“ing”,3);
    • String result = string1.replace('o','_');
    • String result = string1.trim();
  • StringBuffer Like String , but mutable.
    • StringBuffer string1 = “January”;
    • string1.append(”,March”); string1 is modified.
    • string1 = string1.append(”,March”); Not necessary.
    • string1.insert(7, ”,february”);
    • string1.insert(string1.indexOf(”,Mar”,0), ”,february”);
    • string1.delete(0,8);
    • string1.setCharAt(8,'F');
    • string1.replace(0,6,”Jan”);

1.5 Predefined Java Classes

  • java.util.StringTokenizer
    • StringTokenizer input = StringTokenizer(“add 1 and 2\n multiply 3 and 4”, ” \n”);
    • String token = input.nextToken();
    • boolean more = input.hasMoreTokens();
MyClass.java
import java.util.StringTokenizer;
 
class MyClass {
 
   public static void main(String[] args){
 
      StringTokenizer input = new StringTokenizer("add 1 and 2\n multiply 3 and 4", " \n");
 
      while (input.hasMoreTokens()) {
         System.out.println(input.nextToken());
      }
   }
}

1.6 Java Exceptions

try {
   ...
}
catch (Exception exception) {
    System.out.println("Oops!");
    System.out.println(exception);
}
finally {  // optional
  ...
}

Checked Exceptions

  • Subclasses of java.lang.Exception
  • Must be handled or explicitly thrown from methods
  • Signify serious problems. Execution should halt.

Runtime Exceptions

  • Subclasses of java.lang.RuntimeException (which is subclass of java.lang.Exception)
  • Not required to be handled or explicitly thrown.
  • Not so serious.

1.7 Text Input

  • java.util.StringTokenizer
    • Integer.parseInt
    • Double.parseDouble
  • java.util.Scanner
    • String next()
    • boolean nextBoolean()
    • float nextFloat()
    • double nextDouble()
    • int nextInt()
MyClass.java
import java.util.Scanner;
 
public class MyClass {
 
    public static void main(String[] args) {
 
        // Read city, temperature pairs
 
        Scanner input = new Scanner(System.in);
 
        while (input.hasNext()) {
 
            String city = input.next();
            float temperature = input.nextFloat();
 
        }                   
    }
}

1.7 Text Output

System.out.print, System.out.println, System.out.printf

    System.out.println("Simple text output with my age as" + 42 + '!');
 
    System.out.printf("Simple text output with my %s as %d%c","age",42,'!');

Conversion Character Data Type
b boolean
s String
c character
d decimal integer
e decimal number (12.e3)
f decimal number (12000)

[width].[precision]conversion

%10.2f %13.3e %8f %3d

1.8 File Input

  • java.io.BufferedReader and java.io.FileReader
MyClass.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
 
public class MyClass {
 
   public static void main(String[] args) {
 
      BufferedReader input;
      String line;
      StringTokenizer tokenizer;
 
      try {
 
         input = new BufferedReader(new FileReader("citytemps.dat"));
         while ((line = input.readLine()) != null) {
 
            tokenizer = new StringTokenizer(line);
            String city = tokenizer.nextToken();
            double temperature = Double.parseDouble(tokenizer.nextToken());
 
            System.out.printf("%20s %5.1f\n",city,temperature);
         }
      }
      catch (IOException e) {
         e.printStackTrace();
         System.exit(1);
      }
   }
}

1.8 File Input

> javac MyClass.java
> java MyClass
java.io.FileNotFoundException: citytemps.dat (No such file or directory)
	at java.io.FileInputStream.open(Native Method)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at java.io.FileInputStream.<init>(FileInputStream.java:97)
	at java.io.FileReader.<init>(FileReader.java:58)
	at MyClass.main(MyClass.java:16)

What's wrong?

1.8 File Input

> javac MyClass.java
> java MyClass
java.io.FileNotFoundException: citytemps.dat (No such file or directory)
	at java.io.FileInputStream.open(Native Method)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at java.io.FileInputStream.<init>(FileInputStream.java:97)
	at java.io.FileReader.<init>(FileReader.java:58)
	at MyClass.main(MyClass.java:16)

What's wrong?

Yep! Missing the data file.

citytemps.dat
Fort-Collins 87.2
Greeley 83.523
Estes-Park 68
Pueblo 120.42

Now, try again.

> java MyClass
        Fort-Collins  87.2
             Greeley  83.5
          Estes-Park  68.0
              Pueblo 120.4

1.8 File Output

  • java.io.FileWriter and java.io.PrintWriter

Let's say we want to output to a file named results.dat the names of all the cities and their average temperatures.

Add to the previous file:

import java.io.FileWriter;
import java.io.PrintWriter;
 
PrintWriter output;
output = new PrintWriter(new FileWriter("results.dat"));
    // in loop
    output.printf("%s ",city);
    numberOfCities ++;
    temperatureSum += temperature;
output.printf("%4.1f\n",temperatureSum / numberOfCities);

1.8 File Input and Output

MyClass.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import java.io.FileWriter;
import java.io.PrintWriter;
 
public class MyClass {
   public static void main(String[] args) {
 
      BufferedReader input = null;  // so javac does not complain.
      String line;
      StringTokenizer tokenizer;
      PrintWriter output = null;
      try {
         input = new BufferedReader(new FileReader("citytemps.dat"));
         output = new PrintWriter(new FileWriter("results.dat"));
         double temperatureSum = 0.0;
         int numberOfCities = 0;
         while ((line = input.readLine()) != null) {
            tokenizer = new StringTokenizer(line);
            String city = tokenizer.nextToken();
            double temperature = Double.parseDouble(tokenizer.nextToken());
 
            System.out.printf("%20s %5.1f\n",city,temperature);
            output.printf("%s ",city);
            numberOfCities ++;
            temperatureSum += temperature;
         }
         output.printf("%4.1f\n",temperatureSum / numberOfCities);
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(1);
      } finally {
         try {
            input.close();
            output.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      } // end finally
   }
}

Run it

> javac MyClass.java
> java MyClass
        Fort-Collins  87.2
             Greeley  83.5
          Estes-Park  68.0
              Pueblo 120.4
> more results.dat
Fort-Collins Greeley Estes-Park Pueblo 89.8

2.1 Problem Solving and Software Engineering

  • preconditions
  • postconditions
  • invariants
  • loop invariants
  • assertions
assert count < 100 : "count of" + count + "must be less than 100";

2.2 Object-Oriented Design

  • procedural abstraction
    • Design top-down.
    • Say “what” not “how”, until at bottom.
  • data abstraction
    • Design the interface first, the”abstract data type” (ADT).
    • Say “what” not “how”, until ready to implement for particular kind of data.
    • Hide all information not needed by ADT user.
  • object-oriented design
    1. encapsulation: data and operations
    2. inheritance: implement common parts at highest level
    3. polymorphism: appropriate operations chosen at run time
  • Unified Modeling Language (UML)
    • tools for designing graphically
    • independent of implementation language
    • can convert between languages and UML

2.3 Key Issues in Programming

  • modularity
  • modifiability
  • ease of use
  • fail-safe programming
  • style
    • Documentation
      • initial comment
        • statement of purpose
        • author and date
        • description of program's input and output
        • description of how to use the program
        • assumptions such as the type of data expected
        • statement of exceptions, what can go wrong
        • Brief overview of major classes
      • initial comments in each class, purpose and data
      • initial comments in each method, purpose, pre and postconditions and called methods
      • comments in the body of each method to explain important features or subtle logic.
  • debugging
if (debug) {
   System.out.println( ..... );
}

4.1 Abstract Data Types (ADTs)

The Walls

  • ADT implementation hidden from the user (programmer)
  • The user has limited access through a window of the wall.
  • The designer/implementor of the ADT also designs the window.
  • Window is “what” you can do with the ADT, not “how” it is implemented.
  • But, you may want to know something about “how”, to decide which ADT to use.

4.2 A List ADT

Say you need a way to store a bunch of pieces of information, all with similar structure. What do you want the window to look like?

First, write down in English what you want the storage to do. Then write some pseudocode for each thing.

4.2 A List ADT

Say you need a way to store a bunch of pieces of information, all with similar structure. What do you want the window to look like?

First, write down in English what you want the storage to do. Then write some pseudocode for each thing.

storage = create() Create the storage
storage.add(oneExample) Add one item to the storage.
storage.get(23) Get the item at position 23
storage.remove(12) Remove from storage the item at position 12
storage.find(thisExample) Search storage for an item matching this example
storage.size() How many items are currently in storage?

4.2 ADT Axioms

Invariants: statements that are always true.

What are some examples for the List ADT?

4.2 ADT Axioms

Invariants: statements that are always true.

What are some examples for the List ADT?

If you insert an item into the position of an ADT list, retrieving the item will result in .

list = create()
list.add(i, x)
list.get(i) = x

or

list.add(i,x).get(i) = x

4.3 Implementing ADTs

Encapsulation: hide most of data fields (member variables) and member methods

Java interfaces

  • Windows in the wall
  • Multiple ADT implementations guaranteed to have same window

Read the example array-based implementation of the ADT list.

Notice

  • ListException class
  • IntegerListInterface interface
Recent changes RSS feed CC Attribution-Share Alike 3.0 Unported Driven by DokuWiki