java basics - city university of new yorkcwang/212/java_tutorial.pdfinput and output: file i/o using...

33
Java Basics Instructor: Cuiyuan Wang (Ann) [email protected] Queens College 1 / 33

Upload: others

Post on 18-Apr-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Java Basics

Instructor: Cuiyuan Wang (Ann)[email protected]

Queens College

1 / 33

Page 2: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Overview

1 Variables in JAVA

2 Methods

3 Overloading Methods

4 Input/Output statements

5 Strings

6 Exception Handling

7 Summary

2 / 33

Page 3: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Variables in JAVA

Variables

Java programming language defines the following kinds of variables:

1 Instance Variables (Non-Static Fields)

2 Class Variables (Static Fields)

3 / 33

Page 4: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Variables in JAVA

Instance Variables

Their values are unique to each instance of a class i.e., each object

Example: StudentID is an instance variable. Because every studenthas a different StudentID.

4 / 33

Page 5: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Variables in JAVA

Class Variables

A class variable is any field declared with the static modifier, this tellsthe compiler that there is exactly one copy of this variable inexistence, regardless of how many times the class has beeninstantiated/created.

Example: The lecturer of this workshop is always me regardless ofany student. StudentID can be different, but the lecturer is alwaysthe same.

5 / 33

Page 6: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Variables in JAVA

Local Variables

Similar to how an object stores its state in fields, a method will oftenstore its temporary state in local variables.

There is no special keyword designating a variable as local, thatdetermination comes entirely from the location in which the variableis declared-which is between the opening and closing braces of amethod.

Example: for (int i=0; i <10; i++) .... The variable i here is thelocal variable. It is only valid within the opening and closing braces ofthe for loop. It is invalid outside the for loop.

6 / 33

Page 7: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Variables in JAVA

Examples

public void swap( int x, int y )

{

int temp = x; // temp is a local variable

x = y;

y = temp;

}

7 / 33

Page 8: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Methods

Defining Methods

Method declarations have six components:

1 Modifiers—such as public, private, protected.

2 The return type—the data type of the value returned by the method,or void if the method does not return a value.

3 The method name—the rules for naming are same as C++

4 The parameter list in parenthesis—a comma-delimited list of inputparameters, preceded by their data types, enclosed by parentheses. Ifthere is no parameters, you must use empty parentheses.

5 An exception list- to be discussed later.

6 The method body, enclosed between braces- the methods code,including the declaration of local variables.

8 / 33

Page 9: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Methods

Method: Modifiers and Access Levels

Modifier Class Package Subclass World

public Y Y Y Yprotected Y Y Y Nno modifier Y Y N Nprivate Y N N N

9 / 33

Page 10: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Overloading Methods

Overloading Methods

Methods within a class can have the same name if they have differentparameter lists.

Example:

Suppose that you have a class that can use calligraphy to drawvarious types of data and that contains a method for drawing eachdata type.

Option 1: New name for each method—for example,drawString(String s), drawInteger(int i), drawFloat(float f), and so on.

Option 2: Same name but different parameters (Overloading) Youcan use the same name for the drawing methods but pass a differentargument list to each method (see example in next slide)

10 / 33

Page 11: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Overloading Methods

Overloading Methods: Example

public classDataArtist

{

public void draw ( String s )

{

.

}

public void draw ( int i )

{

.

}

public void draw (int i, double f)

{

.

}

}11 / 33

Page 12: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Overloading Methods

Caution: Overloading Methods

The compiler does NOT consider return type when differentiating methods.You cannot declare two methods with the same parameters even if theyhave a different return type.

12 / 33

Page 13: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Input/Output statements

Input and Output: Standard I/O

C++ JAVA

cout << ”Hello World” << endl; System.out.println(”Hello World”);cin >> name; System.in(name);

13 / 33

Page 14: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Input/Output statements

Input and Output: File I/O using ByteStream

CopyBytes spends most of its time in a simple loop that reads theinput stream and writes the output stream, one byte at a time.

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class CopyBytes

{

public static void main(String[]args) throwsIOException

{

FileInputStream in = null;

FileOutputStream out = null;

try

{ in = newFileInputStream("input.txt");

out = newFileOutputStream("output.txt");

14 / 33

Page 15: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Input/Output statements

Input and Output: File I/O using ByteStream

int c;

while ((c =in.read()) != -1)

{

out.write(c);

}

}

finally

{

if (in != null)

{

in.close();

}

if (out != null)

{

out.close();

}

}

}

}

15 / 33

Page 16: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Input/Output statements

When Not to Use Byte Streams

CopyBytes seems like a normal program, but it actually represents a kindof low-level I/O that you should avoid.Byte streams should only be used for the most primitive I/O.Byte streams use unbuffered I/O. This means each read or write requestis handled directly by the underlying OS.This can make a program much less efficient, since each such requestoften triggers disk access, network activity, or some other operation that isrelatively expensive.So why talk about byte streams?Because all other stream types are built on byte streams.

16 / 33

Page 17: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Input/Output statements

Input and Output: File I/O using BufferedStream

To reduce this kind of overhead, the Java platform implements bufferedI/O streams.Buffered input streams read data from a memory area known as a buffer;the native input API is called only when the buffer is empty.Similarly, buffered output streams write data to a buffer, and the nativeoutput API is called only when the buffer is full.A program can convert an unbuffered stream into a buffered stream .There are four buffered stream classes used to wrap unbuffered streams:BufferedInputStream and BufferedOutputStream create buffered bytestreams, while BufferedReader and BufferedWriter create bufferedcharacter streams.(example below)

BufferedReader in, out;

in = new BufferedReader(newFileReader("input.txt"));

out = newBufferedWriter(newFileWriter("output.txt"));

17 / 33

Page 18: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Strings

Strings

Strings are widely used in Java programming.

A string is a sequence of characters.

String is class and hence each instance is an object of type String.

18 / 33

Page 19: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Strings

Creating Strings

Two options:

1 String greeting = "Hello World!" ; //string literal

2 char[] helloArray = { ’h’, ’e’, ’l’, ’l’, ’o’, ’.’ };

String helloString = new String(helloArray);

19 / 33

Page 20: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Strings

String Conversion

Converting Strings to Numbers

int x= Integer.parseInt("3");

Converting Numbers to Strings

Three options:

int i;

String s1 = " " + i;

String s2 = String.valueOf(i);

String s3 = Integer.toString(i);

20 / 33

Page 21: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Strings

Manipulating Characters in a String

Getting Characters and Substrings by Index:

String a = "hello!";

//gets the character at position index 1

char b = a.charAt(1);

//gets the substring starting at position index 1 (including)

//to index 3 (excluding)

String c = a.substring(1,3);

//gets the string starting at position index 3 up to the end

String d = a.substring(3);

System.out.println (a + " " + b + " " + c + " " + d);

The output is

hello! e e1 lo!

21 / 33

Page 22: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Exception Handling

What is an Exception

Definition:

An exception is an event, which occurs during the execution of aprogram, that disrupts the normal flow of the program’s instruc-tions.

When an error occurs within a method, the method creates an objectand hands it off to the runtime system.

The object, called an exception object, contains information aboutthe error, including its type and the state of the program when theerror occurred.

Creating an exception object and handing it to the runtime system iscalled throwing an exception.

22 / 33

Page 23: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Exception Handling

Types of Exceptions

There are three kinds of Exceptions:

1 Checked exception

2 Error

3 Runtime Exception

Errors and runtime exceptions are collectively known as uncheckedexceptions.

23 / 33

Page 24: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Exception Handling

Checked Exceptions

These are exceptional conditions that a well-written application shouldanticipate and recover from.Example

Suppose an application prompts a user for an input file name,then opens the file by passing the name to the constructor forjava.io.FileReader.

Normally, the user provides the name of an existing, readable file, sothe construction of the FileReader object succeeds, and theexecution of the application proceeds normally.

But sometimes the user supplies the name of a nonexistent file, andthe constructor throws java.io.FileNotFoundException.

A well-written program will catch this exception and notify the user ofthe mistake, possibly prompting for a corrected file name.

24 / 33

Page 25: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Exception Handling

Error

These are exceptional conditions that are external to the application, andthat the application usually cannot anticipate or recover from.Example

Suppose that an application successfully opens a file for input,but is unable to read the file because of a hardware or systemmalfunction. The unsuccessful read will throw java.io.IOError.

An application might choose to catch this exception, in order tonotify the user of the problem

It also might make sense for the program to print a stack trace andexit.

25 / 33

Page 26: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Exception Handling

Runtime Exception

These are exceptional conditions that are internal to the application, andthat the application usually cannot anticipate or recover from. Theseusually indicate programming bugs, such as logic errors or improper use ofan API.Example

Consider the application described previously that passes a filename to the constructor for FileReader. If a logic error causes anull to be passed to the constructor, the constructor will throwthe NullPointerException.

The application can catch this exception

It probably makes more sense to eliminate the bug that caused theexception to occur

26 / 33

Page 27: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Exception Handling

try-catch Statement for Exception Handling: The try

block

The first step in constructing an exception handler is to enclose the codethat might throw an exception within a try block.

private List<Integer> list;

private static final int SIZE = 10;

PrintWriter out = null;

try

{

System.out.println("Entered try statement");

out = new PrintWriter ( newFileWriter ( "OutFile.txt" ) );

for ( int i = 0; i < SIZE; i++)

out.println("Value at: " +i+ " = " +list.get(i));

}

// put catch and finally statements . . .

Question: Why do we add the try block here? 27 / 33

Page 28: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Exception Handling

try-catch Statements for Exception Handling: The try

block

Answer: Why do we add the try block here?

The second line in try block is a call to a constructor.

The constructor initializes an output stream on a file.

If the file cannot be opened, the constructor throws an IOException.

The forth line in the try block is a call to the arrayList class’s get method.

This call throws an IndexOutOfBoundsException if the value of itsargument is too small (less than 0) or too large (more than thenumber of elements currently contained in the array)

28 / 33

Page 29: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Exception Handling

try-catch Statements for Exception Handling: The catch

block

try

{

//see the try block slide

} catch (FileNotFoundExceptione)

{

System.err.println("FileNotFoundException: "

+ e.getMessage());

throw newSampleException(e);

} catch (IOExceptione)

{

System.err.println("CaughtIOException: "

+ e.getMessage());

}

29 / 33

Page 30: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Exception Handling

try-catch Statements for Exception Handling: Thefinally block

The finally block always executes when the try block exitsregardless of what happens within the try block.

finally

{

if (out != null)

{

System.out.println("Closing PrintWriter");

out.close();

}

else

{

System.out.println("PrintWriter not open");

}

}30 / 33

Page 31: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Exception Handling

Example: try-catch and finally put togetherpublic void writeList()

{

PrintWriterout = null;

try

{

System.out.println("Entering" + " try statement");

out = new PrintWriter(new FileWriter("OutFile.txt"));

for (int i= 0; i < SIZE; i++)

out.println("Value at: " +i+ " = " +vector.elementAt(i));

}

catch (ArrayIndexOutOfBoundsExceptione)

{

System.err.println("CaughtArrayIndexOutOfBoundsException:"

+ e.getMessage());

}

catch (IOExceptione)

{31 / 33

Page 32: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Exception Handling

Example: try-catch and finally put togetherSystem.err.println("CaughtIOException: "

+ e.getMessage());

}

finally

{

if (out != null)

{

System.out.println("ClosingPrintWriter");

out.close();

}

else

{

System.out.println("PrintWriternot open");

}

}

}

32 / 33

Page 33: Java Basics - City University of New Yorkcwang/212/JAVA_tutorial.pdfInput and Output: File I/O using Bu eredStream To reduce this kind of overhead, the Java platform implements bu

Summary

Summary

Variables: instance variables, class variables, local variables,parameters.

Methods: method modifiers(public, private, protected), methodssignature(method name, parameter type), methods overloading.

Input/Output statements: Byte Streams, Buffered Streams

Strings: creating Strings, converting strings to numbers, manipulatingcharacters in strings

Try-Catch statements: Exceptions, three types of exceptions,try-catch-finally blocks.

33 / 33