Click presentation screen icon to the right to see the slide show.
Main concepts you should know.
Read through the chapters carefully by next time.
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.
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.
public class MyClassName { } abstract public class MyClassName { } final public class MyClassName { } class MyClassName { } public class MyClassName extends YourClassName { } public class MyClassName implements YourInterfaceName { }
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. }
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; } }
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
Compiler will not make you a no-argument, default constructor if you define at least one constructor with arguments.
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? ... } }
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? ... }
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; }
Object All classes inherit from this.public boolean equals(Object obj)public String toString()protected void finalize()java.util.Arraysint[] bunch = new int[10];Arrays.fill(bunch,-99);Arrays.toString(bunch)String ImmutableString 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”);java.util.StringTokenizerStringTokenizer input = StringTokenizer(“add 1 and 2\n multiply 3 and 4”, ” \n”);String token = input.nextToken();boolean more = input.hasMoreTokens();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()); } } }
try { ... } catch (Exception exception) { System.out.println("Oops!"); System.out.println(exception); } finally { // optional ... }
Checked Exceptions
java.lang.ExceptionRuntime Exceptions
java.lang.RuntimeException (which is subclass of java.lang.Exception)
|
|
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
java.io.BufferedReader and java.io.FileReader 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); } } }
> 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?
> 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.
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
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);
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 } }
> 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
assert count < 100 : "count of" + count + "must be less than 100";
if (debug) {
System.out.println( ..... );
}
The Walls
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.
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? |
Invariants: statements that are always true.
What are some examples for the List ADT?
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
Encapsulation: hide most of data fields (member variables) and member methods
Java interfaces
Read the example array-based implementation of the ADT list.
Notice
ListException classIntegerListInterface interface