1 / 74

Week 2

Week 2. “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Lab Problem. Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking in Java”. Notes From “Just Java”. Chapter 4. Comments. // a single line comment /* a multi-line comment */

sunee
Download Presentation

Week 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Lab Problem Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking in Java”

  2. Notes From “Just Java” Chapter 4

  3. Comments // a single line comment /* a multi-line comment */ /** a javadoc comment */ javadoc MyDocumentedProgram.java produces .html files

  4. Casts // we can cast a float or double to an int with truncation float f = 3.142; int i = (int) f; // we can cast an int to a short with truncation short s = (short) 123456; System.out.println(s); C:\McCarthy\www\JustJava\Examples>java TestCast -7616

  5. Char type 16-bit Unicode A single char constant looks like ‘A’ in single quotes. May be used as an unsigned short char s = (char) -1; int x = s; System.out.println(x); C:\McCarthy\www\JustJava\Examples>java TestUnsigned 65535

  6. String Class – use .equals() public class TestString { public static void main(String a[]) { String x = "A simple string"; String y = "A simple"; y = y + " string"; if(x == y) System.out.println("They are equal with == "); else if(x.equals(y)) System.out.println("They are equal with .equals()"); else System.out.println("Not equal with == or with .equals()"); } } C:\McCarthy\www\JustJava\Examples>java TestString They are equal with .equals()

  7. Notes From “Just Java” Chapter 5

  8. Forward References // works fine class Fruit { void foo() { grams = 22; } int grams; }

  9. Arrays Two steps: int a[]; a = new int[10]; Fruit b[]; b = new Fruit[345]; // no Fruit objects yet // don’t call b[4].foo() See book for initialization syntax.

  10. Arrays can be cloned public class TestSheep { public static void main(String a[]) { int sheep[] = new int[10]; sheep[4] = 99; int baaa[] = (int[]) sheep.clone(); System.out.println(baaa[4]); } } C:\McCarthy\www\JustJava\Examples>java TestSheep 99

  11. Most operators are the same as c Order of operations is clearly defined in Java. Precedence says which operators bind first. Associativity is the tie breaker when operators are of equal precedence. Order of operations is strictly left to right in Java.

  12. Example public class TestSheep { public static void main(String a[]) { int i = 8; int m[] = new int[10]; m[i] = (i = 2) * i++; System.out.println("m[8] == " + m[8] + " and i == " + i); } } C:\McCarthy\www\JustJava\Examples>java TestSheep m[8] == 4 and i == 3

  13. What Happens on Overflow? When an integer valued expression is too big for its type the lowend bytes are stored and we have no report of overflow. byte b = (int) 10000; An exception is thrown for division by 0.

  14. Example public class TestOverflow { public static void main(String a[]) { byte i = 8; byte m = 0; i = (byte) (i % m); } } C:\McCarthy\www\JustJava\Examples>java TestOverflow Exception in thread "main" java.lang.ArithmeticException: / by zero at TestOverflow.main(TestOverflow.java:7)

  15. Adding a try/catch block public class TestOverflow { public static void main(String a[]) { try { byte i = 8; byte m = 0; i = (byte) (i % m); } catch(ArithmeticException e) { System.out.println("That did not go well"); } System.out.println("Terminating"); } } C:\McCarthy\www\JustJava\Examples>java TestOverflow That did not go well Terminating

  16. Notes From Bruce Eckel’s Thinking in Java “Just Java” Chapter 13 Simple I/O

  17. JAVA I/O and Client/Server

  18. The Java IO System • Different kinds of IO – Files, the console, blocks of memory, network connections • Different kinds of operations – Sequential, random- access, binary, character, by lines, by words, etc. Source: Eckel

  19. The Java IO Library Design • Seems like a lot of classes • Also seems at first like an odd design – Not typically how you think of using classes – Can require a lot of typing • There is a plan – A learning experience in class design – The “Decorator” Design Pattern Source: Eckel

  20. InputStream and OutputStream • InputStream (Abstract class) This abstract class is the superclass of all classes representing an input stream of bytes. • OutputStream (Abstract class) This abstract class is the superclass of all classes representing an output stream of bytes. Source: Eckel

  21. Types of InputStream ByteArrayInputStream read memory block StringBufferInputStream read from String (not buffer) FileInputStream read from file PipedInputStream read from another thread SequenceInputStream reads from several streams FilterInputStream Decorators subclass this class. A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality.

  22. Two important FilterInputStream classes -- Decorators • • DataInputStream (binary data) • Full interface for reading primitive and built- in types • Construct with an InputStream • When reading a float, four bytes are read • • BufferedInputStream • Adds buffering to the stream (usually do this) • Construct with an InputStream

  23. FileInputStream - Reading Data From a File BufferedInputStream – Buffers input DataInputStream – Reading binary data readLine() -- deprecated DataInputStream BufferedInputStream Decorators FileInputStream Source of data String File Name

  24. // copy a binary or text file import java.io.*; public class CopyBytes { public static void main( String args[]) throws IOException { DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream(args[0]))); DataOutputStream out = new DataOutputStream( new BufferedOutputStream( new FileOutputStream(args[1])));

  25. byte byteIn; try { while(true) { byteIn = in.readByte(); out.writeByte(byteIn); } } catch(EOFException e) { in.close(); out.close(); } } }

  26. Types of OutputStream Writes to: ByteArrayOutputStream Block of memory FileOutputStream File PipedOutputStream “Pipe” (to another thread) FilterOutputStream Decorators subclass this class

  27. Three important FilterOutputStream classes -- Decorators • DataOutputStream – Full interface for writing primitive and built-in types; complements DataInputStream for portable reading & writing of data DataOutputStream is normally for storage. • PrintStream – Allows primitive formatting for data display. Not as nice a c’s printf(). Converts arguments to ASCII or EBCDIC. Use PrintWriter when writing Unicode characters rather than bytes. • BufferedOutputStream – Adds a buffer(usually do this).

  28. Writing ASCII Data To A File PrintStream writes in the platform’s default encoding. PrintStream BufferedOutputStream Decorators FileOutputStream File Name Sink String

  29. // Writing ASCII data to a file import java.io.*; public class OutPutDemo { public static void main(String args[]) throws FileNotFoundException{ PrintStream out = new PrintStream( new BufferedOutputStream( new FileOutputStream("IODemo.out"))); out.println("Hello world...on a file"); out.close(); } }

  30. DataOutPutStream is for binary output. DataInputStream is for reading binary. DataOutputStream BufferedOutputStream Decorators FileOutputStream Sink String

  31. // Writing data to a file In Binary not ASCII import java.io.*; public class OutPutDemo { public static void main(String args[]) throws FileNotFoundException, IOException { DataOutputStream out = new DataOutputStream ( new BufferedOutputStream( new FileOutputStream("Binary.out"))); out.writeDouble(3.34); // can’t view this!! out.writeDouble(2.33); out.close(); } }

  32. Readers and Writers • New in Java 1.1 • Provide Unicode-compliant, character-based I/O • Similar in structure to the InputStream and OutputStream • “byte” hierarchy

  33. PrintWriter has replaced PrintStream for text output. PrintWriter BufferedWriter Decorators FileWriter String Sink

  34. // Writing data to a file -- improves on the old PrintStream import java.io.*; public class OutPutDemo { public static void main(String args[]) throws FileNotFoundException, IOException { PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter("IODemo.out"))); out.println("Hello world...on a file"); out.close(); } }

  35. Converting from an 8-bit InputStream to 16-bit Unicode BufferedReader Converts from an InputStream to a Reader InputStreamReader Inputstream A System.in object is of type InputStream

  36. import java.io.*; public class InputDemo { public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); System.out.println("What is your name?"); String name = in.readLine(); System.out.println("Hello "+ name); } }

  37. BufferedReader InputStreamReader Reader FileInputStream InputStream String

  38. import java.io.*; // Read and write an ASCII file public class InputDemo { public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream("IODemo.in"))); String line; while((line = in.readLine()) != null) System.out.println(line); } }

  39. Some Examples // Demonstrate character I/O in Java // Count the number of a's and b's import java.io.*; public class CharIO { public static void main(String arg[]) throws IOException { InputStreamReader is = new InputStreamReader(System.in); System.out.println("Enter a line of text and I'll count the a's and b's");

  40. int aCount = 0; int bCount = 0; int i; // i should be an int so that we can detect a -1 from // the read method. -1 is returned when read() sees // <ctrl><z> in DOS i = is.read(); while(i != '\n') { char c = (char) i; if(c == 'a') aCount++; if(c == 'b') bCount++; i = is.read(); } System.out.println("a total = " + aCount + " b total = " + bCount); }}

  41. Some Examples Count lines // Demonstrate character I/O in Java // Echo the input and count lines import java.io.*; public class CharIO2 { public static void main(String arg[]) throws IOException { InputStreamReader is = new InputStreamReader(System.in);

  42. System.out.println("I'll echo and count lines"); int lineCount = 0; int i; i = is.read(); // -1 = EOF = <ctrl><z> in DOS while(i != -1) { char c = (char) i; if(c == '\n') lineCount++; System.out.print(c); i = is.read(); } System.out.println("--------------------------"); System.out.println("Line count == " + lineCount); } }

  43. Some Examples Using StringTokenizer // Read a line of integers // and display their sum import java.io.*; import java.util.*; // for StringTokenizer public class LineOfInts { public static void main(String arg[]) throws IOException {

  44. InputStreamReader is = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(is); StringTokenizer st; System.out.println("Enter a line of integers"); String s = br.readLine(); // use comma, space, and tab for delimeters t = new StringTokenizer(s, ", \t");

  45. int sum = 0; while(st.hasMoreElements()) { int val = Integer.parseInt(st.nextToken()); sum += val; } System.out.println("The sum is " + sum); } }

  46. Some Examples Formatting a double // display a number rounded to two decimal places // at least one digit to the left of the decimal point // # means a digit, 0 shows as absent import java.io.*; import java.text.*; public class FormattedOutput { static final double myDouble = 456.346; public static void main(String arg[]) throws IOException { DecimalFormat df = new DecimalFormat("0.00"); System.out.println(df.format(myDouble)); // displays 456.35 } }

  47. Some Examples // Java I/O // Read a double and display its square root import java.io.*; public class DoubleIO { public static void main(String arg[]) throws IOException { InputStreamReader is = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(is);

  48. double x; System.out.println("Enter a double and I'll compute the square root"); String inputString = br.readLine(); x = Double.parseDouble(inputString); // displays NAN if x < 0 System.out.println("The square root of "+x+" is " + Math.sqrt(x)); } }

  49. Object Serialization I/O • Save or restore an object • Works across networks (RMI arguments and return values) • Compensates for differences in operating systems • All relevant parts of an Object magically stored and retrieved; even “web of objects”

  50. Object serialization • Class must implement Serializable • Wrap a stream in a ObjectOutputStream (for writing) or ObjectInputStream (for reading) • Use writeObject( ) and readObject( )

More Related