Week 2 ObjectOriented Programming Javas Big Integer Class

Week 2 • Object-Oriented Programming • Java’s Big. Integer Class • Java I/O and Client/Server OOP, Java's Big. Integer Class and I/O 1

Object-Oriented Programming and Java’s Big. Integer Class • Abstraction The focus is on “what” not “how”. • Encapsulation Information hiding is used to promote modularity and the use of abstractions. • Polymorphism We may want to treat an object not as an instance of its specific type but as an instance of its base type. • Inheritance OOP promotes code reuse via the “is-a” relationship. • Composition OOP promotes code reuse via the “has-a” relationship. OOP, Java's Big. Integer Class and I/O 2

Using Java’s Big. Integer Class import java. math. *; public class Test. Big. Ints { public static void main(String args[] ) { Abstraction Encapsulation Big. Integer x = new Big. Integer("1234567890123" + "45678901234567890"); Big. Integer y = new Big. Integer("9393929292" + "9191919192"); Big. Integer z = x. multiply(y); System. out. println(z); } } OOP, Java's Big. Integer Class and I/O 3

The to. String() method public class Big. Integer { public String to. String() { A Big. Integer “is a” Object. The println() method calls to. String(). // Returns the decimal String representation of this // Big. Integer. // Overrides: to. String() in class Object } Polymorphism } OOP, Java's Big. Integer Class and I/O 4

Another Example import java. math. *; import java. util. *; bit. Length - bit. Length of the returned Big. Integer. public class Test. Big. Ints { public static void main(String args[] ) { A Random object assists with the computation. Big. Integer m = new Big. Integer(4, 10, new Random(2456)); Big. Integer n = new Big. Integer(4, 10, new Random(94)); certainty - a measure of the uncertainty that the caller is willing to tolerate. Prob(prime) = -10). 1 -(2 OOP, Java's Big. Integer Class and I/O 5 if(m. compare. To(n) < 0) System. out. println(m + " < " + n ); else System. out. println(m + " >= " + n ); } }

Consider compare. To() if(m. compare. To(n) < 0) System. out. println(m + " < " + n ); else System. out. println(m + " >= " + n ); public class Big. Integer extends Number implements Comparable Inheritance and Polymorphism Comparable is an interface that Big. Integer implements. The Big. Integer class therefore has a method called compare. To(). Any method foo(Comparable x) can be called with a Big. Integer. OOP, Java's Big. Integer Class and I/O 6

Another example import java. math. *; public class Test. Big. Ints { Big. Integer extends the abstract Number class. public static void main(String args[] ) { Big. Integer m = new Big. Integer("34"); foo(m); No problem } public static void foo(Number n) { long x = n. long. Value(); x++; System. out. println("x = " + x); } } OOP, Java's Big. Integer Class and I/O 7

Composition import java. math. *; class Big. Fraction { private Big. Integer numerator; private Big. Integer denominator; A Big. Fraction “has-a” Big. Integer numerator and a Big. Integer denominator. public Big. Fraction(Big. Integer num, Big. Integer denom) { numerator = num; denominator = denom; } public Big. Fraction(String num, String denom) { this(new Big. Integer(num), new Big. Integer(denom)); } OOP, Java's Big. Integer Class and I/O 8

Composition (cont. ) public String to. String() { return numerator + "/" + denominator; } } public class Test. Big. Ints { public static void main(String args[]) { Big. Fraction x = new Big. Fraction("1", "2"); System. out. println(x); } } OOP, Java's Big. Integer Class and I/O 9

JAVA I/O AND CLIENT/SERVER OOP, Java's Big. Integer Class and I/O 10

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. OOP, Java's Big. Integer Class and I/O 11

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 OOP, Java's Big. Integer Class and I/O 12

Input. Stream and Output. Stream • Input. Stream (Abstract class) This abstract class is the superclass of all classes representing an input stream of bytes. • Output. Stream (Abstract class) This abstract class is the superclass of all classes representing an output stream of bytes. OOP, Java's Big. Integer Class and I/O 13

Types of Input. Stream Byte. Array. Input. Stream read memory block String. Buffer. Input. Stream read from String (not buffer) File. Input. Stream read from file Piped. Input. Stream read from another thread Sequence. Input. Stream reads from several streams Filter. Input. Stream Decorators subclass this class. OOP, Java's Big. Integer Class and I/O 14 A Filter. Input. Stream contains some other input stream, which

Two important Filter. Input. Stream classes - Decorators • Data. Input. Stream (binary data) • Full interface for reading primitive and built- in types • Construct with an Input. Stream • When reading a float, four bytes are read • Buffered. Input. Stream • Adds buffering to the stream (usually do this) • Construct with an Input. Stream OOP, Java's Big. Integer Class and I/O 15

File. Input. Stream - Reading Data From a File Buffered. Input. Stream – Buffers input Data. Input. Stream – Reading binary data read. Line() -- deprecated Data. Input. Stream Buffered. Input. Stream File. Input. Stream String File Name OOP, Java's Big. Integer Class and I/O 16

// copy a binary or text file import java. io. *; public class Copy. Bytes { public static void main( String args[]) throws IOException { Data. Input. Stream in = new Data. Input. Stream( new Buffered. Input. Stream( new File. Input. Stream(args[0]))); Data. Output. Stream out = new Data. Output. Stream( new Buffered. Output. Stream( new File. Output. Stream(args[1]))); OOP, Java's Big. Integer Class and I/O 17

byte. In; try { while(true) { byte. In = in. read. Byte(); out. write. Byte(byte. In); } catch(EOFException e) { in. close(); out. close(); } } OOP, Java's Big. Integer Class and I/O 18

Types of Output. Stream Writes to: Byte. Array. Output. Stream Block of memory File. Output. Stream File Piped. Output. Stream “Pipe” (to another thread) Filter. Output. Stream Decorators subclass this OOP, Java's Big. Integer Class and I/O class 19

Three important Filter. Output. Stream classes - Decorators • Data. Output. Stream – Full interface for writing primitive and built-in types; complements Data. Input. Stream for portable reading & writing of data Data. Output. Stream is normally for storage. • Print. Stream – Allows primitive formatting for data display. Not as nice a c’s printf(). Converts arguments to ASCII or EBCDIC. Use Print. Writer when writing Unicode characters rather than bytes. OOP, Java's Big. Integer Class and I/O 20

Writing Data To A File Print. Stream writes in the platform’s default Encoding. Print. Stream Buffered. Output. Stream File. Output. Stream String File Name OOP, Java's Big. Integer Class and I/O 21

// Writing data to a file import java. io. *; public class Out. Put. Demo { public static void main(String args[]) throws File. Not. Found. Exception{ Print. Stream out = new Print. Stream( new Buffered. Output. Stream( new File. Output. Stream("IODemo. out"))); out. println("Hello world. . . on a file"); out. close(); } } OOP, Java's Big. Integer Class and I/O 22

Data. Out. Put. Stream is for binary output. Data. Input. Stream is for reading binary. Data. Output. Stream Buffered. Output. Stream File. Output. Stream String OOP, Java's Big. Integer Class and I/O 23

// Writing data to a file In Binary not ASCII import java. io. *; public class Out. Put. Demo { public static void main(String args[]) throws File. Not. Found. Exception, IOException { Data. Output. Stream out = new Data. Output. Stream ( new Buffered. Output. Stream( new File. Output. Stream("Binary. out"))); out. write. Double(3. 34); // can’t view this!! out. write. Double(2. 33); out. close(); } } OOP, Java's Big. Integer Class and I/O 24

Print. Writer replaces Print. Stream. Text output. Print. Writer Buffered. Writer File. Writer String OOP, Java's Big. Integer Class and I/O 25

// Writing data to a file import java. io. *; public class Out. Put. Demo { public static void main(String args[]) throws File. Not. Found. Exception, IOException { Print. Writer out = new Print. Writer( new Buffered. Writer( new File. Writer("IODemo. out"))); out. println("Hello world. . . on a file"); out. close(); } } OOP, Java's Big. Integer Class and I/O 26

Converting from an 8 -bit Input. Stream to 16 -bit Unicode Buffered. Reader Input. Stream. Reader Inputstream Input stream System. in OOP, Java's Big. Integer Class and I/O 27
![import java. io. *; public class Input. Demo { public static void main(String args[]) import java. io. *; public class Input. Demo { public static void main(String args[])](http://slidetodoc.com/presentation_image_h/32755eb43e08a77bc7860ddc86acb1fb/image-28.jpg)
import java. io. *; public class Input. Demo { public static void main(String args[]) throws IOException { Buffered. Reader in = new Buffered. Reader( new Input. Stream. Reader(System. in)); System. out. println("What is your name? "); String name = in. read. Line(); System. out. println("Hello "+ name); } } OOP, Java's Big. Integer Class and I/O 28

Some Examples // Demonstrate character I/O in Java // Count the number of a's and b's import java. io. *; public class Char. IO { public static void main(String arg[]) throws IOException { Input. Stream. Reader is = new Input. Stream. Reader(System. in); System. out. println("Enter a line of text and I'll count the a's and b's"); OOP, Java's Big. Integer Class and I/O 29

int a. Count = 0; int b. Count = 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 i = is. read(); // <ctrl><z> in DOS while(i != 'n') { // DOS terminates each line with 13 10 char c = (char) i; if(c == 'a') a. Count++; if(c == 'b') b. Count++; i = is. read(); } System. out. println("a total = " + a. Count + " b total = " + b. Count); } } OOP, Java's Big. Integer Class and I/O 30

Some Examples Count lines // Demonstrate character I/O in Java // Echo the input and count lines import java. io. *; public class Char. IO 2 { public static void main(String arg[]) throws IOException { Input. Stream. Reader is = new Input. Stream. Reader(System. in); OOP, Java's Big. Integer Class and I/O 31

System. out. println("I'll echo and count lines"); int line. Count = 0; int i; i = is. read(); // -1 = EOF = <ctrl><z> in DOS while(i != -1) { char c = (char) i; if(c == 'n') line. Count++; System. out. print(c); i = is. read(); } System. out. println("-------------"); System. out. println("Line count == " + line. Count); } } OOP, Java's Big. Integer Class and I/O 32

Some Examples Using String. Tokenizer // Read a line of integers // and display their sum import java. io. *; import java. util. *; // for String. Tokenizer public class Line. Of. Ints { public static void main(String arg[]) throws IOException { OOP, Java's Big. Integer Class and I/O 33

Input. Stream. Reader is = new Input. Stream. Reader(System. in); Buffered. Reader br = new Buffered. Reader(is); String. Tokenizer st; System. out. println("Enter a line of integers"); String s = br. read. Line(); // use comma, space, and tab for delimeters t = new String. Tokenizer(s, ", t"); OOP, Java's Big. Integer Class and I/O 34

int sum = 0; while(st. has. More. Elements()) { int val = Integer. parse. Int(st. next. Token()); sum += val; } System. out. println("The sum is " + sum); } } OOP, Java's Big. Integer Class and I/O 35

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 Formatted. Output { static final double my. Double = 456. 346; public static void main(String arg[]) throws IOException { Decimal. Format df = new Decimal. Format("0. 00"); System. out. println(df. format(my. Double)); // displays 456. 35 } } OOP, Java's Big. Integer Class and I/O 36

Some Examples // Java I/O // Read a double and display its square root import java. io. *; public class Double. IO { public static void main(String arg[]) throws IOException { Input. Stream. Reader is = new Input. Stream. Reader(System. in); Buffered. Reader br = new Buffered. Reader(is); OOP, Java's Big. Integer Class and I/O 37

double x; System. out. println("Enter a double and I'll compute the square root"); String input. String = br. read. Line(); x = Double. parse. Double(input. String); // displays NAN if x < 0 System. out. println("The square root of "+x+" is " + Math. sqrt(x)); } } OOP, Java's Big. Integer Class and I/O 38

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” OOP, Java's Big. Integer Class and I/O 39

Object serialization • Class must implement Serializable • Wrap a stream in a Object. Output. Stream (for writing) or Object. Input. Stream (for reading) • Use write. Object( ) and read. Object( ) OOP, Java's Big. Integer Class and I/O 40

Some Examples Writing Big. Integers import java. math. *; import java. io. *; public class Test. Big. Ints { public static void main(String args[]) throws IOException { Big. Integer x = new Big. Integer("1234567891011121314"); Big. Integer y = new Big. Integer("12345678900000"); Object. Output. Stream out = new Object. Output. Stream( new File. Output. Stream("bigints. dat")); out. write. Object("Big Integer Storage"); out. write. Object(x); out. write. Object(y); } } OOP, Java's Big. Integer Class and I/O 41

Some Examples Reading Big. Integers import java. math. *; import java. io. *; public class Test. Big. Ints { public static void main(String args[]) throws IOException, Class. Not. Found. Exception { Big. Integer x, y; Object. Input. Stream in = new Object. Input. Stream( new File. Input. Stream("bigints. dat")); String s = (String)in. read. Object(); x = (Big. Integer)in. read. Object(); y = (Big. Integer)in. read. Object(); System. out. println(s + " " + x + " " + y); } OOP, Java's Big. Integer Class and I/O 42

Some Examples List serialization import java. util. *; import java. io. *; public class Save. AList implements Serializable { public static void main(String args[])throws IOException, Class. Not. Found. Exception { Linked. List stack = new Linked. List(); stack. add. First("Little Cat A"); stack. add. First("Little Cat B"); stack. add. First("Little Cat C"); OOP, Java's Big. Integer Class and I/O 43

Object. Output. Stream out = new Object. Output. Stream( new File. Output. Stream("Cat. Stack. out")); out. write. Object("The cat and the hat's hat cats"); out. write. Object(stack); out. close(); Object. Input. Stream in = new Object. Input. Stream( new File. Input. Stream("Cat. Stack. out")); String s = (String) in. read. Object(); Linked. List another. Stack = (Linked. List) in. read. Object(); System. out. println(s + another. Stack); } } OOP, Java's Big. Integer Class and I/O 44

Output C: Mc. Carthy46935ioSerialization>java Save. AList The cat and the hat's hat cats[Little Cat C, Little Cat B, Little Cat A] OOP, Java's Big. Integer Class and I/O 45

I/O on the Net • Historically error- prone, difficult, complex • Threading is also very useful and relatively easy here • Excellent reference: “Java Network Programming” by Elliotte Rusty Harold, O’Reilly Books, 1997. OOP, Java's Big. Integer Class and I/O 46

Identifying a Machine • Uniquely identify a machine from all the others in the world • IP (Internet Protocol) address that can exist in two forms: 1) DNS (Domain Name Service) form: hempel. heinz. cmu. edu 2) “Dotted quad” form: 128. 2. 240. 92 • Represented internally by 32 bit number (4. 3 billion possibilities. Oops!) (going to 128) • static Inet. Address. get. By. Name( ) produces OOP, Java's Big. Integer Class and I/O a 47

Servers & Clients • Two machines must connect • Server waits around for connection • Client initiates connection • Once the connection is made, server & client look identical • Both ends are turned into Input. File and Output. File objects, which can then be converted to Reader and Writer objects OOP, Java's Big. Integer Class and I/O 48

Testing w/ o a Network You might not trust your code • localhost : the “local loopback” IP address for testing without a network Inet. Address addr = Inet. Address. get. By. Name(null); • Equivalently: Inet. Address. get. By. Name("localhost"); • Or using the reserved IP number for the loopback: Inet. Address. get. By. Name("127. 0. 0. 1"); • open two windows and talk OOP, Java's Big. Integer Class and I/O 49

Port: Unique “Place” in a Machine • IP address isn’t enough to identify a unique server • Many servers can exist on one machine Protocol Port http server 80 ftp server 21 telnet 23 finger 79 • A “server” is a program watching a port. OOP, Java's Big. Integer Class and I/O 50

Ports • When you set up client and server, you must specify IP address and port, so they can find each other • Not a physical location, but a software abstraction to represent a service • 1 - 1024 are reserved (on Unix, root may access these ports), higher numbered ports are available OOP, Java's Big. Integer Class and I/O 51

Sockets • Software abstraction used to represent the “terminals” of a connection between two machines • Socket is the actual 2 - way connector. Can initiate a connection with a server • Server. Socket isn’t really a socket but more of a “Server. Connector” that produces a Socket as the return value of accept( ) , which waits (blocks) for a connection. • In the end, you get a Socket on each machine OOP, Java's Big. Integer Class and I/O 52

Just Like Files. . . • Once you have a Socket , you call get. Input. Stream( ) and get. Output. Stream( ) to produce the corresponding Input. Stream and Output. Stream objects • You convert these to readers and writers, wrap them in a Buffered. Reader or Buffered. Writer and Print. Writer • From then on, it’s like reading and writing any other IO stream! OOP, Java's Big. Integer Class and I/O 53

Some Examples Client/Server // Jabber. Server. Java // Very simple server that just // echoes whatever the client sends. // One client at a time. No threads yet! import java. io. *; import java. net. *; public class Jabber. Server { // Choose a port outside of the range 1 - 1024: static final int port = 8080; public static void main( String[] args ) OOP, Java's Big. Integer Class and I/O 54

try { boolean flush = true; Server. Socket s = new Server. Socket(port); System. out. println(" Server Started: " + s); // Blocks until a connection occurs: Socket socket = s. accept(); System. out. println( "Connection accepted, socket: "+ socket); Buffered. Reader in = new Buffered. Reader( new Input. Stream. Reader( socket. get. Input. Stream())); Print. Writer out = new Print. Writer( new Buffered. Writer( new Output. Stream. Writer( socket. get. Output. Stream())), flush); OOP, Java's Big. Integer Class and I/O 55

while (true) { // till client says ‘END’ String str = in. read. Line(); if (str. equals("END")) break; System. out. println(" Echoing: " + str); out. println(str); } System. out. println(" closing. . . "); socket. close(); } catch( Exception e) { e. print. Stack. Trace(); } } OOP, Java's Big. Integer Class and I/O 56

// Jabber. Client. java // Very simple client that just sends // lines to the server and reads lines that the server sends. import java. net. *; import java. io. *; public class Jabber. Client { // Choose a port outside of the range 1 - 1024: static final int port = 8080; public static void main( String args[]) { try { // Produce "Local Loopback" IP address Inet. Address addr =Inet. Address. get. By. Name(null); System. out. println(" addr = " + addr); Socket socket = new Socket(addr, port); // ‘remote’ server System. out. println(" socket = " + socket); OOP, Java's Big. Integer Class and I/O 57

Buffered. Reader in = new Buffered. Reader( new Input. Stream. Reader( socket. get. Input. Stream())); // Enable Print. Writer autoflush: Print. Writer out = new Print. Writer( new Buffered. Writer( new Output. Stream. Writer( socket. get. Output. Stream())), flush); OOP, Java's Big. Integer Class and I/O 58

for( int i = 0; i < 10; i ++) { out. println(" howdy " + i); String str = in. read. Line(); System. out. println( str); } out. println(" END"); } catch( Exception e) { e. print. Stack. Trace(); } } } OOP, Java's Big. Integer Class and I/O 59
- Slides: 59