General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 –...

61
General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone: 618-453-3990 Email: [email protected] Lab Assignments and Homework will be posted and submitted through Blackboard. The Blackboard site for the course should be available within a couple of days. 1
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    213
  • download

    0

Transcript of General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 –...

Page 1: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

General Information• T.A. Information

• Name: Andrew Beussink• Office: Faner 2038• Office Hours: 1:00 – 3:00 TR, or drop in or by appointment• Office Phone: 618-453-3990• Email: [email protected]

• Lab Assignments and Homework will be posted and submitted through Blackboard.• The Blackboard site for the course should be available within a

couple of days.

1

Page 2: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Faner Hall

2

Page 3: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Late Policy• Normally, assignments may still be submitted up to three days

after the due date, but it carries a penalty:• 10% if turned in at most 24 hours after the due date• 20% if turned in from 24 to 48 hours after the due date• 30% if turned in from 48 to 72 hours after the due date• If not submitted after 3 days, the assignment will receive a grade

of zero• Partial submissions can be submitted for a partial grade• Other arrangements for approved reasons can be made with

the instructor.

3

Page 4: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Java FundamentalsAndrew BeussinkCS 220: Programming with Data StructuresSouthern Illinois University Carbondale

4

Page 5: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Java Fundamentals

1. Introduction2. Variables3. Expressions4. Control Statements5. Methods6. Exceptions7. Input and Output8. Additional OOP Features

5

Page 6: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

1. INTRODUCTION

Java’s Basic Structure, Classes and Scope, Using Java, Running Java Applications, the Java API, Coding Conventions, Comments

6

Page 7: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Java’s Basic Structure• Java is an object-oriented language, based on the object-

oriented paradigm that views a program as an interaction between objects.

• An object is represented by a class.• A class consists of data fields containing the object’s

information and methods providing actions related to the object. Related classes can be collected into packages.

• Compiled Java programs are portable; high-level language is compiled into Java bytecode which is interpreted by a machine-specific virtual machine.

7

Page 8: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Classes and Scope• Access to classes and their data fields and methods is

controlled through scope modifiers.• The private modifier is used to limit access to data fields or

methods for use only within the class itself.• The public modifier specifies that the data field or method can be

accessed anywhere.• There are also the modifiers protected and package, which will be

discussed later on.• Following the concept of encapsulation, data fields are usually

private; access to the object’s information is controlled through the public methods of its class.

8

Page 9: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Using Java• The standard virtual machine implementation is the Java

Runtime Environment (JRE). This is required to run a Java application or applet on a computer.

• Developing Java applications and applets requires additional tools, including the compiler. The Java Development Kit (JDK) is the most commonly used. It also includes the JRE.

• Installers for the Java SE 6 can be downloaded from the official website here (lower down, Java SE 6.0 update 30).• Java SE 7 was released last July but we will (most likely) be using

Java SE 6 for this course.

9

Page 10: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Using Java• An integrated development environment (IDE) is commonly used

for developing in Java. Popular free IDEs for Java include Netbeans and Eclipse.

• The Java JDK and Netbeans and Eclipse are already installed on computers in this lab.

• The course textbook is based on a previous version of Java (J2SE 5.0); however, it appears that it will not be an issue for the programming requirements of the course.

10

Page 11: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Running Java Applications• Small Java applications are compiled into class files, which can be

run from the command line:C:\Users\Andrew> java MyClass

• Larger applications are compiled in to Java archive (jar) files, which can also be run from the command line:

C:\Users\Andrew> java –jar MyApp.jar• For testing applications for development, however, applications can

be run from within most IDEs.

11

Page 12: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

The Java API• A major strength of Java is the vast amount of classes provided

for use as part of the Java Class Library. Information about these classes, including their public methods, can be found in the Java API Specification. It can be found here for Java SE 6.

• To use one of these classes, it must be imported before the class definition using it. Import statements can include a single class or an entire package.• import java.io.* will import all of the classes in the io

package, while import.java.io.Scanner imports only the Scanner class.

12

Page 13: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Coding Conventions• It is common practice to begin an identifier of a class with a

capital letter (i.e. String for class String), and lowercase letters for variables and methods (i.e. studentAge for a variable holding a student’s age, or getStudentName for a method that returns a student’s name.)

• As in the examples above, it is also common to use “camel-back” notation for identifiers, capitalizing the first letter of additional words in an identifier.

• These conventions are only intended to make code easier to understand; they are not enforced by the compiler.

• Starting statements on new lines and indentation is also use to make the code more readable.

13

Page 14: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Comments• Comments in Java are similar to those in C or C++. They are

discarded by the compiler and only used to aid in code readability.• A comment line is indicated by a two forward slashes, //. Any

characters after this until the end of the line are ignored.• The start and end of a multiline comment is indicated by a

forward slash and asterisk, /* and */, respectively. Any characters between them are ignored.

14

Page 15: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

2. VARIABLES

Definition, Primitive Data Types, Objects, Arrays, Class String, Reserved Words

15

Page 16: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Definition• A variable is an abstract representation of a unit of memory,

consisting of an identifier, a type and a value.• The variable type specifies the range of the value and the set of

operations that can be preformed upon it.• Categories of primitive data types include integers, floating-

point (real) numbers, characters, and Boolean (true or false).• Objects are also considered to be variables.• Variables are created and initialized by assignment statements.• The keyword “static” can be used to share a variable with all

objects of a class. The keyword “final” can be used in addition to this to create a constant shared variable:

static final double PI = 3.141592653589793;

16

Page 17: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Primitive Data TypesCategory Type Size Range

Integer byte 1 byte -128 to 127

short 2 bytes -32,768 to 32767

int 4 bytes -2,147,483,648 to 2,147,483,647

long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Floating Point

float 4 bytes ±3.40282347*1038 to ±1.40239846*10-45

double 8 bytes ±1.79769313486231570*10308

to ±4.94065645841246544*10-324

Character char 2 bytes All Unicode characters

Boolean boolean

1 byte true or false17

Page 18: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Primitive Data Types• Primitive data types are declared by type and identifier:

int studentAge;• They can also have an initial value assigned to them on

declaration:float milesDriven = 12.52;

• If variables are not assigned an initial value, they are automatically assigned zero values for number data types and null for objects.

• Most primitive data types have Wrapper classes for increased functionality (e.g. Integer)

18

Page 19: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Object Variables• Declaring an object variable is similar to declaring primitive

data types.• Initializing an object, however, requires the new operator

along with a call to the object’s constructor:Account myAccount = new Account();

• An object’s class may have more than one constructor, one of which may accept initial values.

• Java objects are created in dynamic memory, but Java automatically frees memory no longer used.• The keyword “new” is used for allocating memory

• Strings are implemented by Class String.19

Page 20: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Arrays• An array is a simple data structure for storing a collection of

variables. In Java, they are implemented in a way somewhat similar to objects.

• Declaring an array requires the type and identifier, as well as square brackets:

float[] gpa;• Arrays must be initialized for use, and its length must be

specified:gpa = new float[10];

• This can be done in a single statement:float[] gpa = new float[20];

20

Page 21: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Arrays• They can also be initialized with values:

char[] grades = {A, B, C, D};• Each index of the array can be accessed directly:

gpa[5] = 3.625;• Array indices begin at zero. The size of the array can be called

by the length instance variable:int x = grades.length; // the value of x

is 4

• Multidimensional arrays can also be created:float[][] rainfall = new float[12]

[10];21

Page 22: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Reserved Wordsabstract continue for new switchassert default goto package synchronizedboolean do if private thisbreak double implements protected throwbyte else import public throwscase enum instanceof return transient catch extends int short trychar final interface static voidclass finally long strictfp volatileconst float native super while

Literals: true false null

22

Page 23: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

3. EXPRESSIONS

Unary and Binary Arithmetic Operators, Arithmetic and Boolean Expressions

23

Page 24: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Unary Arithmetic OperatorsName Symbol Example

Unary plus + Indicates a positive value, but does not actually modify a value.

Unary minus - int x = 5;int y = -x;The value of y is -5.

increment ++ int x = 5;++x;The value of x is 6.

decrement -- int y = 20;--y;The value of y is 19.

Logical compliment ! boolean flag1 = false;boolean flag2 = !flag1;The value of flag2 is true.

24

Page 25: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Binary Arithmetic OperatorsCategory Symbol Example

Addition + int x = 5 + 10;The value of x is 15.

Subtraction - int y = x – 12;The value of y is 3.

Multiplication * int z = x * y;The value of z is 45;

Division / x = z / 5;The value of x is now 9

Modulus % y = x % 4;The value of y is 1.

25

Page 26: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Arithmetic Expressions• The unary and binary operators can be combined with

variables and literals and parentheses to make complex expressions:

int a = (x + y) * 5 – 12 % ++z;• Additive and multiplicative operator precedence -- with or

without parentheses -- is similar to that of mathematics: unary operators take higher precedence over binary operators (postfix notation over prefix):

x++ > ++x > *, /, % > +,-

26

Page 27: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Type Conversion• “Lower” types are implicitly type cast to “higher” types: float x = 5 is valid but int x = 12.2 is invalid.• int -> long -> float -> double

• Type casting to “lower” types must be done explicitly: int x = (int) 12.2

is valid, the resulting value of x being 12.• In complex arithmetic operations, this explicit type casting

might need to be done to get the desired result.

27

Page 28: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Boolean OperatorsName Symbol Example

Greater than > x > 5

Less than < x < 12

Greater than or equal >= x >= 7

Less than or equal <= x <= 10

Equal == x == 9

Not equal != x != 0

Logical not ! !(x > 12) same as (x <= 12)

28

Page 29: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Boolean Expressions• Boolean expressions are used to test for certain conditions

and return true or false.• Boolean expressions can be combined using the logical

operators && (and) or || (or):x < 12 && x !=0

• These two operators have lower precedence than all operators mentioned so far.

29

Page 30: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

4. CONTROL STATEMENTSSelection and Iteration Statements

30

Page 31: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Statements• The simplest statement is the assignment statement, as seen

in the section on variables.• These may contain arithmetic expressions.

• Statements that belong together can be collected into a unit or block. The start and end of the block is indicated with curly braces.

• Control statements are more complex statements that control the flow of the program, depending on current conditions.• They generally consist of some Boolean expression to test

followed by a statement or block of statements to perform if the Boolean expression is true.

31

Page 32: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Selection Statements• if statement:if (boolean_expression) statement;

• if-else statement:

if (boolean_expression) { statement1; statement2;} else statement3;

• Nested if-else:if (boolean_expression1) statement1;else if (boolean_expression2) { statement2; statement3;} else statement4;

32

Page 33: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Selection Statements• switch statement:switch (integral_expression) {case 1:

statement1;break;

case 2:statement2;break;

case 3, 4:statement3;break;

default:statement4;

}33

Page 34: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Iteration Statements• while statement:

while (boolean_expression) statement;

• It preforms the statement until the Boolean expression is found to be false.

• do-while statement:

do { statement1; statement 2;} while (boolean_expression);

• The statements are preformed once before testing the Boolean expression.

• Remember the semicolon!

34

Page 35: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Iteration Statements

• for statement:for (expression1; boolean_expression; expression2) { statement1; statement2;

• The first expression is usually some variable or expression including variables and can contain a declaration (e.g. int x=0)

• The Boolean expression (e.g. x < 10) is tested before the statements are executed.

• The second expression is executed at the end of each iteration (e.g. ++x).

35

Page 36: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Iteration Statements• Iteration statements (especially for) are frequently used for

working with arrays.for (int i = 0; i< array1.length; ++i) {

array1[i] = i*2;}

• Like if-else statements, iteration statements can also be nested (e.g. accessing a multidimensional array).

• The keywords continue and break are used to skip to the next iteration and exit the iteration statement.

• There is also a for-each loop that has simpler syntax for iterating through elements in data structures.

36

Page 37: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

5. METHODSMethod Declaration, Static Methods, the Main Method

37

Page 38: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Method Declaration• A method is a set of operations related to an object that can

be called from elsewhere. Its declaration contains its scope (e.g. public, private), its return type and its parameter list:

public String getDefinition (String word)• The return statement is the last statement in the method.• In a declaration of a class a method declaration is followed by

a semicolon. In an implementation of the method, the related statements follow, enclosed in curly braces.

• Frequently, method declaration and implementation are not handled separately. 38

Page 39: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Method Declaration• Methods can only return one type (but could return

something like an array) but can have multiple parameters.• Primitive data types are pass-by-value, so the original variable

is not modified by a method to which it is passed.• Objects, however, are pass-by-reference (the reference, or the

object’s location in memory, is passed), and special consideration may need to be made to insure that the original object is not modified by another class or unintentionally lost when the method is finished executing.

39

Page 40: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Static Methods• Normal methods can only be called in relation to an object of

that class:int x = student1.getAge();

• Static methods can be called without an object of that type, but the call needs to include the class in which it is defined; for example, the method

public static float sqrt(int number) located in the Math class can be called by the following:

double x = Math.sqrt(25.12);

40

Page 41: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

The main Method• The main method of an application is its “entry point,” where

the compiler and program execution begin.• The main method has optional parameters for catching

additional instructions from the command line:public static void main (String[] args)

• The return type is void, so no return statement is necessary, or it can be stated as return;

41

Page 42: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Constructor Methods• Constructor methods are used by classes to create an object

when it is initialized.• When creating a class, if no constructor method is included, a

default constructor method is implicitly provided.• The default constructor method sets all primitive data type

variables to 0 and all object variables to null.• Constructor methods that include initial values for the object’s

data can also be created.• If any other constructor is included, a default constructor is not

provided, and must be created if desired.• An additional constructor can also set the object’s data to

different default values.42

Page 43: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Constructor Methods

public class Person { private String name;

public Person() { name = “unspecified”; }

public Person(String newName) { name = newName; }} 43

Page 44: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

6. EXCEPTIONSCatching and Throwing Acceptations

44

Page 45: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Exceptions• An exception is a way of handling conditions that interrupt the

normal flow of execution. For an application to be robust, it should be designed to handle possible exceptions, rather than simply terminating.

• Several methods in the class library (such as I/O classes) require exception handling.

• Generally, exceptions from which the program may recover are checked, and those that are not (i.e. runtime errors) are unchecked.

• When an exception is encountered, it can be handled in that method or it can be thrown back to the calling method, which will be required to catch the exception. The catching method may then decide how (or if) to handle the exception.

45

Page 46: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Catching Exceptions• try-catch blocks are used to catch exceptions. The

method call that might throw an exception is placed within the try block, which is followed by catch blocks for each possible exception.

try { statement1;} catch (exceptionClass identifier) { statement2;}

• The catch block(s) can be followed by an optional finally block, which is always executed.

46

Page 47: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

Throwing Exceptions• A method declaration for a method that throws a checked

exception must contain the exception thrown: public String getLine() throws ExceptionClassName

• The exception is thrown in the method using the throw statement:

throw new ExceptionClass(argument_string);• There are exception classes already defined in the Java Public

Library. New exception classes can also be created.

47

Page 48: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

7. INPUT AND OUTPUTConsole and Text File Input and Output

48

Page 49: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

© 2

006

Pear

son

Addi

son-

Wes

ley.

Al

l rig

hts

rese

rved

1-49

Text Input and Output• Input and output consist of streams• A stream is a sequence of characters that either come from or

go to an I/O device (i.e. keyboard, monitor)• InputStream - Input stream class• PrintStream - Output stream class

• java.lang.System provides three stream objects• System.in – standard input stream• System.out – standard output stream• System.err – standard error stream

Page 50: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

© 2

006

Pear

son

Addi

son-

Wes

ley.

Al

l rig

hts

rese

rved

1-50

Input• Example of the Scanner class:int nextValue;int sum=0;Scanner keyboard = new Scanner(System.in);nextValue = keyboard.nextInt();while (nextValue > 0) {sum += nextValue;nextValue = keyboard.nextInt();

} // end whilekeyboard.close();

Page 51: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

© 2

006

Pear

son

Addi

son-

Wes

ley.

Al

l rig

hts

rese

rved

1-51

Input• Scanner class (continued)

• More useful next methods• String next();• boolean nextBoolean();• double nextDouble();• float nextFloat();• int nextInt();• String nextLine();• long nextLong();• short nextShort();

Page 52: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

© 2

006

Pear

son

Addi

son-

Wes

ley.

Al

l rig

hts

rese

rved

1-52

Output• Methods print and println

• Write character strings, primitive types, and objects to System.out

• println terminates a line of output so next one starts on the next line

• When an object is used with these methods• Return value of object’s toString method is displayed• You usually override this method with your own implementation

Page 53: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

© 2

006

Pear

son

Addi

son-

Wes

ley.

Al

l rig

hts

rese

rved

1-53

File Input and Output• File

• Sequence of components of the same type that resides in auxiliary storage

• Can be large and exists after program execution terminates• Files vs. arrays

• Files grow in size as needed; arrays have a fixed size• Files provides both sequential and random access; arrays provide

random access• File types

• Text and binary (general or nontext) files

Page 54: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

© 2

006

Pear

son

Addi

son-

Wes

ley.

Al

l rig

hts

rese

rved

1-54

Text Files• Designed for easy communication with people

• Flexible and easy to use• Not efficient with respect to computer time and storage

• End-of-line symbol• Creates the illusion that a text file contains lines

• End-of-file symbol• Follows the last component in a file

• Scanner class can be used to process text files

Page 55: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

© 2

006

Pear

son

Addi

son-

Wes

ley.

Al

l rig

hts

rese

rved

1-55

Text Files

Figure 1-11A text file with end-of-line and end-of-file symbols

Page 56: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

© 2

006

Pear

son

Addi

son-

Wes

ley.

Al

l rig

hts

rese

rved

1-56

Text Files• Example

String fname, lname;int age;Scanner fileInput;File inFile = new File("Ages.dat");try {

fileInput = new Scanner(inFile);while (fileInput.hasNext()) {

fname = fileInput.next();lname = fileInput.next();age = fileInput.nextInt();System.out.println(fname + “ ” + lastname + “ is ” + age + “ years old.”);

} // end whilefileInput.close();

} // end trycatch (FileNotFoundException e) {

System.out.println(e);} // end catch

Page 57: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

© 2

006

Pear

son

Addi

son-

Wes

ley.

Al

l rig

hts

rese

rved

1-57

Text Files• Open a stream to a file

• Before you can read from or write to a file• Use class FileReader

• Constructor throws a FileNotFoundException• The file stream is usually embedded within an instance of class Scanner

• After this, reading from the file is similar than reading from System.in.

Page 58: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

© 2

006

Pear

son

Addi

son-

Wes

ley.

Al

l rig

hts

rese

rved

1-58

Text Files• Example

String inputLine;try {Scanner input = new Scanner(new FileReader("Ages.dat"));while ((inputLine = input.readLine()) != null) {

// process line of data...

}} // end trycatch (IOException e) {System.out.println(e);System.exit(1); // I/O error, exit the program

} // end catch

Page 59: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

© 2

006

Pear

son

Addi

son-

Wes

ley.

Al

l rig

hts

rese

rved

1-59

Text Files• File output

• You need to open an output stream to the file• Use class FileWriter• Stream is usually embedded within an instance of class PrintWriter

• That provides methods print and println

Page 60: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

© 2

006

Pear

son

Addi

son-

Wes

ley.

Al

l rig

hts

rese

rved

1-60

Text Files• Example

try {PrintWriter output = new PrintWriter(new FileWriter(“results.dat"));output.println("Results of the survey");output.println("Number of males: " + numMales);output.println("Number of females: " + numFemales);// other code and output appears here...

} // end trycatch (IOException e) {System.out.println(e);System.exit(1); // I/O error, exit the program

} // end catch

Page 61: General Information T.A. Information Name: Andrew Beussink Office: Faner 2038 Office Hours: 1:00 – 3:00 TR, or drop in or by appointment Office Phone:

© 2

006

Pear

son

Addi

son-

Wes

ley.

Al

l rig

hts

rese

rved

1-61

Text Files• Closing a file

• SyntaxmyStream.close();

• Adding to a text file• When opening a file, you can specify if file should be replaced or

appended• Syntax

PrintWriter ofStream = new PrintWriter(new FileOutputStream("Results.dat", true));