CSC – Java Programming II Lecture 9 January 30, 2002.

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

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.
III. Streams. Introduction Often a program needs to bring in information from an external source or to send out information to an external destination.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
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.
Files Files are used to store long term data. –Typically referred to as persistent data. –A file is a group of related records. –A list of friends addresses.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Chapter 9 Streams and File I/O Overview of Streams and File I/O
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
1 File Output. 2 So far… So far, all of our output has been to System.out  using print(), println(), or printf() All input has been from System.in 
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
ARRAYS public class ArrayDemo { public static void main(String[] args) { int[] anArray; // declare an array of integers anArray = new int[10]; // create.
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.
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Chapter 91 Streams and File I/O Chapter 9. 2 Reminders Project 6 released: due Nov 10:30 pm Project 4 regrades due by midnight tonight Discussion.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Tirgul 1 Today’s subject - Java reminders and additions: –Inner classes –Packages –I/O streams –Command Line Arguments –Primitive and Reference Data Types.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Guide To UNIX Using Linux Third Edition
JavaScript, Third Edition
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
1 CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Dynamic Arrays Dynamic arrays are arrays that are re- allocated to a larger size. –See Eck Section 8.3 for details. –For instance, what happens with the.
Program structure Four different storage-class specifications: –Automatic (auto): local to a function, normally declared variables are automatic. Does.
CIS 270—Application Development II Chapter 14—Files and Streams.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
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.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 9 Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Pemrograman Dasar Arrays PTIIK - UB. Arrays  An array is a container object that holds a fixed number of values of a single type.  The length of an.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 9 l Streams and Simple File I/O l Exception Handling with File.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
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.
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.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Exceptions Exception handling – Exception Indication of problem during execution – E.g., divide by zero – Chained exceptions Uses of exception handling.
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.
File Input and Output Appendix E © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Using a Pointer as an Array Name C allows us to subscript a pointer as though it were an array name Here's an example: #define N 100 int a[N], i, sum =0,
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
Java IO Exploring the java.io package and living to talk about it.
Sequential files creation & writing
OO Design and Programming II I/O: Reading and Writing
Object Writing in files
University of Central Florida COP 3330 Object Oriented Programming
OBJECT ORIENTED PROGRAMMING II LECTURE 21_1 GEORGE KOUTSOGIANNAKIS
I/O Basics.
OBJECT ORIENTED PROGRAMMING II LECTURE 11_1 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Chap 2. Identifiers, Keywords, and Types
Review for Midterm 3.
Presentation transcript:

CSC – Java Programming II Lecture 9 January 30, 2002

Creating and Initializing a Multidimensional Array The declaration of a multidimensional array will contain more than one set of square brackets: int[][] a; It’s legal to put some or all of the brackets after the array name: int[] a[]; int a[][];

Creating and Initializing a Multidimensional Array The new keyword is used to allocate space for a multidimensional array: a = new int[5][10]; a will have 5 rows and 10 columns. The declaration of a multidimensional array can be combined with the allocation of space for the array: int[][] a = new int[5][10];

Creating and Initializing a Multidimensional Array a = new int[5][10];

Creating and Initializing a Multidimensional Array Rules for assigning default values to array elements: –Numbers are set to zero. –boolean elements are set to false. –Elements of a reference type are set to null.

Creating and Initializing a Multidimensional Array The initializer for a two-dimensional array looks like a series of one-dimensional array initializers: int[][] square = {{8, 3, 4}, {1, 5, 9}, {6, 7, 2}};

Processing the Elements in a Multidimensional Array Statements that sum the elements in an array a by visiting the elements row by row: int sum = 0; for (int row = 0; row < 3; row++) for (int col = 0; col < 3; col++) sum += a[row][col]; Because the loops are nested, the row and col variables will take on all possible combinations of values.

Processing the Elements in a Multidimensional Array Order in which the elements of a will be visited: a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] Nested for loops are ideal for processing multidimensional arrays.

How Multidimensional Arrays Are Stored In Java, a two-dimensional array is a one- dimensional array whose elements are one- dimensional arrays.

Using Two-Dimensional Arrays to Store Images Two-dimensional arrays are often used to store images. Images are sometimes stored in gray scale, rather than in color. In a gray-scale image, each pixel is a shade of gray. Typically there are 256 shades, represented by integers between 0 (black) and 255 (white).

A sample gray-scale image

A 2-D Array of Gray Scale Values

Using Two-Dimensional Arrays to Store Images Arrays often occupy large amounts of memory, especially when they have more than one dimension. If numRows and numColumns are both 1000, the grayscaleImage array will require 4,000,000 bytes of memory (1000  1000  4). Arrays this large may exceed the limits of a Java interpreter.

14.1Files and Streams A file is a collection of related data that is given a name and placed on a storage medium. A file can be used to persist data over a long period of time and between executions. All files are the same in one important respect: they consist of bytes.

How Files Are Stored In some files, each byte represents a character. In other files, the bytes mean other things. Suppose that a file consists of four bytes: Some possible meanings: –The bytes represent the ASCII characters J, a, v, and a. –The bytes represent a single integer. –The first two bytes represent a short integer, and the second two represent another short integer. –The bytes represent a single float value.

Text Files Versus Binary Files Files fall into two categories: –In a text file, the bytes represent characters in some character set, such as ASCII or Unicode. –In a binary file, the bytes don’t necessarily represent characters (although some of them may).

Text Files Versus Binary Files Text files have two characteristics that binary files don’t possess. –First, text files are divided into lines. –Second, text files may contain a special “end- of-file” marker. In a binary file, there’s no “end-of-line” or “end-of-file” marker; all bytes are treated equally.

Streams Programs that work with files will need to use the java.io package. The names of many java.io classes include the word “stream.” A stream is an abstraction that represents any “file-like” source of input or destination for output. A stream object may be capable of reading from anything that resembles a file or writing to anything that resembles a file.

Streams Classes whose names end with Stream are subclasses of InputStream and OutputStream : System.out and System.err are instances of the PrintStream class.

Streams Other classes have names that end with Reader or Writer. These classes are subclasses of Reader and Writer :

Streams The reader and writer classes are designed to help with a common problem: Java stores characters in Unicode, whereas most software assumes that characters are stored in ASCII form. An instance of a Reader class solves the problem by automatically converting bytes to Unicode characters during input. Similarly, an instance of a Writer class will convert Unicode characters to single bytes during output.

Streams The reader and writer classes are designed to help with a common problem: Java stores characters in Unicode, whereas most software assumes that characters are stored in ASCII form. An instance of a Reader class solves the problem by automatically converting bytes to Unicode characters during input. Similarly, an instance of a Writer class will convert Unicode characters to single bytes during output.

Stream Layering A diagram showing the layering of the three classes:

Working with Files Working with a file involves three steps: –Open the file –Perform operations on the file –Close the file

File Pointers For each open file, Java maintains a file pointer, which keeps track of which byte will be the next to be read or written. If a file is opened for reading, the file pointer will be at the beginning:

Creating File Objects There are several ways to create a File object. One File constructor expects a string containing the file’s name: File f = new File("Lottery.java"); Java will try to locate the file in the current directory. To work with a file in a different directory, path information will need to be included in the string: File f = new File("c:\\programs\\lottery\\Lottery.java");

Using Multiple catch Blocks More than one catch block may be capable of handling a given exception: try { … } catch (FileNotFoundException e) { … } catch (IOException e) { … } If a FileNotFoundException occurs, both catch blocks can potentially handle the exception, but only the first will be allowed to.

finally Blocks After the last in a series of catch blocks, a finally block may be present: try block catch ( exception-type identifier ) block … catch ( exception-type identifier ) block finally block

Writing Data Types A DataOutputStream object can’t be created directly from a file name. Instead, a FileOutputStream object is first created, and then that object is used to create a DataOutputStream object: FileOutputStream fileOut = new FileOutputStream(fileName); DataOutputStream out = new DataOutputStream(fileOut); The DataOutputStream constructor will accept any output stream object as its argument.

Writing Data Types A partial list of DataOutputStream methods: Description Action void write(int b) Writes the value of b as a single byte. void write(byte[] b, Writes len bytes of the array b, start- int off, int len) ing at the position indicated by off. void writeBoolean( Writes the value of v as a byte contain- boolean v) ing either 1 ( true ) or 0 ( false ). void writeByte(int v) Writes the value of v as a single byte. void writeChar(int v) Writes the value of v as 2 bytes. void writeDouble(double v) Writes the value of v as 8 bytes. void writeFloat(float v) Writes the value of v as 4 bytes. void writeInt(int v) Writes the value of v as 4 bytes. void writeLong(long v) Writes the value of v as 8 bytes. void writeShort(int v) Writes the value of v as 2 bytes.