Tirgul 1 Today’s subject - Java reminders and additions: –Inner classes –Packages –I/O streams –Command Line Arguments –Primitive and Reference Data Types.

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
III. Streams. Introduction Often a program needs to bring in information from an external source or to send out information to an external destination.
10-1 Writing to a Text File When a text file is opened in this way, a FileNotFoundException can be thrown – In this context it actually means that the.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
Tirgul 1 Today’s subjects: –First programming exercise. –Java reminder & completions : reference data types, cloning, inner classes, packages. –Short reminder.
Files and Streams CS 21a Chapter 11 of Horstmann.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Files and Streams CS 21a. 10/02/05 L18: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Java Review Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Tirgul 2 Subjects of this tirgul: –Short discussion about standard output/error. –Short discussion about comparators. –Main subject: asymptotic analysis.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java I/O Input: information brought to program from an external source
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
CIS 068 JAVA I/O: Streams and Files. CIS 068 I/O Usual Purpose: storing data to ‘nonvolatile‘ devices, e.g. harddisk Classes provided by package java.io.
CSC – Java Programming II Lecture 9 January 30, 2002.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Two Ways to Store Data in a File Text format Binary format.
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
File IO Basics By Dan Fleck Coming up: Data Streams.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
GENERICS AND FILE HANDLING Saumya Srivastava (977934) Divyangana Pandey (977790) Shubhi Saxena (978108) Arka Das (962969) AHD05/15-16 AJA 21.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Java Input / Output l a modular approach to input/output: - different stream objects are connected/wrapped to handle I/O l a data stream object: a flow.
Generics and file handling Presented by: Abha Kumari Neha Pradip Vhanmane Raj Visa Rashmi Kewlani Suvrat Dixit.
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Lecture 8: I/O Streams types of I/O streams Chaining Streams
OO Design and Programming II I/O: Reading and Writing
CMSC 202 Text File I/O.
University of Central Florida COP 3330 Object Oriented Programming
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
I/O Streams- Basics Byte Streams and Character Streams
Comp 212: Intermediate Programming Lecture 30 – Stream and File I/O
File I/O ICS 111: Introduction to Computer Science I
Review for Midterm 3.
Comp 212: Intermediate Programming Lecture 30 – Stream and File I/O
Presentation transcript:

Tirgul 1 Today’s subject - Java reminders and additions: –Inner classes –Packages –I/O streams –Command Line Arguments –Primitive and Reference Data Types –Cloning

Inner classes Motivation: Suppose you need an iterator class for your LinkedList class. Defining a new class solely for this purpose complicates your package structure. Furthermore - this class must get a handler to a specific LinkedList instance and it can ’ t access its private data members. And, there would be such a class for every DS. The solution : Inner classes. Useful for simple “ helper ” classes that serve a very specific function at a particular place in the program, and are not intended to be general purpose “ top level ” classes. They make your code clearer, and prevent cluttering your package namespace.

Inner classes - Example & Syntax public class LinkedList { private Node head;... public Iterator iterator() { return new ListIterator() }; private class ListIterator implements Iterator { Node current; public ListIterator () { current = head; } public boolean hasNext() {...} public Object next() {... } } // end class ListIterator } // end class LinkedList

Packages Java classes are organized in packages to help organize and share programs and projects. Examples: java.util, java.io The import keyword extends the scope of the program to contain (part of) a specific package. We can build our own packages, using these guidelines: –Locate all package classes in a subdirectory with the same name as the package name. –The first line of a class of some package should be: package package_name; –Set the CLASSPATH variable to point to the directory where the package subdirectory resides. For example, to use the package dast.util that resides in the subdirectory ~dast/www/public/dast/util you should add the path ~dast/www/public to your CLASSPATH variable.

Java I/O Streams Often a program needs to import/export information to/from an external source (a file, a network, etc.) - For this, we open a stream on an information source. The java.io package contains all classes, interfaces, exceptions, etc. that involve I/O streams. Two types of I/O streams: -- Character streams: textual information is represented by an encoding that gives a numeric value for each symbol - the text is stored as a list of numbers. Here, Java translates between internal Unicode representation and external representation (e.g.ASCII). Class hierarchy based in Reader and Writer abstract classes. -- Binary (byte) streams: views the information as a sequence of bytes (e.g. images, sound). No translation occurs. Class hierarchy based in InputStream and OutputStream abstract classes.

Hierarchy Structure File streams: classes like FileReader, FileWriter (similarly, FileInputStream and FileOutputStream). Layered streams: –A Reader may operate on top of an InputStream. –BufferedReader on top of another Reader, to aggregate the reading (e.g. read an entire line). –PrintWriter, to format the output (prints integer, strings, etc.) –Many possibilities – see API.

Java streams - Example import java.io.*;... public void doSomething throws IOException { FileReader in = new FileReader("results.txt"); FileWriter out = new FileWriter("statistics.txt"); BufferedReader r = new BufferedReader(in); PrintWriter p = new PrintWrite(out); String input, output; while ((input = r.readLine()) != null) {... //do something interesting and create output string p.print(output); } r.close(); in.close(); p.close(); out.close(); }

Default I/O Streams Class System has 3 default streams, available to every Java program: Input from the keyboard goes into the ‘standard input’. This is the data member System.in of type java.io.InputStream Output (usually to the terminal window) written through 2 streams: –‘Standard output’ – System.out of type java.io.PrintStream –‘Standard error’ – System.err of type java.io.PrintStream [ PrintStream is an exception - it is a stream, but allows character output through its print() and println() methods. ]

The standard output and error are directed by the Operating System. By default - both to the terminal. The convention - standard error for error messages, standard output for regular output. In UNIX, the user can redirect to a file: –standard output by adding “ > my_out.txt ”. For example: java MyClass param1 > out.txt –both to the same file, by adding “ >& my_out.txt ” –You can’t redirect only the standard error, but redirecting to different files is possible (by outsmarting): ( java MyClass > out.txt) >& err.txt Default I/O Streams

Command Line Arguments A way to pass parameters to a program. The method main() accepts a single argument that is an array of strings. The command line arguments (separated by blank(s)) are stored in this array (each argument is a string). For example, if we have: class Test { public static void main(String[] args){...} } then, when we run the command: java Test 1 abc -a - b we’ll have: args[0] = "1", args[1] = "abc", args[2]="-a", args[3]="-", args[4]="b"

Primitive and Reference DT Primitive DT: ( boolean, int, float, etc.) each is stored in a unique memory place: int a=5; int b=a; a = 6; So after this command sequence b will have a value of 5. (This is called copy “by value”). ab

Primitive and Reference DT Reference DT: (all objects) a variable points to a memory place created by the new command. Many variables may point to the same memory place Employee a = new Employee(); a.ID = 5; Employee b = a; a.ID = 6; So after this command sequence b.ID will have a value of 6. (by changing a we also changed b ). ID b a

Primitive and Reference DT When we pass an object as an argument to a method, a new reference to the same object is created. When we pass primitive DT to a method, a new variable is created. If an object variable has the value null, this actually means: “this variable does not point to any memory place” How do we make an actual copy of the object, not another reference to same object? This is called cloning.

Cloning Cloning – The Java way of making a copy of an object. Employee a = new Employee(); a.ID = 5; if ( a instanceof Cloneable ) { Employee b = a.clone(); a.ID = 6; } Now b is a reference to a new object (identical to a ) A class that provides the clone() method should implement the Cloneable interface. We can check if a class is Cloneable by using the instanceof operator.

How to be “ cloneable ” Class Object contains the method clone(), which we override. Class Object implements clone() as a bit-by-bit memory copy. public class Employee implements Cloneable { public int ID; public Object clone() { try { return super.clone(); } catch (CloneNotSupportedExcetion e) { } // this catch is not supposed to happen. }

Cloning Method Object.clone() throws CloneNotSupportedException if the class does not implement Cloneable. Therefore, if you want to use Object.clone() you should nest it in a try - catch block. Method Object.clone() is declared protected, therefore you must override the clone() method, declaring it public. public class Employee implements Cloneable { public int ID; public Object clone() { try { return super.clone(); } catch (CloneNotSupportedExcetion e) { } // this catch is not supposed to happen. }

Cloning - “deep” and “shallow” copy Shallow/Deep copy – Copies by reference/value the object data members. For example: A B A B A1 A B B1 Shallow copy Deep copy Original

“deep” and “shallow” copy Notice that Object.clone() performs shallow copy For example, Java’s Vector implements shallow copy: Emp e1 = new Emp(); Emp e2 = new Emp(); e1.id = 1; e2.id = 2; Vector v1 = new Vector(); v1.addElement(e1) ; v1.addElement(e2); Vector v2 = v1.clone(); Then: ((Emp)v2.elementAt(0)).id = 3; System.out.println(((Emp)v1.elementAt(0)).id); will print 3, but: v2.removeElementAt(0); System.out.println(((Emp)v1.elementAt(0)).id); will still print 3.

Cloning vs. Copy Constructor Copy constructors can be used to solve the same problem as cloning. They play an important role in languages (e.g. C++) where objects can be passed by value as well as by reference. In Java, although you can use both techniques, cloning is more general. For example, a deep copy of a list of objects of different types. There is no way of knowing what kind of copy constructor should be called for each element, but the clone() method makes sure you get the right copy of each.