1 / 59

Object-Oriented Programming in Java: BigInteger Class & I/O

Explore the concepts of abstraction, encapsulation, polymorphism, inheritance, and composition in Java's BigInteger class along with I/O operations. Learn how to use BigInteger to perform mathematical computations and handle large numbers efficiently.

andrer
Download Presentation

Object-Oriented Programming in Java: BigInteger Class & I/O

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 • Object-Oriented Programming • Java’s BigInteger Class • Java I/O and Client/Server OOP, Java's BigInteger Class and I/O

  2. Object-Oriented Programming and Java’s BigInteger 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 BigInteger Class and I/O

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

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

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

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

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

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

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

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

  11. 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 BigInteger Class and I/O

  12. 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 BigInteger Class and I/O

  13. 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. OOP, Java's BigInteger Class and I/O

  14. 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. OOP, Java's BigInteger Class and I/O

  15. 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 OOP, Java's BigInteger Class and I/O

  16. FileInputStream - Reading Data From a File BufferedInputStream – Buffers input DataInputStream – Reading binary data readLine() -- deprecated DataInputStream BufferedInputStream FileInputStream String File Name OOP, Java's BigInteger Class and I/O

  17. // 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]))); OOP, Java's BigInteger Class and I/O

  18. byte byteIn; try { while(true) { byteIn = in.readByte(); out.writeByte(byteIn); } } catch(EOFException e) { in.close(); out.close(); } } } OOP, Java's BigInteger Class and I/O

  19. Types of OutputStream Writes to: ByteArrayOutputStream Block of memory FileOutputStream File PipedOutputStream “Pipe” (to another thread) FilterOutputStream Decorators subclass this class OOP, Java's BigInteger Class and I/O

  20. 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). OOP, Java's BigInteger Class and I/O

  21. Writing Data To A File PrintStream writes in the platform’s default Encoding. PrintStream BufferedOutputStream FileOutputStream File Name String OOP, Java's BigInteger Class and I/O

  22. // Writing 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(); } } OOP, Java's BigInteger Class and I/O

  23. DataOutPutStream is for binary output. DataInputStream is for reading binary. DataOutputStream BufferedOutputStream FileOutputStream String OOP, Java's BigInteger Class and I/O

  24. // 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(); } } OOP, Java's BigInteger Class and I/O

  25. PrintWriter replaces PrintStream. Text output. PrintWriter BufferedWriter FileWriter String OOP, Java's BigInteger Class and I/O

  26. // Writing data to a file 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(); } } OOP, Java's BigInteger Class and I/O

  27. Converting from an 8-bit InputStream to 16-bit Unicode BufferedReader InputStreamReader Inputstream Input stream System.in OOP, Java's BigInteger Class and I/O

  28. 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); } } OOP, Java's BigInteger Class and I/O

  29. 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"); OOP, Java's BigInteger Class and I/O

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

  31. 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); OOP, Java's BigInteger Class and I/O

  32. 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); } } OOP, Java's BigInteger Class and I/O

  33. 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 { OOP, Java's BigInteger Class and I/O

  34. 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"); OOP, Java's BigInteger Class and I/O

  35. int sum = 0; while(st.hasMoreElements()) { int val = Integer.parseInt(st.nextToken()); sum += val; } System.out.println("The sum is " + sum); } } OOP, Java's BigInteger Class and I/O

  36. 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 } } OOP, Java's BigInteger Class and I/O

  37. 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); OOP, Java's BigInteger Class and I/O

  38. 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)); } } OOP, Java's BigInteger Class and I/O

  39. 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 BigInteger Class and I/O

  40. Object serialization • Class must implement Serializable • Wrap a stream in a ObjectOutputStream (for writing) or ObjectInputStream (for reading) • Use writeObject( ) and readObject( ) OOP, Java's BigInteger Class and I/O

  41. Some Examples Writing BigIntegers import java.math.*; import java.io.*; public class TestBigInts { public static void main(String args[]) throws IOException { BigInteger x = new BigInteger("1234567891011121314"); BigInteger y = new BigInteger("1234567890000000000"); ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("bigints.dat")); out.writeObject("Big Integer Storage"); out.writeObject(x); out.writeObject(y); } } OOP, Java's BigInteger Class and I/O

  42. Some Examples Reading BigIntegers import java.math.*; import java.io.*; public class TestBigInts { public static void main(String args[]) throws IOException, ClassNotFoundException { BigInteger x, y; ObjectInputStream in = new ObjectInputStream( new FileInputStream("bigints.dat")); String s = (String)in.readObject(); x = (BigInteger)in.readObject(); y = (BigInteger)in.readObject(); System.out.println(s + " " + x + " " + y); } } OOP, Java's BigInteger Class and I/O

  43. Some Examples List serialization import java.util.*; import java.io.*; public class SaveAList implements Serializable { public static void main(String args[])throws IOException, ClassNotFoundException { LinkedList stack = new LinkedList(); stack.addFirst("Little Cat A"); stack.addFirst("Little Cat B"); stack.addFirst("Little Cat C"); OOP, Java's BigInteger Class and I/O

  44. ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("CatStack.out")); out.writeObject("The cat and the hat's hat cats"); out.writeObject(stack); out.close(); ObjectInputStream in = new ObjectInputStream( new FileInputStream("CatStack.out")); String s = (String) in.readObject(); LinkedList anotherStack = (LinkedList) in.readObject(); System.out.println(s + anotherStack); } } OOP, Java's BigInteger Class and I/O

  45. Output C:\McCarthy\46935\io\Serialization>java SaveAList The cat and the hat's hat cats[Little Cat C, Little Cat B, Little Cat A] OOP, Java's BigInteger Class and I/O

  46. 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 BigInteger Class and I/O

  47. 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 InetAddress.getByName( ) produces a Java object containing address OOP, Java's BigInteger Class and I/O

  48. 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 InputFile and OutputFile objects, which can then be converted to Reader and Writer objects OOP, Java's BigInteger Class and I/O

  49. Testing w/ o a Network • You might not trust your code • • localhost : the “local loopback” IP address • for testing without a network InetAddress addr = • InetAddress.getByName(null); • • Equivalently: InetAddress.getByName("localhost"); • • Or using the reserved IP number for the • loopback:InetAddress.getByName("127.0.0.1"); • open two windows and talk OOP, Java's BigInteger Class and I/O

  50. 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 BigInteger Class and I/O

More Related