320 likes | 440 Views
CS110 Lecture 23 Thursday, April 22, 2004. Announcements hw10 due tonight exam next Tuesday, April 27 final exam Wednesday, May 20, 8:00 AM McCormack, Floor 01, Room 0608 Agenda Questions Characters Strings Files. Characters. Type char is primitive in Java
E N D
CS110 Lecture 23Thursday, April 22, 2004 • Announcements • hw10 due tonight • exam next Tuesday, April 27 • final exam Wednesday, May 20, 8:00 AM McCormack, Floor 01, Room 0608 • Agenda • Questions • Characters • Strings • Files Lecture 23
Characters • Type char is primitive in Java • A char is really an int • In the old days characters were just small integers • The ASCII character set contains 128 characters numbered 0-127 • one byte, 8 bits: 00000000 to 11111111 in binary (0-255 decimal) • ascii codes are the bytes with the high bit 0 • Googling for ASCII code will find lots of information Lecture 23
Characters (continued) • Printable characters are 32-126 (decimal) – other bytes are • visible in emacs (look at a class file) • used for emacs commands, like ^S • To represent them in Java use escape character: \ • ‘\ddd’ // ddd is base 8 number < 256 • System.out.println(‘\007’); //ring bell • ‘\n’, ‘\b’, ‘\t’, ‘\”’, ‘\\’ • See Escape.java in joi/examples/ Lecture 23
Unicode • Unicode extends character set to 16 bits (0 to 216-1) for kanji, Arabic, Hebrew, mathematics, … • Type char in Java really is a 16 bit int • We usually write these values as hexadecimal strings: 16 bits is four hex digits • ‘\uXXXX’ (X = 0, 1, …, 9, A, … , F) • Internationalization (I18N) • locale • collation sequence • time, date, number format Lecture 23
classCharacter • Wrapper class for primitive type char • Static methods to process charvalues • Use Character to save charin a Collection (happens automatically in Java 1.5) • Character(char ch) // constructor • public char charValue() • static int getNumericValue(char ch) // unicode value • static boolean isDigit(char ch) • static char toUpperCase(char ch) • … see API for more Lecture 23
Strings ... • The String API - lots there to use when needed • constructors • equality • comparisons • substrings • character contents • changing String contents (not) • finding meaning in Strings • Read (some of) String.java • See StringDemo.java in JOI/examples Lecture 23
String constructors • String s; • s = “hello”; //common and convenient • s = new String(“hello”); • char[ ] charArray = {‘O’, ‘K’} ; s = new String( charArray ); • String t = new String(s); Lecture 23
String matches and searches boolean equals(String anotherString); boolean equalsIgnoreCase(String anotherString); int compareTo(String anotherString); // +,-,0 boolean startsWith(String prefix); boolean endsWith(String suffix); int indexOf(int ch); // -1 if not found int indexOf(String str); int indexOf(String str, int fromIndex); int lastIndexOf(...); Lecture 23
Equality • In Java, “==” means “two variables have same value” • Box and arrow pictures help: • same value for primitive types is just what you expect • same value for reference types: arrow points to the same Object • In Object public boolean equals(Object o) { return this == o; } • Override equals in class String extends Object to compare Strings character by character (that’s what equality for String should mean). Lecture 23
Equality String s = “hello”; String t = “hello”; s == t false (sometimes) s.equals(t) true s.equals(“hello”) true “hello”.equals(s) true (weird) • See EqualsDemo.java in JOI/examples Lecture 23
String.java • About 1/3 of it is comment! public final class String { … } • Implementation uses a character array: private char[] value; private int offset; private int count; • The characters that make up this String are stored in value at positions offset … offset+count-1 (usually offset = 0) Lecture 23
Comparing Strings public int compareTo(String s) // not boolean “hello”.compareTo(“help!”) -4 // = ‘l’ - ‘p’ “hello”.compareTo(“hell”) 1 // 5-4 (lengths) x.compareTo(y) == 0 just when x.equals(y) compareTo is wonderful for sorting (alphabetizing) Lecture 23
compareTo pseudocode • march through the character arrays looking for first char difference (be sure not to run off the end, since lengths may differ) • if you find a char difference, return it (numerically) • if no difference when you reach the end of the shorter string, return the difference in lengths (0 if the same) Lecture 23
public int compareTo(String anotherString) { int len1 = this.count; // a field int len2 = anotherString.count; int n = Math.min(len1, len2); char v1[] = this.value; // another field char v2[] = anotherString.value; int i = offset; // pretend offset=0 int j = anotherString.offset; while (n-- != 0) { // code like C char c1 = v1[i++]; // i++ in loop char c2 = v2[j++]; if (c1 != c2) { // (first) mismatch return c1 - c2; // subtract ints } } return len1 - len2; // same length? } from String.java Lecture 23
Substrings String s = “hello, world”; s.startsWith(“hello”) returns true s.substring(3,8) returns “lo, w” // from index 3 to index 8-1 s.substring(7) returns “world” // index 7-end s.indexOf(“world”) returns 7 s.indexOf(“hello”) returns 0 s.indexOf(“foo”) returns -1 Lecture 23
Seeing characters in a String String s = “hello”; for (int i = 0; i < s.length(); i++){ char c = s.charAt(i); // do whatever with c } Lecture 23
Changing String contents (NOT) • These methods return a new String: they do not change the String getting the message! • s.toUpperCase() returns “HELLO, WORLD” • s.replace(‘o’,‘x’) returns “hellx, wxrld” • s.concat(“!”) returns “hello, world!” • s += “!” returns “hello, world!” • s.concat(‘!’) returns “hello, world!” • “ x y z \t\b”.trim() returns “x y z” Lecture 23
Methods Returning/Constructing new Strings concat(String str); //Can also use + replace(char old, char new); // Not in place! substring(int beginIndex); // new String! substring(int beginIndex, int endIndex); toLowerCase(); // new String! toLowerCase(Locale locale); toUpperCase(); toUpperCase(Locale locale); trim(); Lecture 23
Class StringBuffer • Like a String, but with direct access to char contents – therefore mutable • Much more efficient StringBuffer buf = new StringBuffer("World"); buf.insert(0, "Jello, "); buf.append("!"); buf.setCharAt(0,'H'); // now "Hello, World!" buf.reverse(); // now "!dlroW ,olleH" String s = buf.toString(); Lecture 23
Conversions • Strings have no meaning: “1001” is not 1001 • To convert a String to an integer: int n; String s = “1001”; try { n = Integer.parseInt(s); // String int } catch (NumberFormatException e) { // take corrective action } Lecture 23
Conversions • To convert an integer to a String int n = 1001; String s; s = String.valueOf(n); // “1001” s = “” + n; // rely on smart concatenation s = Integer.toHexString(n) // “3e9” s = Integer.toBinaryString(n) // “1111101001” • More such static methods in String, Integer, Double • To convert any Object to a String: Object obj … ; s = obj.toString(); s = “” + obj; // rely on smart concatenation Lecture 23
I/O programming • I/O = input/output • I/O is hard • deals with real world beyond programmers control • Output easier than input (programmer knows more) • System.out.println() is straightforward • Terminal readLine() wraps hard to use System.in • java.io package provides lots of useful classes • I/O programming may throw many Exceptions • Even good tools are hard to use when topic is hard • Count on borrowing from code that works Lecture 23
public class File • Information about files, not their contents (Juno should be redesigned this way) • Constructors File(String path) or (String path, String name) or(File dir, String name) • Methods boolean exists(), isFile(), isDirectory(),canRead(), canWrite(); long length(), lastModified(); boolean delete(), mkdir(), renameTo(File dest); String getName(), getParent(), getPath(),getAbsolutePath() Lecture 23
Useful final Fields • In class File Windows Unix File.pathSeparator; ";" ":" File.separator; "\" "/" • In class System System.getProperty ("line.separator") "\n\r" "\n public static final FileDescriptor in; public static final FileDescriptor out; public static final FileDescriptor err; Lecture 23
Profile • main in Profile.java (pseudocode): declare and initialize counters open Java source for reading while (get a line from source file) classify line, increment counters close source file print results Lecture 23
Copy • Classic example dealing with file contents • Write Windows command line copy in Java: • java Copy sourcefile targetfile • main in Copy.java (pseudocode): open sourcefile for reading open targetfile for writing while (get stuff from sourcefile) write stuff to targetfile close both files Lecture 23
Copy1.java FileReader inStream = null; // 26, outside try FileWriter outStream = null; // 27, outside try try { inStream = new FileReader(args[0]); // 32 outStream = new FileWriter(args[1]); // 33 while (…) { // 36-38 copy loop } catch // various errors • 40: faulty command line input - give usage message • 44: source file not found (or not readable) target file not writeable • 47: something went wrong in actual read/write Lecture 23
Keyword finally try { } catch() { { finally { code here runs whether or not try works } • Copy1.java 53, 61: close files whether or not there was an error in processing (underlying OS may limit number of files you may have open) • try (lines 51, 63) since even closing a file may throw an Exception Lecture 23
FileReader/FileWriter i/o int ch; // character read as an int (line 28) while ((ch = inStream.read()) != -1) { // 36 outStream.write(ch); } • Java (and C) idiom: assignment statement x = ygets value of x , so (ch = inStream.read()) != EOF • sends instream a read() message • assigns returned int to variable ch • compares that int to EOF, declared final static, used by read() to signal end of file • result is true or false, so useful inside while( ) Lecture 23
Copy2 using BufferedReader/Writer BufferedReader inStream = null;// lines 24, 25 BufferedReader inStream = null String line; try inStream = new BufferedReader ( new FileReader(argv[0])); outStream = ... while ((line = inStream.readLine()) != null) outStream.write( line ); outStream.newLine(); // no ‘\n’ in line • BufferedReader/Writer handle whole lines (Strings) • readLine returns null at EOF Lecture 23
data coming in data going out program Streams/filters • data can be characters, Strings, bytes, objects,… • Streams connect to file, terminal, String, net, … • Always use same methods: read, write (polymorphism) • Examples: • copy: stream of characters, or of lines (Strings) • Profile: stream of lines, program counts kinds • TV: input stream from cable, output stream to screen Lecture 23
*Stream classes Lecture 23