Java - Exceptions

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Console is located in java.lang.console true or false

false. Console is located in java.io.Console

In File class flush() frees up expensive operating system resources. True or false

false. It guarantees last data gets written to disk. close() frees up expensive operating system resources.

Java 7 Compilers use instance methods in Paths to create files and directories. True or false

false. Java 7 Compilers use static methods in Paths to create files and directories.

Path and Paths contain only static methods true or false?

false. Path is an interface.

import java.io.File; import java.io.FileWriter; import java.io. PrintWriter; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileWriter fw = new FileWriter(f); PrintWriter pw = new PrintWriter( fw); pw.println("c"); pw.println("d"); pw.flush(); pw.close(); } } where myFile.txt has two lines contatining "a b" on separate lines. When the above code executes c and d get appended to the file resulting in "a b c d" each on separate lines. True or false

false. a and b get overwritten with c and d therefore output would be: c d

A(n) ____________________ object is an avenue for reading and writing a file.

file channel

the _____ holds the byte number of a location in the file

file pointer (721)

finally block

finally always runs after the try-catch block, regardless of what happens

the _____ is 1 or more statements that are always executed after the try block has executed and after any catch blocks have executed if an exception was thrown

finally block (698) ~the statements in the finally block execute whether an exception occurs or not

the try statement may have an optional _____ clause, which must appear after all of the catch clauses

finally clause (697) ~this is optional

FileWriter - BufferedWriter - PrintWriter all contain two common methods. Named them.

flush() and close() ----> flush(): guarantees that the last of the data gets written to disk. close(): Closes the stream and releases any system resources associated with it.

What method am I? guarantees that the last of the data gets written to disk.

flush() located in FileWriter - BufferedWriter - PrintWriter

catch clause

follows try block. Defines how to handle the exceptions.

This type of loop is ideal in situations where the exact number of iterations is known.

for loop

for loop

for(initialization; condition; iteration) statement; in the most common form of loops is the for loop. initialization sets a loop control variable to an initial value. The conditon is a Boolean expressoin that tests the loop control variable. If true, the for loop continues to iterate. If false, the loop terminates. Iteration - how the loop control variable is changed each time the loop iterates.

General form of the for

for(initialization; condition; iteration) statement; initialization is the assignment of value to a variable. Condtion to check for true or false Iteration - what to do if true

How unchecked exceptions are propagated

from top of the stack to the main method by defualt

each exception object has a method named _____ that can be used to retrieve the *default error message* for the exception

getMessage (688) ~also used when the exception is not handled & the app halts

>=

greater than or equal to

to ____ an exception, you use a try statement

handle (684)

Catch block is used for

handling exception and it must be used after try block

permanent storage device

hardware used to store files

languages that let you use an easily understood vocabruary of descriptive terms, as as "read," "write," or "add," are known as ________ languages.

high-level language

Throwing exceptions short hand

if (whatever) throw new MaxException("Something went wrong."); Note, you just need to throw an exception object, and that's why there's a new MaxException. You don't really need to assign a var/object to it.

FACT

if a class contains objects of other classes as fields, those classes must implement the *Serializable* interface, in order to be *serialized* (724)

When does the checked exceptions propagate the calling chain

if the exception is declared with throws key word

WARNING

if the file that you are opening with the *FileOutputStream* object already exists, it will be erased & an empty file by the same name will be created (713)

When does finally block not executed

if the program terminates calling system.exit() or with fatal errors that causes the program to abort

How to handle an exception?

if u r calling a method that declares an exception we must either catch the exception or declare the exception

FACT

if you do not pass a message to the constructor, the exception will have a *null* message (704)

FACT

if you pass the name of an existing file to the FileOutputStream constructor, it will be erased and a new empty file with the same name will be created (718)

General form of if statement

if(condition) statement;

examples of things stored in binary

images, music, or compiled program files with a .class extension (bytecode)

What do you need to do to use File -FileWriter- FileReader - BufferedReader - BufferedWriter - PrintWriter in your code

import java.io.*;

When using the PrintWriter class, which of the following import statements would you write near the top of your program?

import java.io.*;

Byte Streams : FileInputStream and FileOutputStream Example

import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }

import ___.___.*; class B { public static void main(String[] args) throws Exception { File a = new File("c:\\a\\f.txt"); FileWriter writer = _______; writer._______("Hello"); writer.________; writer._________; } } Fill in the blanks (Assume the file exists).

import java.io.*; class B { public static void main(String[] args) throws Exception { File a = new File("c:\\a\\f.txt"); FileWriter writer = new FileWriter(a); writer.write("Hello"); writer.flush(); writer.close(); } }

import java.io._____ ; import java.io._____ ; import java.io._____ ; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); _____ i = new _____ (f); _____ j = new _____ (i); System. out. println(j._____ ()); } } Using BufferedReader and FileReader fill in the blanks above to read the first line within the file myFile.txt

import java.io.BufferedReader; import java.io.File; import java.io.FileReader; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); System. out. println(br.readLine()); } }

Create an empty directory using only java.io.File; for C:\\a\\

import java.io.File; class A { public static void main( String [] args) { File f = new File( "C:\\a\\b\\"); f.mkdir(); } }

Check if a file exists using only java.io.File; C:\\a\\b\\log.txt

import java.io.File; class A { public static void main( String [] args) { File f = new File("C:\\a\\b\\log.txt"); System. out. println( f.exists()); } } Will return true if file exists

Create an empty directory using only java.io.File; for "C:\\a\\b\\" folders

import java.io.File; class A { public static void main( String[] args) { File f = new File( "C:\\a\\b\\"); f.mkdirs(); } } Note: The main method does not need to declare that it throws Exception

import java.io._____ ; class A { public static void main(String[] args) throws Exception { _____ dir = new _____ ("C:\\a\\b\\"); dir._____ (); _____ f = new _____ (dir, "MyFile.txt"); _____ . _____ ();} } Fill in the blanks above to create a new file "MyFile.txt" within the newly created directories a\b

import java.io.File; class A { public static void main(String[] args) throws Exception { File dir = new File("C:\\a\\b\\"); dir.mkdirs(); File f = new File(dir, "MyFile.txt"); f. createNewFile();} }

Create an empty file using only java.io.File; for "C:\\a\\b\\Log.txt" folders

import java.io.File; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\b\\Log.txt"); f.createNewFile(); } }

Write code to check if I named MyFile.txt exists within the directory C:\a\b

import java.io.File; class B { public static void main(String[] args) { File f = new File("c:\\a\\b\\MyFile.txt"); System. out. println( f.exists()); } }

import java.io.File; class B { public static void main(String[] args) { File f = new File("____"); System. out. println( _____ ); } } Fill in the code above to check if I named MyFile.txt exists within the directory C:\a\b

import java.io.File; class B { public static void main(String[] args) { File f = new File("c:\\a\\b\\MyFile.txt"); System. out. println( f.exists()); } }

import java.io.____; import java.io._____; import java.io. ____; class A { public static void main( String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); ______ i = new _____(f); _____ j = new _____(i); j.______("Hello2"); j._______("World2"); j.flush(); j.close(); } } Fill-in the above spaces which writes text to the disc (one line at a time)

import java.io.File; import java.io.FileWriter; import java.io. PrintWriter; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileWriter i = new FileWriter(f); PrintWriter j = new PrintWriter(i); j.println("Hello2"); j.println("World2"); j.flush(); j.close(); } }

import java.io._____ ; import java.nio._____ ._____ ; class A { public static void main(String[] args) { File f = new File("C:\\a\\b"); _____ p = f._____ (); System. out. println(p); } } Complete the code above to convert File f into the Path new class.

import java.io.File; import java.nio.file.Path; class A { public static void main(String[] args) { File f = new File("C:\\a\\b"); Path p = f.toPath(); System. out. println(p); } } Used to get Path with compiler less than Java 7

import java.io._____ ; import java.nio._____ ._____ ; class A { public static void main(String[] args) { Path p = Paths.get("C:\\a\\b"); _____ f2 = p._____ (); System. out. println(f2); } } Complete the code above to convert Path p into the old File object.

import java.io.File; import java.nio.file.Path; class A { public static void main(String[] args) { Path p = Paths.get("C:\\a\\b"); File f2 = p.toFile(); System. out. println(f2); } }

import java._____ ._____ ; import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths.get(_____ ._____ ( "file:///C://a//File.txt")); System. out. println(p1); } } Fill in the above blanks to enable the file path to be printed to screen on Windows OS

import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths.get("file:///C://a//File.txt"); System. out. println(p1); } } This results in C:\a\File.txt getting printed screen

import java._____ ._____ .Files; import java._____ ._____ .Path; import java._____ ._____ ._____ ; class A { public static void main ( String[] args) throws Exception { Path src = Paths.get( "C:\\a\\log1.txt"); Files.delete(src); } Complete the above code that deletes the file log1.txt

import java.nio.file.Files; import java.nio.file.Path; import java.nio. file.Paths; class A { public static void main ( String[] args) throws Exception { Path src = Paths.get( "C:\\a\\log1.txt"); Files.delete(src); }

import java._____ ._____ .Files; import java._____ ._____ .Path; import java._____ ._____ ._____ ; class A { public static void main ( String[] args) throws Exception { Path src = _____ ._____ ( "C:\\a\\log1.txt"); _____ des = _____ ._____ ( "C:\\a\\log2.txt"); _____ ._____ (src, des); } } Complete the above code that copies the contents of log1.txt to log2.txt

import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main ( String[] args) throws Exception { Path src = Paths.get( "C:\\a\\log1.txt"); Path des = Paths.get( "C:\\a\\log2.txt"); Files.copy(src, des); } }

import java._____ ._____ .Files; import java._____ ._____ .Path; import java._____ ._____ ._____ ; class A { public static void main ( String[] args) throws Exception { Path src = _____ ._____ ( "C:\\a\\log1.txt"); _____ des = _____ ._____ ( "C:\\a\\log2.txt"); _____ ._____ (src, des); } } Where log2.txt does not exist write code that copies the contents of log1.txt to log2.txt

import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main ( String[] args) throws Exception { Path src = Paths.get( "C:\\a\\log1.txt"); Path des = Paths.get( "C:\\a\\log2.txt"); Files.copy(src, des); } }

Create an empty directory using with java.nio.file; for C:\\a\\b\\

import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main( String [] args) throws Exception { Path p = Paths.get( "C:\\a\\b\\"); Files.createDirectories(p); } } Note: it's best to declare that the main method throws Exception when dealing with files

Create empty file using only java.nio.file; for "C:\\a\\b\\Log.txt" file

import java.nio.file.Files; import java.nio.file.Path; import java. nio. file.Paths; class A { public static void main( String[] args) { Path p = Paths.get("C:\\a\\b\\Log.txt"); Files.createFile(p);} }

Check if a file exists using only java.nio.file; C:\\a\\b\\log.txt

import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p = Paths.get("C:\\a\\b\\log.txt"); System. out. println(Files.exists(p)); } } Will return true if file exists

import java.____.file.____; import java.____.file.____; class A { public static void main(String[] args) { Path p1 = _____ ._____ ( "C:\\a\\b\\File.txt"); System. out. println(_____ ); } } Write the code that builds the past for a file location.

import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths.get( "C:\\a\\b\\File.txt"); System. out. println(p1); } } Note: the file location does not need to exist physically.

All java statements end

in a semicolon

FACT

in many cases, the code in the try block will be capable of throwing more than 1 type of exception (690)

Serializable interface

in order for an obcect to be serialized, its class must implement this interface, which is in the *java.io* package & has no methods or fields (724)

the problem with sequential file access:

in order to read a specific byte from the file, all the bytes that precede it must be read first (718)

FACT

in the try block and the catch block, the braces are required (684)

This type of loop has no way of ending and repeats until the program is interrupted.

infinite

If a loop does not contain within itself a way to terminate, it is called an:

infinite loop

data

information processed or stored by a computer

Exception classes are related by

inheritence

This expression is executed by the for loop only once, regardless of the number of iterations.

initialization expression

where is throw keyword used?

inside a method

Random files are also called ____________________ files.

instant access direct access

Assuming that inputFile references a Scanner object that was used to open a file, which of the following statements will read an int from the file?

int number = inputFile.nextInt();

Can declare multiple variables using the same declaration statement

int var1, var2; // both declared using one statement Separate names b commas

*Error* class

intended to be a *superclass* for exceptions that are thrown when a critical error occurs, such as an internal error in the JVM or running out of memory (683) ~your apps should not try to handle these errors because they are the result of a serious condition

exception handling

intercepting & responding to *exceptions* (682)

examples of permanent storage

internal/external hard disks, disks, USB drives, magnetic reels, cassettes, etc.

Why exception Handling is required?

is a mechanism to handle the runtime errors so that normal flow of the program is maintained.

Variable

is a named memor ylocation that can be assigned a value. Can be changed during the execution of a program.

A sentinel value _________ and signals that there are no more values to be entered.

is a special value that cannot be mistaken as a member of the list

The exception class

is a subclass of the Throwable class.

Exception

is an object that describes an unusual situation

Error

is another subclass of the Throw-able class - abnormal conditions that happen in case of severe failures, these are not handled by the Java programs. - are generated to indicate errors generated by the runtime environment.

Checked exeption

is one that must either be caught by a method or be listed in the throws clause of any method that may throw or propagate it

Throwable class

is the parent of both the Error class and the Exception class

root directory

it is placed here when storing a permanent file; equivalent to tossing a loose paper in a filing cabinet

what happens if we declare the exception but not try/catch

it throws a runtime exception. Throws only tells the programmer that an exception might be thrown and propagates the checked exception in the calling chain

What is each repetition of a loop known as?

iteration

What happens if exception is not handled

java default exception handler triggers and print the exception message, print the stack trace and terminates the program

catch

keyword for code block with the exception that might occur

try

keyword for code block you want to check

volatile

likely to change in a sudden way, temporary/momentary

java supports three types of comments: _______, and _____, and javadoc

line + block

This is a variable that controls the number of iterations performed by a loop.

loop control variable

the most basic circuitry-level computer language is

machine language

all Java applications must have a method named

main ()

Exceptions

may represent a situation that won't occur under usual conditions, represents an abnormal condition in the flow of the program They are objects, and objects are defined using classes.

mkdir( )

method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.

mkdirs()

method creates both a directory and all the parents of the directory.

seek method

method used to move the *file pointer* (721)

the ability to catch multiple types of exceptions with a single catch clause is known as _____ and was introduced in Java 7

multi-catch (701)

throw clause

must be appended to the header of a method definition to formally acknowledge that the method will throw or propagate a particular exception (that is, will not catch it, and will not handle it)

All variables must

must be declared before they are used The type of values the variable can old must also be specified

Java is architecturally

neutral

should you handle unchecked exceptions including *Error* or *RuntimeException*?

no (703)

An instance of a class is a(n)

object

What is the class hierachy in Exception handling

object <- throwable <- (Runtime,checked,Error)

The individual operations used in computer program are often grouped into logical units called _______

object oriented programming

How many finally block are allowed after try or after catch

only 1

not including polymorphic references, a try statement can have _____ catch clause(s) for each specific type of exception

only 1 (696)

Which exceptions needs to be declared

only checked exception

How many exceptions are occured at a time and how many catch blocks are executed

only one exception occurs at any time and only one catch block is executed

Envisioning program components as objects that are similar to concrete objects in the real world is the hallmark of _________

orientation

the values of an objects attributes are known as its _____

orientation

in order for a catch clause to be able to deal with an exception, its _____ must be of a type that is compatible with the exception type

parameter (684)

arguments to methods always appear within ________

parethesis

Nonvolatile Storage Disk

permanent storage; it is not lost when a computer loses power

when handling exceptions, you can use a(n) _____ reference as a parameter in the catch clause

polymorphic (690)

In the expression number++, the ++ operator is in what mode?

postfix

The do-while loop is this type of loop.

posttest

The for loop is this type of loop.

pretest

The while loop is this type of loop.

pretest

System.out.print("var2 contains var1 / 2: "); System.out.println(var2);

print() displays the string "var2 contains var1 /2:" The next output will start on the same line

Print a blank line

println() with no arguments

import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths.get("Log.txt"); System. out. println(p1.isAbsolute()); }} A.java and Log.txt above are located in C:\a folder. What is the the output when code run?

prints false as Paths.get("Log.txt"); is not an absolute path it is a relative path. The following would return true: Path p1 = Paths.get("C:\\a\\Log.txt"); indicating an absolute path to Log.txt

import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths.get("C:\\a\\Log.txt"); System. out. println( p1.isAbsolute()); }} A.java and Log.txt above are located in C:\a folder. What is the the output when code run?

prints true. Paths.get("C:\\a\\Log.txt"); is an absolute path

list( ) method

provided by File object to list down all the files and directories

public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileWriter fw = new FileWriter(f); BufferedWriter bw = new BufferedWriter(fw); bw.write("a"); bw.write(______.________()); bw.write("b"); bw. flush(); bw.close(); } Fill in the blank above to get in separator on your particular operating system

public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileWriter fw = new FileWriter(f); BufferedWriter bw = new BufferedWriter(fw); bw.write("a"); bw.write(System.lineSeparator()); bw.write("b"); bw.flush(); bw.close(); } The above called with print a and b (on separate lines).

in _____, a program can immediately jump to any location in the file without first reading the preceding bytes

random file access (718)

List one method from FileReader class

read()

List two methods from BufferedReader

read() readLine()

Console contained a method a returns a string containing whatever the user entered. What is the name of this method?

readLine() - Reads a single line of text from the console.

Console input method can be used to not echo password. What is the name of this method?

readPassword() - Reads a password or passphrase from the console with echoing disabled

Boolean readBoolean() [DataInputStream method]

reads a boolean value from the file into returns it (716)

byte readByte() [DataInputStream method]

reads a byte value from the file and returns it (716)

double readDouble() [DataInputStream method]

reads a double value from the file and returns it (716)

float readFloat() [DataInputStream method]

reads a float value from the file and returns it (716)

long readLong() [DataInputStream method]

reads a long value from the file and returns it (716)

short readShort() [DataInputStream method]

reads a short value from the file and returns it (716)

int readInt() [DataInputStream method]

reads an int value from the file and returns it (716)

A(n) ____________________ is a collection of fields that contain data about an entity.

record

unchecked exception

requires no throws clause (Only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants. All others are considered checked.)

the command to execute a compiled java application is _______

run

When you write a Java program and __________, you are using __________.

save it to disk; permanent storage

when the code in a method throws an exception, the normal execution of that method stops & the JVM _____ for a compatible exception handler inside the method

searches (702) ~if there is no code inside the method to handle the exception, then control of the program is passed to the previous method in the call stack [the method that called the offending method] ~if that method cannot handle the exception, then control is passed again, up the *call stack*, to the previous method. ~this continues until control reaches the *main method* ~if the main method does not handle the exception, then the program is halted and the default exception handler handles the exception (702)

when an exception is thrown by code in the try block, the JVM begins _____ the try statement for a catch clause that can handle it

searching (692) ~it searches the catch clauses from top to bottom and passes control of the program to the first catch clause with a parameter that is compatible with the exception

all java programming statements must end with a _______

semi-colom

This is a special value that signals when there are no more items from a list of items to be processed. This value cannot be mistaken as an item from the list.

sentinel

with _____ access, when a file is opened for input, its read position is at the very beginning of the file

sequential access (718) ~this means that the first time data is read from the file, the data will be read from its beginning. ~as the reading continues, the file's read position advances sequentially through the file's contents

Java allows you to _____ objects, which is a simpler way of saving objects to a file

serialize (724)

*IOException*

serves as a superclass for exceptions that are related to input and output operations (683)

*RuntimeException*

serves as a superclass for exceptions that result from programming errors, such as an out-of-bounds array subscript (683)

Error

similar to exception, except that an error generally represents an unrecoverable situation and should not be caught

What should be the order of catch blocks if there are more than one

small to big, arthimetic, exception but not Exception and Arthimetic

When you execute Java interpreter, you are

specifiying the name of hte class. It will search for a file by that name with a .class extension then execute the code in the specified class.

finally

statement that will be executed whether or not there is an exception

System.exit

static method ________ terminates an application.

When you write a Java program that __________, you are using __________.

stores a value in a variable; RAM

FACT

storing data in its *binary format* is more efficient than storing it as text because there are fewer conversions to take place (713)

input stream

stream from which we read information

output stream

stream to which we write information

if the parent class declares an exception then subclass overridden method

subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

the rules of a programming language constitute it's _________

syntax

Void

tells the computer that main() does not return a value

RAM

temporary storage within a computer; "memory"

;

terminates statements Ends a logical entity NOT used to end a block Can write multiple statements on the same line if they're separated with a ; Ex. x=y; y=y+1; System.out.println(x + " " + y); Can also break really long lines up to make them more readable.

Categories of Files

text files and binary files

FACT

the *FileInputStream constructor* will throw a *FileNotFoundException* if the file named by the string argument cannot be found (715)

FACT

the *FileNotFoundException* is a *checked exception* (703)

NOTE

the *FileOutputStream* constructor throws an *IOException* if an error occurs when it attempts to open the file (713)

which class can you use to sequentially process a binary file?

the *RandomAccessFile class* (719)

FACT

the *RandomAccessFile class* treats a file as a stream of bytes (721) ~tey are numbered, with the first byte being 0 & the last being 1 less than the number of bytes in the file

NOTE

the *exception classes* are in packages in the Java API (683)

You can use this method to determine whether a file exists.

the File class's exists method

NOTE

the Java API documentation lists all of the exceptions that can be thrown from each method (685)

In what cases finally is executed

the block is executed always . no matter if there is an exception or not or it is handled or not

When java source code is compiled, each class is put into its own output file named after

the class using hte .class extension Give java source file the same name as the class the contain so the source file name will match the name of hte .class file.

CONCEPT

the content of a binary file is not formatted as text & not meant to be opened in a text editor (712)

FACT

the default exception handler *prints* an error message & crashes the program (682)

What happens if we write try/catch

the exception is handled and the program flow is normal

FACT

the key word *throws* is written at the end of the method header, followed by a list of the types of exceptions that the method can *throw* (703)

Name of main class should match

the name of hte file that holds the program. Make sure the capitalization matches as well, it's case sensitive.

Out

the output system stream that is connected to the console

deserialization

the process of reading a serialized object's bytes and constructing an object from them (725)

try block

the program to be executed always If no error is caught, then the program runs normally. If error caught, program jumps to the appropriate catch handler. After error has been handled, code after the try-catch block is run.

Not handling exceptions

the program will run up until the exception, and then it will crash and print out an error message.

FACT

there are many error conditions that can occur while a Java app is running that will cause it to halt execution (681)

FACT

there are some types of data that should be stored only in its raw binary format (713) ~*images, audio, & video* are an example

IO-Exceptions

these are exceptions that occurs during reading or writing to input or output stream.

void writeChar(int c) [DataOutputStream method]

this method accepts an int which is assumed to be a character code. The character it represents is written to the file as a 2-byte Unicode character (714)

Syntax of throw keyword

throw new Exception();

*EOFException* object

thrown when an app attempts to read beyond the end of the file (683)

*FileNotFoundException* object

thrown when an app tries to open a file that does not exist (683)

the _____ clause informs the compiler of the exceptions that could get thrown from a method

throws clause (703)

FACT

to meet the needs of a specific class or app, you can create your own exception classes by extending the Exception class or 1 of its subclasses (708)

FACT

to open a binary file for input, you wrap a *DataInputStream object* around a *FileInputStream object* (715)

CONCEPT

to prevent *exceptions* from crashing your program, you must write code that detects and handles them (681)

FACT

to serialize an object and write it to the file, use the *ObjectOutputStream* class's *writeObject* method (725)

Why is throws keyword used?

to tell the caller of the method that there is a probability of exception occurring. In order to maintain normal flow of the program he needs to handle the exception it makes checked exception to propagate the calling chain

FACT

to write *bytes to a file*, use an output stream object, such as *FileOutputStream* (725)

File -FileWriter- FileReader - BufferedReader - BufferedWriter - PrintWriter are located in java.io true or false

true

File -FileWriter- FileReader - BufferedReader - BufferedWriter - PrintWriter need to have be wrapped in a try/catch block or declare that method throws an Exception. true or false

true

Files and Paths contain only static methods true or false?

true

In File class flush() guarantees last data gets written to disk. close() frees up expensive operating system resources. true or false

true

Path is located in java.nio.file.Path true or false

true

import java.io.File; import java.io.FileWriter; import java.io. PrintWriter; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileWriter fw = new FileWriter(f); PrintWriter pw = new PrintWriter( fw); pw.println("c"); pw.println("d"); pw.flush(); pw.close(); } } where myFile.txt has two lines contatining "a b" (On separate lines). When the above code executes c and d get overwritten resulting in "c d" each on separate lines. True or false

true

BufferedWriter is more efficient than FileWriter true or false

true. BufferedWriter is more efficient FileWriter as FileWriter writes single chars at a time whereas BufferedWriter writes chunks of data to file

Console is located in java.io.Console true or false

true. Console contains methods to access the PHYSICAL DEVICES i.e. keyboard/monitor

Java 7 Compilers use static methods in Paths to create files and directories.

true. e.g. Path p = Paths.get("C:\\a\\b\\Log.txt"); Path p = Paths.get("C:\\a\\b"); Files.createDirectories(p);

a _____ is 1 or more statements that are executed & can potentially throw an exception

try block (684)

try-catch

try {...} catch {...} finally {...} Can have as many catches as I want. Don't have to have finally. Technically, don't have to have a catch if i have a finally. I can't think of a situation where that would be appropriate...

Declare a variable

type var-name Type is the type of variable being declared var-name is the name of the variable

the 2 categories of exceptions include:

unchecked & checked (703)

_____ inherit from the *Error* class or the *RuntimeException* class

unchecked exceptions (703)

FACT

use *OutputInputStream* object along with a *FileInputStream* object (725)

Usage of throw keyword

used to explicitly throw an exception

How to handle exceptions?

using try/catch or throws keyword

Named computer memory locations are called ________

variables

The value you store in memory is lost when the program ends or the computer loses power. This type of storage device is called ____________________.

volatile

Two Mains Types of Storage Devices

volatile and nonvolatile storage

FACT

when a file is first opened, the *file pointer* is set to 0 (721) ~when an item is read from the file, it is read from the byte that the *file pointer* points to ~Reading also causes the pointer to advance to the byte beyond the item that was read

exception propagation (handling elsewhere)

when an exception is caught and handled at an outer level in the method-calling hierarchy. If an exception is not caught and handled in the method where it occurs, control is immediately returned to the method that invoked the method that produced the exception. If it isn't caught there, control returns tot he method that called it, and so on.

FACT

when an exception is thrown by a method executing under several layers of method calls, it is sometimes helpful to know which methods were responsible for the method being called (699)

FACT

when an exception is thrown, it cannot be ignored, but must be handled by the program or default exception handler (702)

FACT

when an object is serialized, it is converted into a series of bytes that contains the object's data (724) ~if the object is set up properly, even the other objects that it might contain as fields are automatically *serialized*

FACT

when data is stored in a *binary file*, you cannot open the file in a text editor (713)

FACT

when in the same try statement you are handling multiple exceptions & some of the exceptions are related to each other through inheritance, then you should handle the more specialized exception classes before the more general exception classes (697)

when is an *exception thrown*?

when the code does *not handle* an exception (682)

Assume that inputFile references a Scanner object that was used to open a file. Which of the following while loops shows the correct way to read data from the file until the end of the file is reached?

while (inputFile.hasNext()) { ... }

Which of the following are pre-test loops?

while, for

Integer values

whole number values, precede the name of a variable with the keyword int

How far will it propagate?

will be propagated until it is caught and handled or until it is passed out of the main method, which causes the program to terminate and produces an exception message.

catch (InputMismatchException ex) { System.out.println("integer is required"); input.nextLine();

write a catch block to handle input mismatch that prints "integer required" and prepares for new input public class InputMismatchExceptionDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean continueInput = true; do { try { System.out.print("Enter an integer: "); int number = input.nextInt(); // Display the result System.out.println( "The number entered is " + number); continueInput = false; } _______ } } while (continueInput); } }

the _____ method throws an *IOException* if an error occurs

writeObject method (725)

to write a string to a binary file you should use the *DataOutputStream* class's _____ method

writeUTF method (717) ~this method writes its *String* argument in a format known as *UTF-8 encoding*

void writeUTF(String str) [DataOutputStream method]

writes the String object passed to str to the file using the Unicode Text Format (714)

void writeBoolean(boolean b) [DataOutputStream method]

writes the boolean value passed to b to the file (714)

void writeByte(byte b) [DataOutputStream method]

writes the byte value passed to b to the file (714)

void writeDouble(double d) [DataOutputStream method]

writes the double value to d to the file (714)

void writeFloat(float f) [DataOutputStream method]

writes the float value passed to f to the file (714)

void writeInt(int i) [DataOutputStream method]

writes the int value passed to i to the file (714)

void writeLong(long num) [DataOutputStream method]

writes the long value passed to num to the file (714)

void writeShort(short s) [DataOutputStream method]

writes the short value passed to s to the file (714)

All source code is first

written into plain text files ending in .java. Those source files are then compiled into .class files by javac compiler, this contains bytecodes. The java launcher tool then runs your application with the Java virtual machine.

can we declare multiple exceptions with throws keyword at once

yes

Can we rethrow an exception

yes by throwing the same exception in the catch block

The if statement

you can selectively execute part of a program through if. if(condition) statement; If true, it's executed If false, it's skipped

FACT

you can think of the code in the try block as being *protected* since the app will not halt if the try block throws an exception (684)

FACT

you can use the *throw* statement to manually throw an exception (704) ~causes the object to be created and thrown

CONCEPT

you can write code that throws 1 of the standard Java exceptions, or an instance of a custom exception class that you have designed (704)

recover

• Error • Exceptional conditions • Applications cannot __ • Eg. Cannot read file due to hard-drive failure

programming bugs logic errors APIs

• Runtime Exception • Usually the result of ___, ____ and improper use of __. • Eg. Reading an array beyond its length

JVM Exceptions

− These are exceptions/errors that are exclusively or logically thrown by the JVM. Examples: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException.

Programmatic Exceptions

− These exceptions are thrown explicitly by the application or the API programmers. Examples: IllegalArgumentException, IllegalStateException.

List three constructors with parameters of File class

#1 File(File parent, String child) #2 File(String pathname) #3 File(String parent, String child) - Creates a new File instance from a parent abstract pathname and a child pathname string. File(String pathname) - Creates a new File instance by converting the given pathname string into an abstract pathname. File(String parent, String child) - Creates a new File instance from a parent pathname string and a child pathname string.

Three standard I/O streams

(1) System.in - standard input stream (2) System.out - standard output stream (3) System.err - standard error stream (output for error messages)

finally try exception

(IS OPTIONAL) • The ___ keyword is used to create a block of code that follows a __ block. • A - block of code always executes, whether or not an ___ has occurred. • Using a - block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. • Avoid placing code that can throw an exception in a finally block.

if there is no reason to reference the *FileOutputStream object*, these statements can be combined into 1 as follows: [code]

*DataOutputStream outputFile =* -->*new DataOutputStream(new* -->*FileOutputStream("MyInfo.dat"));* (713)

list the classes that inherit from the *IOException* class:

*EOFException* & *FileNotFoundException* (683) ~examples of classes that exception objects are created from

if the *file pointer* refers to a byte number that is beyond the end of the file, a(n) _____ is thrown when a read operation is performed

*EOFException* (721)

just below the *Throwable* class are the classes _____ & _____

*Error* & *Exception* (683)

open a binary file for input [code]

*FileInputStream fstream =* -->*new FileInputStream("MyInfo.dat");* *DataInputStream inputFile =* -->*new DataInputStream(fstream);* (715)

list the exceptions that are instances of classes that inherit from *Exception*

*IOException* & *RuntimeException* (683) ~also serve as superclasses

to write a *serialized object to a file*, use the _____ object

*ObjectOutputStream* output (725)

general format of *RandomAccessFile* class constructor [code]

*RandomAccessFile(String filename, String mode)* (719)

all of the classes in the *exception class hierarchy* inherit from the _____ class

*Throwable* class (683)

the _____ is an internal list of all the methods that are currently executing

*call stack* (699)

catch clause [code]

*catch (ExceptionType ParameterName)* (684) ~(name of exception class.....variable name)

_____ is the process of reconstructing a serialized object

*deserialization* (712)

_____ is the process of converting an object to a series of bytes and saving them to a file

*object serialization* (712)

*throws* [code]

*public void displayFile(String name) throws* *FileNotFoundException* (703) ~if there is more than 1 type of exception, you separate them with commas

_____ is a file that allows a program to read data from any location within the file, or write data to any location within the file

*random access file* (712)

the _____ method returns the deserialized object

*readObject* method (725) ~throws a number of different exceptions if an error occurs

a(n) _____ is a list of all the methods in the *call stack*

*stack trace* (699) ~it indicates the method that was executing when an exception occurred and all of the methods that were called in order to execute that method

*throw statement* [code]

*throw new Exception("Out of fuel");* (704) throw new ExceptionType(MsgString);

general format of a try statement with a finally clause [code]

*try {* -->*try block statements* *} catch (ExceptionType ParameterName) {* -->*catch block statements* *} finally {* -->*finally block statements* *}* (697)

general format of the try statement [code]

*try {* -->*try block statements* *} catch (ExceptionType ParameterName) {* -->*catch block statements* *}* (684)

general format of the *seek method* [code]

*void seek(long position)* (721)

The increment operator is:

++

User-defined Exceptions

- All exceptions must be a child of Throwable. -to write a checked exception, extend the Exception class. -to write a runtime exception, must extend the RuntimeException class. class MyException extends Exception { } -extend the predefined Exception class to create your own Exception.

Stream

- a sequence of data - two kinds of Streams = InPutStream, OutPutStream

OutputStream object's helper methods

- can be used to write to stream or to do other operations on the stream. - public void close() throws IOException{} -protected void finalize()throws IOException {} -public void write(int w)throws IOException{} -public void write(byte[] w)

Checked exceptions

- compile time exceptions. - A checked exception is an exception that occurs at the compile time. - cannot simply be ignored at the time of compilation, the programmer should take care of (handle) these exceptions. example: FileNotFoundException

java.io package

- contains nearly every class you might ever need to perform input and output (I/O) in Java - All these streams represent an input source and an output destination - The stream in the java.io package supports many data such as primitives, object, localized characters, etc.

FileInputStream

- is used for reading data from the files. - Objects can be created using the keyword new and there are several types of constructors available. InputStream f = new FileInputStream("C:/java/hello"); or File f = new File("C:/java/hello"); InputStream f = new FileInputStream(f);

FileOutputStream

- is used to create a file and write data into it. - The stream would create a file, if it doesn't already exist, before opening it for output. ex1: OutputStream f = new FileOutputStream("C:/java/hello") ex2: File f = new File("C:/java/hello"); OutputStream f = new FileOutputStream(f);

Creating Directories: 2 useful File utility methods

- mkdir( ) - mkdirs()

Character Streams

- perform input and output for 16-bit unicode - most frequently used classes are, FileReader and FileWriter. - Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

Byte Streams

- used to perform input and output of 8-bit bytes - most frequently used classes are, FileInputStream and FileOutputStream.

Unchecked exceptions

-Runtime Exceptions. - An unchecked exception is an exception that occurs at the time of execution. - programming bugs, such as logic errors or improper use of an API. - Runtime exceptions are ignored at the time of compilation. -example: ArrayIndexOutOfBoundsException

difference between throws and throw keywords

-Throws is used to postpone the handling of a checked exception - throw is used to invoke an exception explicitly.

*FileInputStream*

-class that allows you to *open a file* for reading binary data & establish a connection with it -it provides only the basic functionality for reading bytes from the file (715)

*DataInputStream*

-class that allows you to *read data* of any primitive type, or String objects, from a binary file -the class itself cannot directly access a file -it is used in conjunction with a *FileInputStream object* that has a connection to a file (715)

Typical File Tasks

-determining whether and where a path or file exits -opening a file for use by a program -writing new or revised data created by a program to a file -reading previously stored data into a program to display to a user, to be raised by a user, or to be used as information to perform a tad such as payroll -closing a file -deleting a file

NOTE

-do not confuse the *throw statement* with the *throws clause* -*throw statement*: causes an exception to be thrown -*throws clause*: informs the compiler that a method throws 1 or more exceptions (705)

The Finally Block

-follows a try block or a catch block. -always executes, irrespective of occurrence of an Exception.

important points to know about *RandomAccessFile modes*:

-if you open a file in *r mode* & the file does not exist, a *FileNotFoundException* is thrown -if you open a file in *r mode* & try to write to it, an *IOException* is thrown -if you open an existing file in *rw mode*, it will not be deleted. The file's existing contents will be preserved -if you open a file in *rw mode* & the file does not exist, it will be created (719)

important methods available in the Throwable class

-public String getMessage() -public Throwable getCause() -public String toString() -public void printStackTrace() -public StackTraceElement [] getStackTrace() -public Throwable fillInStackTrace()

char readChar() [DataInputStream method]

-reads a char value from the file and returns it -the character is expected to be stored as a two-byte Unicode character, as written by the DataOutputStream class's writeChar method (716)

String readUTF() [DataInputStream method]

-reads a string from the file and returns it as a String object -the string must have been written with the DataOutputStream class's writeUTF method (716)

*FileOutputStream* class

-this class allows you to *open a file* for writing binary data and establish a connection with it -it provides only basic functionality for writing bytes to the file (713)

*DataOutputStream*

-this class allows you to *write data* of any primitive type or String objects to a binary file -the class by itself cannot directly access a file -it is used with the *FileOutputStream object* that has a connection to a file (713)

Catching Exceptions

-using a combination of the try and catch keywords. -A try/catch block is placed around the code that might generate an exception.

FACT

-when the *DataInputStream* class's *readUTF* method reads from the file, it expects the first 2 bytes to contain the number of bytes that the string occupies -then it reads that many bytes and returns them to a String (717)

The terms temporary and permanent refer to ....

... volatility, not length of time.

you save text files containing Java source code using the file extension ______

.java

3 standard I/O streams

1) standard output. 2) standard input. 3) standard error.

to *open a binary file for input*, you can use the following classes including:

1. *FileInputStream* 2. *DataInputStream* (715)

to *write data to a binary file* you must create objects from which classes:

1. *FileOutputStream* 2. *DataOutputStream* (713)

How to deal with exceptions

1. Not handle at all 2. Handle it where it occurs 3. Handle at another point in the program

What are the two inherent types of exceptions?

1. Runtime exceptions: exceptions that OCCUR WITHIN THE JAVA RUNTIME SYSTEM. Things like arithmetic exceptions, pointer exceptions, and indexing exceptions. 2. Non-runtime exceptions: exceptions that occur in code outside of the Java runtime system. For example, exceptions that occur during Input/ouput.

if the code in a method can potentially throw a *checked exception*, then that method must meet 1 of the requirements including:

1. must handle the exception or 2. must have a *throws* clause listed in the method header (703)

Examples of exceptions

1. trying to divide by zero 2. array index out of bounds 3. specified file not found 4. requested IO operation could not be completed normally 5. attempting to follow a null reference 6. attempting to execute an operation that violates some security measure

What will the println statement in the following program segment display? int x = 5; System.out.println(x++);

5

Java keywords

50 words abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native short static strictfp super switch synchronized this throw throws transient try void volatile while

What will the println statement in the following program segment display? int x = 5; System.out.println(++x);

6

BufferedInputStream

A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods.

ByteArrayInputStream

A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream.

Closeable

A Closeable is a source or destination of data that can be closed.

FileInputStream

A FileInputStream obtains input bytes from a file in a file system.

FilterInputStream

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.

Flushable

A Flushable is a destination of data that can be flushed.

an indication from the operating system when it reaches the end of the stream

A Java program simply receives...

PrintStream

A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently.

PushbackInputStream

A PushbackInputStream adds functionality to another input stream, namely the ability to "push back" or "unread" one byte.

Readable

A Readable is a source of characters.

SequenceInputStream

A SequenceInputStream represents the logical concatenation of other input streams.

nonzero value

A _____, normally indicates that an error has occurred

SecurityException

A ________ occurs if the user does not have permission to write data to the file.

FileNotFoundException

A _________ occurs if the file does not exist and a new file cannot be created.

file or directory

A ___________'s path specifies its location on disk. The path includes some or all of the directories leading to the ___________.

How do you create a block of code?

A block of code is started with a { and ends with a }

InputStreamReader

A bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset.

LineNumberReader

A buffered character-input stream that keeps track of line numbers.

StringWriter

A character stream that collects its output in a string buffer, which can then be used to construct a string.

StringReader

A character stream whose source is a string.

PushbackReader

A character-stream reader that allows characters to be pushed back into the stream.

Cloneable

A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.

ClassLoader

A class loader is an object that is responsible for loading classes.

SecurityManager

A class that allows applications to implement a security policy.

Serializable

A class that implements ObjectOuput (such as ObjectOutputStream) declares this method and ensures that the object being output implements ______

Serializable

A class that implements _______ is tagged as being a ________ object.

Object Class

A class that is automatically inherited when extends is not written from another class. every object directly or indirectly extends from the Object class and inherits Object class's members

Abstract Class

A class that is not instantiated, but other classes extend it. Must be extended. Fundamentally, you can think of an abstract class as an interface with a partial implementation (with the caveat that a class can implement more than one interface, but can only derive from a single abstract class)

DataInputStream

A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way.

DataOutputStream

A data output stream lets an application write primitive Java data types to an output stream in a portable way.

ObjectStreamField

A description of a Serializable field from a Serializable class.

Flushable

A destination of data that can be flushed.

Character.UnicodeBlock

A family of character subsets representing the character blocks in the Unicode specification.

FileOutputStream

A file output stream is an output stream for writing data to a File or to a FileDescriptor.

FileFilter

A filter for abstract path-names.

FileFilter

A filter for abstract pathnames.

Stack Trace

A list of all the methods in the call stack. It indicates the method that was executing when an exception occurred and all of the methods that were called in order to execute that method.

What does it mean to "catch an exception"?

A method can catch an exception by providing an exception handler, a block of code (i.e. a catch block), that handles that exception. Performed via the "catch" keyword.

What does it mean to "specify all checked exceptions"? I.e., propagating all checked exception?

A method specifies that it can throw exceptions by using the "throws" clause in the method declaration. This is called PROPAGATING the exception.

Abstract Method

A method that appears in the superclass, but expects to be overridden in a subclass. -Has only a header and no body Header must end with a semicolon ;

How do you create a multiline comment

A multiline comment begins with /* and ends with */

StringBuilder

A mutable sequence of characters.

PipedInputStream

A piped input stream should be connected to a piped output stream; the piped input stream then provides whatever data bytes are written to the piped output stream.

PipedOutputStream

A piped output stream can be connected to a piped input stream to create a communications pipe.

CharSequence

A readable sequence of char values.

AutoCloseable

A resource that must be closed when it is no longer needed.

What is a runtime system?

A runtime system is software designed to support the execution of computer programs. Note: the runtime system and program are not the same thing! The runtime system contains implementations of basic low-level commands and may also implement higher-level commands. The runtime system may also perform type checking, debugging, and even code generation and optimization.

Exception Handler

A section of code that gracefully responds to exceptions when they are thrown

Thread

A sequence of execution in a program.

How do you create a single line comment

A single line comment beings with // and ends at the end of the line

Closeable

A source or destination of data that can be closed.

StringBuffer

A thread-safe, mutable sequence of characters.

multiple catch blocks

A try block can be followed by ________________

Exception can occur for many different reasons

A user has entered an invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications or the JVM has run out of memory.

What is a variable?

A variable is a named memory location. The contents of a variable can be changed during the execution of a program.

In all but rare cases, loops must contain within themselves:

A way to terminate

Name three methods of PrintWriter class

AFP: append(char c) - Appends the specified CHARACTER to this writer. format(String format, Object... args) - Writes a FORMATTED STRING to this writer using the specified format string and arguments. printf(String format, Object... args) - A CONVENIENCE method to write a FORMATTED string to this writer using the specified format string and arguments.

List the six main I/O classes in Java 7 API

Abbreviation: FFFBBP ----> File -FileWriter- FileReader - BufferedReader - BufferedWriter - PrintWriter

contains all directories

Absolute Path

Reader

Abstract class for reading character streams.

FilterReader

Abstract class for reading filtered character streams.

FilterWriter

Abstract class for writing filtered character streams.

Writer

Abstract class for writing to character streams.

PushbackInputStream

Adds functionality to another input stream, namely the ability to "push back" or "unread" one byte.

BufferedInputStream

Adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods.

PrintStream

Adds functionality to another output stream, namely the ability to print representations of various data values conveniently.

handle terminate detection handling

Advantage of using exception handling: It enables a method to throw an exception to its caller, enabling the caller to handle the exception. Without this capability, the called method itself must ___ the exception or ____ the program. Often the called method does not know what to do in case of error. This is typically the case for the library methods. The library method can detect the error, but only the caller knows what needs to be done when an error occurs. The key benefit of exception handling is separating the ___ of an error (done in a called method) from the ___ of an error (done in the calling method).

deserialized

After a serialized object has been written into a file, it can be read from the file and ________ to recreate the object in memory.

cast to the object's actual type

After an object has been read, its reference can be...

primitive-type

All ________ variables are serializable.

What keyword is used by a method to throw an exception?

All methods use the "throw" statement to throw an exception. if (size == 0) { throw new EmptyStackException(); }

A for loop normally performs which of these steps?

All of the above (initializes a control variable to a starting value, tests the control variable by comparing it to a maximum/minimum value and terminate when the variable reaches that value, & updates the control variable during each iteration)

Inheritance

Allows a new class to extend an existing class. The new class inherits the members of the class it extends and creates an "is a" relationship

Static

Allows main() to be called before an object of the class has been created. This is necessary becasue main() is called by the JVM before any objects are made.

ASCII

American Standard Code for Information Interchange; designed to represent English characters

InputStreamReader

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset.

ObjectInputStream

An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.

ObjectOutputStream

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream.

OutputStreamWriter

An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset.

ObjectOutputStream

An _________ will not output an object unless it is a Serializable object.

File

An abstract representation of file and directory pathnames.

0

An argument of ___ indicates successful program termination

StackTraceElement

An element in a stack trace, as returned by Throwable.getStackTrace().

What is an Exception in Java?

An event which disrupts the normal flow of the program. It is an object.

What is considered an appropriate exception handler?

An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. If the handler can handle the exception thrown, the handler is said to "catch" the exception object and thus prevents the error. When catching the exception object, the handler can inspect the object and look for information contained in the object.

What is an exception? Short for exceptional event.

An exception is an event that occurs during the execution of a program disrupts the normal flow of instructions during the execution of the program.

method

An exception may be thrown directly by using a throw statement in a try block, or by invoking a ____ that may throw an exception.

running time exception

An exception that can only occur when a program runs

Anonymous Inner Class

An inner class defined inside another class that has no name and must implement an interface or extend another class (extends or implements not written). Can only use final variables generic new classOrInterface{ method; } IntCalculator square = new IntCalculator()//obj imp intfc { public int calculate(int number) { return number* number }};

Functional interface

An interface with only one method. Lamba operators are used to create and object that implements the interface and overrides the abstract method. Example: InterfaceName object = x -> x*x where, parameter -> expression

Call Stack

An internal list of all the methods that are currently executing.

Each repetition of a loop is known as what?

An iteration

System.out

An object that encapsulates console output

Appendable

An object to which char sequences and values can be appended.

Exception

An object which is generated in memory as the result of an error of an unexpected event

Finally Block

An optional catch block that is one or more statements that are always executed after the try block has executed and after any catch blocks have executed if an exception was thrown. Executes regardless of whether an exception was thrown.

Void

An uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword that is the name of the class.

transient

Any class that is not Serializable must be declared _______ so it will be ignored during the serialization process

How have we obtained data in our projects?

Arrays and Scanner inputs

What are runtime exceptions?

Arthimetic exception,indexoutofbounds,nullpointer,numberformat

import java.nio.file.*; class A { public static void main ( String[] args) throws Exception { Path src = Paths.get( "C:\\a\\log1.txt"); Path des = Paths.get( "C:\\a\\log2.txt"); Files.copy(src, des); } } Where log2.txt does exist. The above code will give: a) compiler error b) runtime error c) compile and will copy the contents of log1.txt to log2.txt d) none of the above

B is correct. it will throw a FileAlreadyExistsException log2.txt already exists. It must not exist prior to copy.

if (w < h) { v = w * h w = 0 ]

Block starts at { and ends with } If w is less than h, both statements will be executed.

If you are using a block of statements, don't forget to enclose all of the statements in a set of:

Braces

BufferedReader reads _______ of data to file

BufferedReader reads CHUNKS of data to file

What class am I? Low-level FileWriter more efficient

BufferedWriter class

BufferedWriter makes low - level _____ more _____

BufferedWriter makes low - level FileWriter more EFFICIENT

BufferedWriter writes _______ of data to file

BufferedWriter writes CHUNKS of data to file

output and input data in its binary format—a char is two bytes, an int is four bytes, a double is eight bytes, etc.

Byte-based streams

What is bytecode and why is it important to Java's use for Internet programming?

Bytecode is a highly optimized set of instructions that is exectued by the Java Virtual Machine. Bytecode helps Java achieve portability and security.

import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths. get( URI.create( "file:///C://a//File.txt")); System. out. println(p1); } } Consider the above code running on Windows. The above code will give: a) compiler error b) runtime error c) compile and print C:\a\File.txt d) none of the above

C is correct.

ObjectInputValidation

Callback interface to allow validation of objects within a graph.

Println()

Can be used to display information

CATCH

Can have multiple ___ blocks Must specify exception types to be caught All exceptions caught by Exception class Sometimes called catch clause of exception handler Catch an exception only if you can handle it in a meaningful way

output and input data as a sequence of characters in which every character is two bytes—the number of bytes for a given value depends on the number of characters in that value.

Character-based streams

anticipated recover TRY/CATCH

Checked Exceptions • Should be __ • Application should __ • Checked Exceptions - MUST __ • Errors and runtime exceptions - do not need to try/catch • Eg. Open a file that does not exist

What is a CHECKED EXCEPTION?

Checked exceptions are exceptions that the Java compiler FORCES YOU TO HANDLE by either catching the exception, or re-throwing it. A checked exception is a type of exception that must be either: (1) caught, via "try" and "catch", or, (2) declared in the method in which it is thrown, via "throws". The failure to handle a checked exception results in a compiler error.

Make the distinction between checked/ unchecked exceptions and runtime/non-runtime exceptions.

Checked exceptions are simply exceptions that the Java compiler forces the developer to handle via try and catch blocks. Unchecked exceptions are the opposite of this. For example, the "RuntimeException" exception class is an unchecked exception in Java. Alternatively, the "Exception" exception class is a checked exception.

Object

Class Object is the root of the class hierarchy.

read from or written to a stream

Classes ObjectInputStream and ObjectOutputStream (package java.io). which respectively implement the ObjectInput and ObjectOutput interfaces, enable entire objects to be...

What does finally block has

Clean up code.

Source file

Compilatoin unit A text file with one or more classifications Java compiler requires that a source file use the .java filename extension. The code must reside inside a class. The name of the main class should match the name of the file that holds the program.

A loop that executes as long as a particular condition exists is called a:

Conditional loop

import java.io.Console; class A { public static void main(String[] args) { Console c = System. console(); char[] pw = c. readPassword( "Enter password: "); for(_____ : _____ ){ c._____ (_____ , _____ ); }}} Using a for-each loop complete the code to write out the password to the screen in boolean format.

Console c = System.console(); char[] pw = c. readPassword( "Enter password: "); for(char curChar: pw) { c.format("%b", curChar); } e.g. c:> Java A c:> Enter Password: hello c:> truetruetruetruetrue

import java.io.Console; class A { public static void main(String[] args) { Console c = System. console(); char[] pw = c. readPassword( "Enter password: "); for(_____ : _____ ){ c._____ (_____ , _____ ); }}} Using a for-each loop complete the codeto write out the password to the screen in string format.

Console c = System.console(); char[] pw = c. readPassword( "Enter password: "); for(char curChar: pw) { c.format("%s", curChar); } e.g. c:> Java A c:> Enter Password: hello c:> hello

Console contains methods to access the _____ _____

Console contains methods to access the PHYSICAL DEVICES i.e. keyboard/monitor

Console is useful to write _____ engines for _____ _____

Console is useful to write TEST engines for UNIT TESTING

Console makes it easy to accept input from _____ _____

Console makes it easy to accept input from COMMAND LINE

ObjectStreamConstants

Constants written into the Object Serialization Stream.

ByteArrayInputStream

Contains an internal buffer that contains bytes that may be read from the stream.

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.

FileReader

Convenience class for reading character files.

FileWriter

Convenience class for writing character files.

Loop example int count; for(count = 0; count < 5; count = count+1)

Count is the loop control variable Sets to zero in initalization Each iteration does the condtional test count < 5 If true, the loop continues increasing by 1 until it reaches 5.

A loop that repeats a specific number of times is known as a:

Counter-controlled loop

App steps

Create a IDE project Add code to generate the source file Compile the source file into a .class file Run the program

temporary

Data stored in variables and arrays is...

This is an item that separates other items.

Delimiter

Objects of classes that implement this interface enable a program to iterate through the contents of a directory.

DirectoryStream interface

var2 = var1 / 2;

Divides var1 by 2 then stores the result in var2. Could also do addition, subtraction, multiplication, and division.

TRY

Do these things that might throw an exception Other code okay too Stops when an exception is thrown

Serializable

Enabled by the class implementing the java.io.Serializable interface.

Three main principles of object oriented programming?

Encapsulation Polymorphism Inheritence

What is the first step of constructing an exception handler?

Enclosing the code that might throw an exception within a try block. try { // code } catch and finally blocks...

==

Equal to

the exceptions that inherit from _____ are thrown when a critical error occurs, such as running out of memory

Error (703)

call stack trace

Error message (when not handling). Indicates where exception occured. Can get this information by calling getMessage on the exception class. printStackTrace prints the call stack trace.

Runtime

Every Java application has a single instance of this class that allows the application to interface with the environment in which the application is running.

root directory

Every file or directory on a particular disk drive has the same _________ in its path

end-of-file marker

Every operating system provides a mechanism to determine the end of a file, such as an _________ or a count of the total bytes in the file that is recorded in a system-maintained administrative data structure.

error-handling read modify

Exception Handling separates ___ code from normal programming tasks, making programs easier to ___ and ___

checked unchecked

Exception can be either __ or __

ObjectInput

Extends the DataInput interface to include the reading of objects.

ObjectOutput

Extends the DataOutput interface to include writing of objects.

List seven methods of PrintWriter

FPPPWFC format() printf() println() print() write() flush() close()

T/F - It is not necessary to initialize accumulator variables.

False

T/F - One limitation of the for loop is that only one variable may be initialized in the initialization expression.

False

T/F - The do-while loop is a pretest loop.

False

T/F - The for loop is a posttest loop.

False

T/F - To calculate the total number of iterations of a nested loop, add the number of iterations of all the loops.

False

TRUE/FALSE: In a for statement, the control variable can only be incremented.

False

TRUE/FALSE: In the for loop, the control variable cannot be initialized to a constant value and tested against a constant value.

False

TRUE/FALSE: The do-while loop is a pre-test loop.

False

TRUE/FALSE: When the break statement is encountered in a loop, all the statements in the body of the loop that appear after it are ignored, and the loop prepares for the next iteration.

False

True of False: The Java runtime system ensures that non-runtime exceptions are caught or specified.

False. It is actually the COMPILER that ensures non-runtime exceptions are caught or specified.

BufferedWriter is less efficient than FileWriter true or false

False. BufferedWriter is more efficient FileWriter as FileWriter writes single chars at a time whereas BufferedWriter writes chunks of data to file

In File class close() method guarantees the last data gets written to disk. True or false

False. close() frees up expensive operating system resources

To open a file for reading, you use the following classes.

File and Scanner

What class am I? I make a new empty file but not the data. I search for files and delete files

File class

File class makes a new _____file but not the _____ . It searches for _____ and _____ them.

File class makes a new EMPTY file but not the DATA. It searches for FILES and DELETES them

Which of the following will open a file named MyFile.txt and allow you to read data from it?

File file = new File("MyFile.txt"); Scanner inputFile = new Scanner(file);

File makes a new _____ file but not the data - ______ for files and ________ files

File makes a new EMPTY file but NOT the DATA - SEARCHES for files - DELETES files

What class am I? I read characters (single or whole) stream of chars from a file.

FileReader class

FileReader class _____ characters ( _____ or whole) _____ of chars from a file.

FileReader class READ characters (SINGLE or whole) STREAM of chars from a file.

FileReader reads _______ chars from a _____at a time

FileReader reads SINGLE chars from a FILE at a time

What class am I? write characters (single or whole) stream of chars to a file.

FileWriter class

FileWriter class _____ characters (single or _____ ) stream of _____ to a file.

FileWriter class WRITES characters (single or WHOLE) stream of CHARS to a file.

Which of the following will open a file named MyFile.txt and allow you to append data to its existing contents?

FileWriter fwriter = new FileWriter("MyFile.txt", true); PrintWriter outFile = new PrintWriter(fwriter);

FileWriter writes single _________ at a time to file

FileWriter writes single chars at a time to file

For long-term retention of data

Files

Provides static methods for common file and directory manipulations, such as copying files; creating and deleting files and directories; getting information about files and directories; reading the contents of files; getting objects that allow you to manipulate the contents of files and directories; and more

Files class

text files

Files created using character-based streams are referred to as...

close

Formatter method _____ closes the file

format

Formatter method ______ works like System.out.printf

specified stream

Formatter outputs formatted Strings to the...

occurs if the Formatter is closed when you attempt to output.

FormatterClosedException

getMessage() toString() printStackTrace

Getting Information From Exceptions ____; Returns the message that describes this exception object ____; Returns the concatenation of 3 strings: (1) The full name of the exception class; (2) " : " and (3) the getMessage() method _____ Prints the Throwable object and its call stack trace information on the console

Reversed Is A case

GradedActivity activity = new GradedActivity(); Final exam = activity; //ERROR but GradedActivity activity = new GradedActivity(); Final exam = (FinalExam) activity; //will compile but will crash at runtime execution

>

Greater than

Java platform

Has the java virtual machine and the java application programming interface JVM - bae for the java platform

what are checked exception?

IO,SQL,Filenotfound

IllegalStateException

If a Scanner is closed before data is input, an _________ occurs

The Throws/Throw Keywords

If a method does not handle a checked exception, the method must declare it using the "throws" keyword. - The throws keyword appears at the end of a method's signature. -You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the "throw" keyword.

the file is in the directory from which the program was executed

If a path is not specified, the JVM assumes that...

truncated

If an existing file is opened, its contents are...

the operating sys-tem normally will close the file when program execution terminates

If method close is not called explicitly...

When is a catch block, which proceeds a try block, invoked?

If the exception handler is the first on the call stack and its argument's exception type matches the exception that is thrown. catch (ExceptionType1 name) { ... } The above exception handler is invoked if the exception thrown is of type ExceptionType1 and if the handler is the first one on the call stack.

be created

If the file does not exist, it will...

Default exception handler

If your code does not handle an exception when it is thrown, this handles and prints an error message and crashes the program.

Iterable<T>

Implementing this interface allows an object to be the target of the "foreach" statement.

Throwing exceptions

In doing so, we essentially define our own exceptions For example, if you do public static void main(String[] args) throws OutOfRangeException { code that includes instantiating an OutOfRangeException object and later a if (whatever you want to check) { throw excepObj;} } you essentially make an exception that is not part of the standard library, but it is created from the outOfRangeException class. If there's no try-catch, the error will terminate the program.

What is the call stack?

In regards to exception handling, the call stack is the set of possible "somethings" to handle the exception. Specifically, it is the ordered list of methods that had been called to get to the method where the error occurred.

++

Increases operand by 1 count++; instead of count + 1

Indentation practices

Indent one level after each opening brace and move out one level after closing a brace.

____________ is the process of inspecting data given to the program by the user and determining if it is valid.

Input validation

FilenameFilter

Instances of classes that implement this interface are used to filter filenames.

Class<T>

Instances of the class Class represent classes and interfaces in a running Java application.

FileDescriptor

Instances of the file descriptor class serve as an opaque handle to the underlying machine-specific structure representing an open file, an open socket, or another source or sink of bytes.

Character.Subset

Instances of this class represent particular subsets of the Unicode character set.

RandomAccessFile

Instances of this class support both reading and writing to a random access file.

tagging interface

Interface Serializable is a...

Thread.UncaughtExceptionHandler

Interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.

PipedOutputStream

Is to be connected to a piped input stream to create a communications pipe.

Console I/O

Is used mostly for simple utility programs ans server side code

print()

Is used to display the string on the same line

Deployment technology

JDK software provides standard mechanisms like Java web start software and Java plug in software to deploy your apps to end users.

Java : Exceptions & Advanced File I/O (10) (681-729)

Java : Exceptions & Advanced File I/O (10) (681-729)

Integration libraries

Java IDL API, JDBC, API, Java Naming and Directory Interface API, Java RMI, Java Remote Method, etc. enable database access and manipulation of remote objects.

Where do java programs begin execution?

Java programs begin execution at main()

Main () method

Java subroutine is a method. It's the line the program is executing. All java apps begin execution by calling main().

stream of bytes

Java views each file as a sequential...

User interface toolkits

JavaFX, Swing, Java 2D toolkits allow you to create Graphical user interfaces

ClassValue<T>

Lazily associate a computed value with (potentially) every type.

<

Less than

<=

Less than or equal to

This is a control structure that causes a statement or group of statements to repeat.

Loop

This variable controls the number of times that the loop iterates.

Loop control variable

List six methods of Files class located in java.nio.file.Files

MCNEDD - ALL Static methods - path move(Path scr, Path des, CopyOption... options) ----> path copy(Path scr, Path des, CopyOption... options) ----> boolean notExists(Path path, LinkOption... options) ----> boolean exists(Path path, LinkOption... options) ----> void delete(Path path) ----> boolean deleteIfExists(Path path)

List 8 methods in File class

MEDIICLR - mkdir() - exists() - delete() - isDirectory() - isFile() - createNewFile() - list() - renameTo()

ClassNotFoundException

Method readObject throws a _________ if the class for the object being read cannot be located.

EOFException

Method readObject throws an ________ if an attempt is made to read beyond the end of the file.

Console

Methods to access the character-based console device, if any, associated with the current Java virtual machine.

Overloading

Methods which have the same name but different signatures or parameter lists. showValue(int arg) vs showValue(String arg) Both can be called.

Overriding

Methods which have the same signature. The subclass version will be the only one able to be called showValue(int arg) in super showValue(in arg) in subclass only subby can be called. super.call is required to reach the overridden superclass method Protect from overriding by declaring: final showValue in ht superclass.

List 4 methods of BufferedWriter

NWFC newLine() write() flush() close()

Identifiers

Name given to user defined items like methods and variables. Can start with any letter, underscore, or a dollar sign. Then a letter, digit, dollar sign, or underscore. Underscore is used to make it easier to read Can't start with a digit or java keywords Name should reflect the meaning or usage of the item

Does checked exceptions propagate the calling chain

No

occurs if the data being read by a Scanner method is in the wrong format or if there is no more data to input.

NoSuchElementException

!=

Not equal

Exception Hierarchy

Object Throwable Exception RuntimeException IllegalArgumentException NumberFormatException

ObjectInput

ObjectInput extends the DataInput interface to include the reading of objects.

readObject

ObjectInput interface method ________ reads and returns a reference to an Object from an InputStream

reads an Object from a file.

ObjectInputStream method readObject

ObjectOutput

ObjectOutput extends the DataOutput interface to include writing of objects.

takes an Object as an argument and writes its information to an OutputStream.

ObjectOutput interface method writeObject

ObjectOutputStreams and ObjectInputStreams

Objects of classes that implement interface Serializable can be serialized and deserialized with _______ and _______.

Package

Objects that contain version information about the implementation and specification of a Java package.

FileInputStream

Obtains input bytes from a file in a file system.

Externalizable

Only the identity of the class of an Externalizable instance is written in the serialization stream and it is the responsibility of the class to save and restore the contents of its instances.

Externalizable

Only the identity of the class of an of this instance is written in the serialization stream and it is the responsibility of the class to save and restore the contents of its instances.

--

Operand decreases by 1

instanceOf operator

Operator in Java that can be used to determine whether an object is an instance of a particular class.

____________________ is an abstract class that contains methods for performing output.

OutputStream

Objects of classes that implement this interface represent the location of a file or directory. Path objects do not open files or provide any file-processing capabilities.

Path interface

Provides static methods used to get a Path object representing a file or directory location.

Paths class

Data maintained in files that exists beyond the duration of program execution

Persistent Data

PipedReader

Piped character-input streams.

PipedWriter

Piped character-output streams.

Interface Reference Varaible

Polymorphic variable that can reference any object that implements that interface, regardless of its class type. Limitation When an interface variable is used, it can only call methods that are specified in the interface. Calling a not interface variable will result in a compilation error.

This type of loop will always be executed at least once.

Post-test loop

Stystem

Predefined class that provides access to the system

Private

Prevents a member from being used by code defined outside of its class

This class allows you to use the print and println methods to write data to a file.

PrintWriter

To open a file for writing, you use the following class.

PrintWriter

What class am I? Prints formatted representations of objects to a text-output stream.

PrintWriter class

PrintWriter class prints _____ representations of _____ to a text output stream

PrintWriter class prints FORMATTED representations of OBJECTS to a text output stream

PrintWriter contains extra ______ for _________. Makes it more _____ and ________ than Writer

PrintWriter contains extra METHODS for FORMATTING. Makes it more FLEXIBLE and POWERFUL than Writer

PrintWriter

Prints formatted representations of objects to a text-output stream.

ObjectInputStream.GetField

Provide access to the persistent fields read from the input stream.

Development tools

Provide everything you need. Main tools are javac compiler and javadoc documentation tool

ObjectOutputStream.PutField

Provide programmatic access to the persistent fields to be written to ObjectOutput.

Application programming interface

Provides core functionality of the Java programming language. Offers a wide array of ready to use classes. Is very large.

Volatile Storage

RAM; lost when a computer loses power

What does RAM stand for?

Random Access Memory

to create & work with *random access files* in Java, you must use the _____ class, in the *java.io package*

RandomAccessFile class (719 , 721) ~allows for reading, writing, and moving the file pointer

BufferedReader

Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

is "relative" to another directory—for example, a path relative to the directory in which the application began executing.

Relative Path

ThreadGroup

Represents a set of threads.

ProcessBuilder.Redirect

Represents a source of subprocess input or a destination of subprocess output.

SequenceInputStream

Represents the logical concatenation of other input streams.

This is a sum of numbers that accumulates with each iteration of a loop.

Running total

_____ serves as a superclass for exceptions that result from programming errors, such as an out-of-bounds array subscript

RuntimeException (703)

unchecked checked

RuntimeException, Error, and their subclasses are known as ___ exceptions. All other exceptions are known as ___ exceptions, meaning that the compiler forces the programmer to check and deal with them in a try-catch block or declare it in the method header.

Standard Streams

STDIN, STDOUT and STDERR.

This class allows you to read a line from a file.

Scanner

determines whether the end-of-file key combination has been entered

Scanner method hasNext

hard disks, flash drives, DVDs and more

Secondary Storage Devices

This is a value that signals when the end of a list of values has been reached.

Sentinel

Serializable

Serializability of a class is enabled by the class implementing the java.io.Serializable interface.

ObjectStreamClass

Serialization's descriptor for classes.

is represented as a sequence of bytes that includes the object's data and its type information

Serialized Objects

Before entering a loop to compute a running total, the program should first do this.

Set the accumulator where the total will be kept to an initial value, usually zero

PipedInputStream

Should be connected to a piped output stream; then provides whatever data bytes are written to the piped output stream.

How do we specify the Exceptions thrown by a Method?

Sometimes we want a class higher up the call stack to handle the thrown exception so as to "cover all the bases". Thus, you can implement the exception handler in a client class of our method. Example: the Main class of ImplExample implements the exception handlers for the load() and unLoad() methods of the domain Truck classes. The load() and unLoad() methods throw the exceptions in the domain classes and even lower down the call stack in the TruckImpl class.

Interfaces

Specify the behavior for a class Contains only abstract methods. Implemented by other classes public interface InterfaceName { int field1 =1; int field2 = 2; void display(); default void show; { print "hello" } } no access specifier for the method, its implicitly public. Field declarations are final and static and must be used. Multiples of these can be implemented. default methods can have a body. not required to be overridden.

Single line comment

Starts with // and ends at the end of hte line Usually programmers use this for brief line by line descriptions

In main() there is only one parameter

String args[] Declars a parameter named args This is an array of objects of type string

string

String objects store sequences of characters

Purpose #1 of exception handling - Surviving errors

Surviving errors that would normally take a program out. For example: trying to open a file that doesn't exist. You can catch the exception, print an error message, and continue.

in, out and err are public static object reference variables of the

System class

import java.io.Console; class A { public static void main(String[] args) { Console c = System. console();char[] pw = c.readPassword("Enter password: "); _____ } } Consider the user entering "Hello". fill-in the code to output what the user entered to the screen.

System.out.println(pw); Simply prints the char array to the screen.

Throws try/catch

TWO WAYS TO DEAL WITH EXCEPTIONS 1. Add a '___' declaration 2. Surround the code with a '___' block

DataInput

The DataInput interface provides for reading bytes from a binary stream and reconstructing from them data in any of the Java primitive types.

DataOutput

The DataOutput interface provides for converting data from any of the Java primitive types to a series of bytes and writing these bytes to a binary stream.

Float

The Float class wraps a value of primitive type float in an object.

InPutStream

The InputStream is used to read data from a source.

OutPutStream

The OutputStream is used for writing data to a destination.

Process

The ProcessBuilder.start() and Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it.

Runnable

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.

Short

The Short class wraps a value of primitive type short in an object.

StreamTokenizer

The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time.

Throwable extending

The ____ class is the root of exception classes. All Java exception classes inherit directly or indirectly from Throwable. You can create your own exception classes by ____ Exception or a subclass of Exception

Multi-Catch

The ability to catch multiple types of exceptions with a single catch clause. Example: Catch (NumberformatException | IOException e)

Polymorphism

The ability to take many forms A reference variable is of this type because it can reference objects of different types as long as those types are subclasses of its type. -Can only be used to call methods in that the variable knows within its own class. -A superclass reference variable can reference object of a subclass

Number

The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.

Public keyword

The access modifier, determines how other parts of the program can access the members of teh class. Public mean the member can be accessed by code outside the class in which it is declared.

var1 = 1024; //

The assignment operator is the equal sign. It copies the value on its right side into the variable on its left

StrictMath

The class StrictMath contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.

BufferedOutputStream

The class implements a buffered output stream.

StreamTokenizer

The class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time.

try block, catch block

The code which is prone to exceptions is placed in the _____ Exception occurred is handled by _______ associated with it. Every try block should be immediately followed either by a catch block or finally block.

path

The constructor with one String argument receives the name of the file, including its ...

system errors exceptions runtime exceptions

The exception classes can be classified into three major types

Superclass

The general class. Private members of this class cannot be accessed by the subclass and are technically not inherited. Super calls must be made in order to access these.

IOException

The input / output

DataOutput

The interface provides for converting data from any of the Java primitive types to a series of bytes and writing these bytes to a binary stream.

DataInput

The interface provides for reading bytes from a binary stream and reconstructing from them data in any of the Java primitive types.

Parameters

The main() is the method called when a Java pp begins. Any information you need to pass a method is received by variables specified within the parentheses following the name of the method. These are called parameters. if there are no paramenters, include empty parentheses.

System.out.println("var1 contains " + var1) ;

The plus sign causes the value of var2 to be displayed after the string that proceeds it.

Binding

The process of matching a method call with the correct method definition. Determined at RUNTIME It is the object's type, not the reference type, which determines what method will be called in the case of an overridden method.

java.lang.Throwable

The root class for exceptions

In the event of an exception, what does the runtime system need to find in order to prevent itself from terminating?

The runtime system needs to find a method in the call stack that contains a block of code that can handle the exception. This block of code is known as an EXCEPTION HANDLER. If it cannot find a method with an exception handler, the runtime system--and, consequently, the program--terminates.

After a method throws an exception, what happens?

The runtime system tries to find something to handle the exception. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred.

Subclass

The specialized class that inherits fields and methods from the superclass without any of them having to be rewritten.

Throwable

The superclass of all errors and exceptions in the Java language.

File Navigation and I/O

There are several other classes that we would be going through to get to know the basics of File Navigation and I/O. File Class FileReader Class FileWriter Class

Protected members

These members may be directly accessed by methods of the same class or methods of the subclass or same package. Not quite private because the members can be accessed outside the package but not quite public because access is restricted to methods in the same package, subclass, classes etc.

InputStream

This abstract class is the superclass of all classes representing an input stream of bytes.

OutputStream

This abstract class is the superclass of all classes representing an output stream of bytes.

Math

This class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.

System

This class contains several useful class fields and methods.

StringBufferInputStream Deprecated

This class does not properly convert characters into bytes.

InheritableThreadLocal<T>

This class extends ThreadLocal to provide inheritance of values from parent thread to child thread: when a child thread is created, the child receives initial values for all inheritable thread-local variables for which the parent has values.

CharArrayReader

This class implements a character buffer that can be used as a character-input stream.

CharArrayWriter

This class implements a character buffer that can be used as an Writer.

ByteArrayOutputStream

This class implements an output stream in which the data is written into a byte array.

LineNumberInputStream Deprecated

This class incorrectly assumes that bytes adequately represent characters.

SerializablePermission

This class is for Serializable permissions.

RuntimePermission

This class is for runtime permissions.

Compiler

This class is provided to support Java-to-native-code compilers and related services.

FilterOutputStream

This class is the superclass of all classes that filter output streams.

ProcessBuilder

This class is used to create operating system processes.

ThreadLocal<T>

This class provides thread-local variables.

FilePermission

This class represents access to a file or directory.

String

This class represents character strings.

Byte

This class wraps a value of primitive type byte in an object.

Boolean

This class wraps a value of the primitive type boolean in an object.

Character

This class wraps a value of the primitive type char in an object.

Double

This class wraps a value of the primitive type double in an object.

Integer

This class wraps a value of the primitive type int in an object.

Long

This class wraps a value of the primitive type long in an object.

Superclass Constructor

This constructor always executes before the subclass constructor -The super statements calls the superclass constructor and can only be written in subclass constructor -Must be the first statement in the subclass constructor -If subclass constructor does not explicitly call the superclass constructor Java will call the default constructor or no args version -If a superclass does not have a default constructor and does not have a no=arg constructor, the class that inherits from it must call one of the constructors that the superclass does have.

int var1; // this declares a variable

This declares a variable called var2 of type interger

Comparable<T>

This interface imposes a total ordering on the objects of each class that implements it.

Enum<E extends Enum<E>>

This is the common base class of all Java language enumeration types.

Standard Streams : Standard Input

This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as System.in.

Standard Streams : Standard Output

This is used to output the data produced by the user's program and usually a computer screen is used for standard output stream and represented as System.out.

Standard Streams : Standard Error

This is used to output the error data produced by the user's program and usually a computer screen is used for standard error stream and represented as System.err.

Purpose #2 of exception handling - Escaping a sinking ship; creating our own exception

Throw your/define your own exception (class). This makes our exception distinguishable from other exceptions. For example: writing a parser, a program which walks through a computer program, and actually figures out what it all means so you can go ahead and compile it. In a situation where a computer program is incomplete, we would like to be able to throw an exception from our parser so we can just pile our way out of loops, up many levels up the stack, all at once.

What is "throwing an exception"?

Throwing an exception is when an exception object is created, by the method where the error occurred within, and is handed to the runtime system.

public void myMethod() throws IOException public void myMethod() throws Exception1, Exception2, ..., ExceptionN

To declare an exception in a method, use the throws keyword in the method header, as in this example: _____ The throws keyword indicates that myMethod might throw an IOException. If the method might throw multiple exceptions, add a list of the exceptions, separated by commas, after throws: _____

object serialization

To read an entire object from or write an entire object to a file, Java provides...

T/F - A variable may be defined in the initialization expression of the for loop.

True

T/F - In a nested loop, the inner loop goes through all of its iterations for every iteration of the outer loop.

True

T/F - The while loop is a pretest loop.

True

TRUE/FALSE: A file must always be opened before using it and closed when the program is finished using it.

True

TRUE/FALSE: Java provides a set of simple unary operators designed just for incrementing and decrementing variables.

True

TRUE/FALSE: The do-while loop must be terminated with a semicolon.

True

TRUE/FALSE: The while loop has two important parts: (1) a boolean expression that is tested for a true or false value, and (2) a statement or block of statements that is repeated as long as the expression is true.

True

TRUE/FALSE: When the continue statement is encountered in a loop, all the statements in the body of the loop that appear after it are ignored, and the loop prepares for the next iteration.

True

TRUE/FALSE: When you open a file with the PrintWriter class, the class can potentially throw an IOException.

True

TRUE/FALSE: When you pass the name of a file to the PrintWriter constructor, and the file already exists, it will be erased and a new empty file with the same name will be created.

True

TRUE/FALSE: You can use the PrintWriter class to open a file for writing and write data to it.

True

True or False: The Java runtime system requires that a method must either: (1) catch or (2) specify all checked exceptions that can be thrown by that method.

True

In File class close() method frees up expensive operating system resources

True.

True or False: Java requires ONLY that a program handle checked exceptions.

True. Handling runtime exceptions is not enforced by the compiler. Only checked exceptions.

True or False: A method does not have to catch or specify runtime exceptions.

True. However, it can if it wants to.

Compilers less than Java 7 uses instance methods on File to create files and directories. True or false

True. e.g. File f = new File("C:\\a\\b\\Log.txt");

Fractional components

Two floating point types Float and double for single and double precision values Double is used most often

Uncaught exception

Uncaught exception. When an exception is not caught it is passed to the previous method called in the call stack until it is handles or reaches the main method and is handled with the default exception handler.

Unicode

Universal Character Encoding; designed to represent characters from all languages around the world

Handling when thrown

Use try-catch

throws

Used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.

This type of loop allows the user to decide the number of iterations.

User controlled loop

After comments is class

Uses keyword class to declasre a new class is being identified. Begins with { and ends with } In between the braces are members of the class.

List 3 methods of FileWriter

WFC write() flush() close()

value is too small Continue after the catch block

What is the output of the following code? public class Test { public static void main(String[] args) { try { int value = 30; if (value < 40) throw new Exception("value is too small"); } catch (Exception ex) { System.out.println(ex.getMessage()); } System.out.println("Continue after the catch block"); } }

exception try catch

When an exception is thrown, the normal execution flow is interrupted. As the name suggests, to "throw an exception" is to pass the ____ from one place to another. The statement for invoking the method is contained in a ___ block and a ____ block

How do methods handle exceptions?

When an exception occurs within a method, the method creates an EXCEPTION OBJECT and hands it off to the runtime system. The exception object contains information about the error, including its type and the state of the program when the error occurred.

what is wrapping-chaining with an example from classes File FileWriter and PrintWriter in java.io?

Wrapping-training class is where one object is passed as a parameter to another. In the context of Java I/O e.g. File f = new File("C:\\a\\myFile.txt"); FileWriter fw = new FileWriter(f); PrintWriter pw = new PrintWriter(fw); pw.println("c"); where FileWriter is wrapped inside PrintWriter

try { }catch(ExceptionName e) { }

Write a try/catch block statement

BufferedWriter

Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

What is the optional "final" step of setting up an exception handler?

Writing the "finally" block, which is a perfect spot for cleanup. Use the finally block to close files or release other system resources. The runtime system always executes code within the finally block regardless of what happens within the try block.

Comments

You can enter comments if you'd like. Usually it explains the what the program does. There are three styles of comments. Multiline begin with /* and end in */. Compiler ignores whatever is in between those.

Loop

You can repeatedly execute a sequence of code by creating a loop. There are various loop constructs.

File object

You use _________ to create directories, to list down files available in a directory.

Exceptions program external circumstances

__ are represented in the Exception class, which describes errors caused by your ___ and by __. These errors can be caught and handled by your program

System errors internal system errors terminate

___ are thrown by the JVM and are represented in the Error class. The Error class describes ____ , though such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to ___ the program gracefully

Exceptions

___ are thrown from a method. The caller of the method can catch and handle the exception

Runtime exceptions programming errors

____ are represented in the RuntimeException class, which describes ___ , such as bad casting, accessing an out-of-bounds array, and numeric errors.

When does Exceptions in Java arises in code sequence? a) Run Time b) Compilation Time c) Can Occur Any Time d) None of the mentioned

a

Which of these class is related to all the exceptions that cannot be caught? a) Error b) Exception c) RuntimeExecption d) All of the mentioned

a

Which of these handles the exception when no catch is used? a) Default handler b) finally c) throw handler d) Java run time system

a

Which of these keywords must be used to monitor for exceptions? a) try b) finally c) throw d) catch

a

Which of these operator is used to generate an instance of an exception than can be thrown by using throw? a) new b) malloc c) alloc d) thrown

a

a *file* that contains *binary data* is known as _____

a *binary file* (713)

A directory

a File which can contain a list of other files and directories.

FACT

a catch clause that uses a parameter variable of the Exception type is capable of catching any exceptions that inherits from the Exception class (690)

System

a class predefined by java

computer file

a collection of data stored on a nonvolatile device

paths

a complete list of the disk drive plus the hierarchy of directories in which a file resides

Files: a) contains only static methods b) contains static and non=static methods

a correct

Which of the below can be created using "new": a) File b) Path c)Paths d) Files:

a correct. Path is an interface. Files and Paths are final classes. This class consists exclusively of static methods that operate on files, directories, or other types of files.

File a = new File("c:\\a"); File b = new File("c:\\a\\b"); File f = new File(a,b,"f.txt"); System. out. println( f.createNewFile()); System. out. println( f.exists());The folders exist and the file already exists. The above code will give: a) compiler error b) runtime error c) Compile and Print "false true" d) None of the above

a correct. Remember File constructor can take (File, String) (String) (String,String) params ---> new File(a,b,"f.txt"); gives compiler error

public static void main(String[] args) throws Exception { File i = new File("C:\\a\\b\\"); System.out.println( i.createdirectory()); } The above code will give: a) compiler error b) runtime error c) compile and print true d) none of the above

a correct. createdirectory() is not a method within the File class. To create a new directory you call the method mkdir() or mkdirs() for the creation of subdirectories

public static void main(String[] args) throws Exception { File i = new File("C:\\a\\b\\m.txt"); System. out. println( i.renameTo("C:\\a\\b\\a.txt")); } The above code will give: a) compiler error b) runtime error c) compile and rename m.txt to a.txt d) none of the above

a correct. i.renameTo() doesn't take string parameter. Solution: wrap the new file name in a File object i.e. i.renameTo(new File("C:\\a\\b\\a.txt")); Note: you can also change folder the same way.

public static void main(String[] args) throws Exception { File i = new File("C:\\a\\b\\"); System. out. println(i.del());} Assume the above folders exist. The above code will give: a) compiler error b) runtime error c) compile and delete b folder and return true d) none of the above

a correct. it will give a compiler error as the del() method does not exist in File. Replace this with i.delete() and it would work.

import java.io.Console; class A { public static void main(String[] args) { Console c = System. console(); char[] n = c.readLine("%c", "Enter Name: "); System. out. println("Welcome "+n); } } The above code will give: a) compiler error b) runtime error c) compile and echo whatever you entered to the screen d) none of the above

a correct. readLine("%c", "Enter Name: "); returns a String var. you cannot store variable as a char variable. ----> Compiler error. Solution: String n = c.readLine("%s", "Enter Name: "); or String n = c.readLine("Enter Name: ");

import java.io.Console; class A { public static void main(String[] args) { Console c = System. console(); char n = c.readPassword("%c", "Enter password: "); } } The above code will give: a) compiler error b) runtime error c) compile and store user input to char n d) none of the above

a correct. readPassword() returns char array ----> you cannot store (char[]) and read in a variable (char) ----> compiler error. Solution: char[] n = c.readPassword(

Paths: a) creates Paths objects that contain static methods b) creates Paths objects that contain non-static methods

a correct. static methods: return type: static Path ---- methods: get(String first, String... more) - Converts a path string, or a sequence of strings that when joined form a path string, to a Path. return type: static Path ----- Method: get(URI uri) - Converts the given URI to a Path object.

Why is opening a file important?

a file might be written to disk as a "scratchpad" for use by a program and then deleted at the end of the process to free up disk space

binary file

a file that contains raw binary data (712)

The java compiler creates

a file that contains the bytecode versoin of the program. Bytecode must be executed by teh Java virtual machine.

Code block

a grouping of two or more statements Enclosed in curly braces Becomes a logical unit that can be used in any place single statement can. Link statement together for clarity and efficiency

import java.io.BufferedReader; import java.io.File; import java.io.FileReader; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); System. out. println( br.readLine()); br.flush(); br.close();} } considering hello world is in file myFile.txt (where "hello" is on the first line and "world" on the second) The above code will give: a) compiler error b) runtime error c) compile and print "hello" d) none of the above

a is correct. BufferedReader class does not have a flush() method. If the flush method was removed then it would print "hello" to the screen. Note: flush() is located in BufferedWriter.

import java.io.BufferedReader; import java.io.File; import java.io.FileReader; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); BufferedReader br = new BufferedReader(f); System. out. println( br.readLine()); br.close();} } considering hello world is in file myFile.txt (where "hello" is on the first line and "world" on the second) The above code will give: a) compiler error b) runtime error c) compile and print "hello" d) none of the above

a is correct. File object f needs to be wrapped in FileReader fr object which needs to be wrapped in BufferedReader br object in order to compile i.e. File f = new File("C:\\a\\ myFile.txt"); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr);

import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths.get( "C:\\a\\b\\File.txt"); System. out. println(p1); } } File location does not exist physically in memory. The above code will give: a) compiler error b) runtime error c) compile and print "C:\\a\\b\\File.txt" d) none of the above

a is correct. the folders and subfolders do not need to exist physically in order for this to combine.

examples of things stored in text files

a payroll file or programmer application files that store software instructions

FACT

a try statement can have several catch clauses in order to handle different types of exceptions (692) ~the program does not use the exception handlers to recover from any of the errors ~regardless of whether the file is not found or a nonnumeric item is encountered in the file, this program still halts

Java lets you assign a file to a(n) ____ object so that screen output and file output work in exactly the same manner. a. Stream b. Input c. Output d. File

a. Stream

In random access files, records can be retrieved in any order. a. True b. False

a. True

Java's Path class is used to create objects that contain information about files and directories, while the Files class performs operations on files and directories. a. True b. False

a. True

When you use the BufferedReader class, you must import the java.io package into your program. a. True b. False

a. True

You can store data in variables within a program, but this type of storage is temporary. a. True b. False

a. True

After you create a FileSystem object, you can define a Path using the ____ method with it. a. getPath() b. createPath() c. setPath() d. getDefault()

a. getPath()

The true benefit of using a(n) ____ file is the ability to retrieve a specific record from a file directly, without reading through other records to locate the desired one. a. random access b. text c. open d. input

a. random access

Placing a file in the ____ directory of your storage device is equivalent to tossing a loose document into a drawer. a. root b. path c. back d. loose

a. root

An array of bytes can be wrapped, or encompassed, into a ByteBuffer using the ByteBuffer ____ method. a. wrap() b. convert() c. export() d. toArray()

a. wrap()

Every file path is either __________ or __________.

absolute; relative

This is a variable that keeps a running total.

accumulator

NOTE

all exception objects have a *printStackTrace* method, inherited from the *Throwable* class, that prints a *stack trace* (700)

Where is throws declared

along with the method signature

FACT

an *exception* is an object (682)

Checked exceptions

an exception that is typically a user error or a problem that cannot be foreseen by the programmer. These exceptions cannot simply be ignored at the time of compilation. For example, if a file is to be opened, but the file cannot be found, an exception occurs.

Runtime exceptions

an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation. while a program is running if the JVM detects an operation that is impossible to carry out.

exception

an indication of a problem that occurs during a programs execution

Exception

an object that defines an unusual or erroneous situation.

stream

an ordered sequence of bytes; it can be used as a source of input or as a destination for output

args

arguments

relative path

assumed that the file is located in the same folder as the program using the file

How may catch blocks are allowed after try

atleast 1

What is the output of this program? class box { int width; int height; int length; int volume; void volume() { volume = width * height * length; } void volume(int x) { volume = x; } } class Output { public static void main(String args[]) { box obj = new box(); obj.height = 1; obj.length = 5; obj.width = 5; obj.volume(5); System.out.println(obj.volume); } } a) 0 b) 5 c) 25 d) 26

b

What is the output of this program? class equality { int x; int y; boolean isequal(){ return(x == y); } } class Output { public static void main(String args[]) { equality obj = new equality(); obj.x = 5; obj.y = 5; System.out.println(obj.isequal); } } a) false b) true c) 0 d) 1

b

What is the output of this program? class exception_handling { public static void main(String args[]) { try { System.out.print("Hello" + " " + 1 / 0); } catch(ArithmeticException e) { System.out.print("World"); } } } a) Hello b) World c) HelloWorld d) Hello World

b

What is the output of this program? class exception_handling { public static void main(String args[]) { try { int a = args.length; int b = 10 / a; System.out.print(a); try { if (a == 1) a = a / a - a; if (a == 2) { int c = {1}; c[8] = 9; } } catch (ArrayIndexOutOfBoundException e) { System.out.println("TypeA"); } catch (ArithmeticException e) { System.out.println("TypeB"); } } } } a) TypeA b) TypeB c) 0TypeA d) 0TypeB

b

What is the output of this program? class exception_handling { public static void main(String args[]) { try { int a, b; b = 0; a = 5 / b; System.out.print("A"); } catch(ArithmeticException e) { System.out.print("B"); } } } a) A b) B c) Compilation Error d) Runtime Error

b

What is the output of this program? class exception_handling { public static void main(String args[]) { try { int a[] = {1, 2,3 , 4, 5}; for (int i = 0; i < 7; ++i) System.out.print(a[i]); } catch(ArrayIndexOutOfBoundsException e) { System.out.print("0"); } } } a) 12345 b) 123450 c) 1234500 d) Compilation Error

b

What is the output of this program? class exception_handling { public static void main(String args[]) { try { throw new NullPointerException ("Hello"); System.out.print("A"); } catch(ArithmeticException e) { System.out.print("B"); } } } a) A b) B c) Hello d) Runtime Error

b

What is the process of defining more than one method in a class differentiated by parameters? a) Function overriding b) Function overloading c) Function doubling d) None of these

b

Which of these class is related to all the exceptions that can be caught by using catch? a) Error b) Exception c) RuntimeExecption d) All of the mentioned

b

Paths is located in: a) java.io.file.Paths. b) java.nio.file.Paths

b correct

Files is an: a) abstract class b) final class c) class d) interface

b correct.

import java.io.Console; class A { public static void main(String[] args) { Console c = System. console(); String n = c.readLine("%c", "Enter Name: "); System. out. println("Welcome "+n); } } The above code will give: a) compiler error b) runtime error c) compile and echo whatever you entered to the screen d) none of the above

b correct. Throws java. util. IllegalFormatConversionException Attempting to convert car formatted type to string throws exception. Solution: c.readLine("%s", ........);

import java.io.File; class A { public static void main(String[] args) throws Exception { File dir = new File("C:\\a\\b\\"); File f = new File(dir, "MyFile.txt"); f.createNewFile(); } } Considering the above directories a and b do not exist prior to execution. The above code will give: a) compiler error b) runtime error c) compile and print create an empty file "MyFile.txt" in a\b folder d) none of the above

b correct. f.createNewFile(); will throw an IOException as a and b and directories have not being created ----> insert dir.mkdirs(); AFTER File dir = new File("C:\\a\\b\\"); ----> i.e. File dir = new File("C:\\a\\b\\"); dir.mkdirs(); File f = new File(dir, "MyFile.txt"); f.createNewFile();

import java.nio.file.*; class A { public static void main ( String[] args) throws Exception { Path src = Paths.get( "C:\\a\\log1.txt"); Path des = Paths.get( "C:\\a\\log2.txt"); Files.copy(src, des); } } Where log2.txt does exist. The above code will give: a) compiler error b) runtime error c) compile and copy the content successfully d) none of the above

b correct. it will throw a FileAlreadyExistsException log2.txt already exists. It must not exist prior to copy.

import java.io.File; class A { public static void main( String[] args) { File f = new File( "C:\\a\\b\\Log.txt" ); f.createNewFile(); } } The above code will give: a) compiler error b) runtime error c) compile and create a new file Log.txt d) none of the above

b correct. it will throw a RuntimeException. main class should declare that it throws Exception.

import java.io.File; class B { public static void main(String[] args) throws Exception { File f = new File( "c:\\a\\b\\MyFile.txt"); System. out. println(f.exists()); System. out. println( f. createNewFile() ); } } assume the above path does not exist. The above code will give: a) compiler error b) runtime error c) Compile and Print "false true" d) None of the above

b correct. will print " false java.io.IOException: The system cannot find the path specified"

import java.io.Console; class A { public static void main(String[] args) { Console c = System. console();char[] pw = c.readPassword(null, "Enter password: "); } } The above code will give: a) compiler error b) runtime error c) compile and print "Enter password: " d) none of the above

b is correct. It would throw an NullPointerException. readPassword(null,...) replace with readPassword("%s",... or readPassword( "Enter password: "); and it will compile and run fine.

import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths.get("file:///C://a//File.txt"); System. out. println(p1); } } Consider the above code running on Windows. The above code will give: a) compiler error b) runtime error c) compile and print C://a//File.txt d) none of the above

b is correct. Will throw InvalidPathException because file:///C://a// on Windows is a URL. Solution: convert the string to URI Universal Resource Identifier- Path p1 = Paths.get(URI.create("file:///C://a//File.txt")); making sure to import java.net.URI;

Which of the following statements will write a line separator? a. newline(); b. BufferedWriter.newline(); c. FileChannel.newline(); d. ByteBuffer.newline();

b. BufferedWriter.newline();

Comma-separated values (CSV) is a file format strictly used for working with Java and databases. a. True b. False

b. False

If you simply want to display records in order based on their key field, you need to create a random access file. a. True b. False

b. False

InputStream is a child of FileInputStream. a. True b. False

b. False

Permanent storage is usually called computer memory or random access memory (RAM). a. True b. False

b. False

The top-level element in a Path's directory structure is located at index 1. a. True b. False

b. False

You can direct System.err to a new location, such as a disk file or printer, but you cannot direct System.out to a new location. a. True b. False

b. False

InputStream and OutputStream are subclasses of the ____ class. a. IO b. Object c. Stream d. IOStream

b. Object

____ is an abstract class for reading character streams. a. System.out b. Reader c. System.err d. OutStream

b. Reader

When you use the BufferedReader class, you must import the ____ package into your program. a. java.nio.file b. java.io c. java.nio d. java.io.input

b. java.io

A(n) ____ field is the field in a record that makes the record unique from all others. a. unique b. key c. search d. individual

b. key

You can create a writeable file by using the Files class ____ method. a. getOutputStream() b. newOutputStream() c. newFileOutputStream() d. fileOutputStream()

b. newOutputStream()

A file channel is ____, meaning you can search for a specific file location and operations can start at any specified position. a. moveable b. seekable c. flexible d. dynamic

b. seekable

A data file can be used as a(n) ____ file when each record is accessed one after another in the order in which it was stored. a. application b. sequential access c. stream d. field

b. sequential access

Why is closing a file important?

because an "end of file" marker must be written to disk to let the operating system know where one file ends and another begins

a file that is *opened or created* with the *RandomAccessFile class* is treated as a _____file

binary (719) ~the *RandomAccessFile class* has the same methods as the *DataOutputStream class* for writing data, and the same methods as the *DataInputStream class* for reading data

Files created using byte-based streams

binary files

[ signals the start of main()'s

body All the code in a method will occur between the method's opening curly brace and closing curly brace

the FileOutputStream constructor takes an optional second argument which must be a _____ value

boolean (718)

How do you get the operating system to display the complete file path?

by highlighting a file in finder and then pressing Command I

How do you categorize files?

by the way that they store data

you must compile classes written in java into

bytecode

What is the output of this program? class box { int width; int height; int length; int volume; void volume(int height, int length, int width) { volume = width * height * length; } } class Prameterized_method{ public static void main(String args[]) { box obj = new box(); obj.height = 1; obj.length = 5; obj.width = 5; obj.volume(3, 2, 1); System.out.println(obj.volume); } } a) 0 b) 1 c) 6 d) 25

c

What is the output of this program? class exception_handling { public static void main(String args[]) { try { int a = args.length; int b = 10 / a; System.out.print(a); try { if (a == 1) a = a / a - a; if (a == 2) { int c = {1}; c[8] = 9; } } catch (ArrayIndexOutOfBoundException e) { System.out.println("TypeA"); } catch (ArithmeticException e) { System.out.println("TypeB"); } } } } a) TypeA b) TypeB c) 0TypeA d) 0TypeB

c

What is the output of this program? class exception_handling { public static void main(String args[]) { try { int a[] = {1, 2,3 , 4, 5}; for (int i = 0; i < 5; ++i) System.out.print(a[i]); int x = 1/0; } catch(ArrayIndexOutOfBoundsException e) { System.out.print("A"); } catch(ArithmeticException e) { System.out.print("B"); } } } a) 12345 b) 12345A c) 12345B d) Comiplation Error

c

What is the output of this program? class exception_handling { public static void main(String args[]) { try { int i, sum; sum = 10; for (i = -1; i < 3 ;++i) { sum = (sum / i); System.out.print(i); } } catch(ArithmeticException e) { System.out.print("0"); } } } a) -1 b) 0 c) -10 d) -101

c

What is the output of this program? class exception_handling { static void throwexception() throws ArithmeticException { System.out.print("0"); throw new ArithmeticException ("Exception"); } public static void main(String args[]) { try { throwexception(); } catch (ArithmeticException e) { System.out.println("A"); } } } a) A b) 0 c) 0A d) Exception

c

What is the output of this program? class exception_handling { public static void main(String args[]) { try { int a = args.length; int b = 10 / a; System.out.print(a); try { if (a == 1) a = a / a - a; if (a == 2) { int c = {1}; c[8] = 9; } } catch (ArrayIndexOutOfBoundException e) { System.out.println("TypeA"); } catch (ArithmeticException e) { System.out.println("TypeB"); } } } } a) TypeA b) TypeB c) 0TypeA d) 0TypeB

c

What is the output of this program? class exception_handling { public static void main(String args[]) { try { int i, sum; sum = 10; for (i = -1; i < 3 ;++i) sum = (sum / i); } catch(ArithmeticException e) { System.out.print("0"); } System.out.print(sum); } } a) 0 b) 05 c) Compilation Error d) Runtime Error

c

Which of these class is related to all the exceptions that are explicitly thrown? a) Error b) Exception c) Throwable d) Throw

c

Which of these is a super class of all exceptional type classes? a) String b) RuntimeExceptions c) Throwable d) Cachable

c

Which of these is the method which is executed first before execution of any other thing takes place in a program? a) main method b) finalize method c) static method d) private method

c

Which of these keywords is not a part of exception handling? a) try b) finally c) thrown d) catch

c

Which of these keywords is used to by the calling function to guard against the exception that is thrown by called function? a) try b) throw c) throws d) catch

c

Which of these keywords is used to generate an exception explicitly? a) try b) finally c) throw d) catch

c

Which of these keywords is used to manually throw an exception? a) try b) finally c) throw d) catch

c

Paths is an: a) abstract class b) static class c) class d) interface

c correct

Path contains: a) only static methods b) static and nonstatic methods c) nonstatic methods only

c correct.

import java.io.File; class B { public static void main(String[] args) throws Exception { File f = new File( "c:\\a\\b\\MyFile.txt"); System. out. println( f.exists()); System. out. println( f.createNewFile()); } } assume the above path does exist. The above code will give: a) compiler error b) runtime error c) Compile and Print "false true" d) None of the above

c correct. It's important to ensure that the path/folders exist beforehand. f.exists() --> returns false. f.createNewFile() --> returns true when MyFile.txt successfully created

Files and Path and Paths: a) can be created using "new" b) cannot be created using "new"

c correct. Path is an interface. Files and Paths are final classes. This class consists exclusively of static methods that operate on files, directories, or other types of files.

import java.io.Console; class A { public static void main(String[] args) { Console c = System. console(); String n = c.readLine("%s", "Enter Name: "); System. out. println("Welcome "+n); } } The above code will give: a) compiler error b) runtime error c) compile and echo whatever you entered to the screen d) none of the above

c correct. e.g. c:> java A :c> Enter Name: Mark c:> Welcome Mark

import java.io.Console; class A { public static void main(String[] args) { Console c = System. console();char[] pw = c.readPassword("%s", "Enter password: "); } } The above code will give: a) compiler error b) runtime error c) compile and print "Enter password: " d) none of the above

c is correct.

public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); System.out.println(br.readLine()); br.close(); } considering "hello world" is in file myFile.txt (where "hello" is on the first line and "world" on the second) The above code will give: a) compiler error b) runtime error c) compile and print "hello" d) none of the above

c is correct.

public static void main(String[] args) throws Exception { File i = new File("C:\\a\\b\\m.txt"); System. out. println( i.renameTo(new File("C:\\a\\b\\a.txt"))); } The above code will give: a) compiler error b) runtime error c) compile and rename m.txt to a.txt d) none of the above

c is correct.

public static void main(String[] args) throws Exception { File i = new File("C:\\a\\b\\"); System. out. println( i.isDirectory()); } The above code will give: a) compiler error b) runtime error c) compile and print false d) compile and print true

c is correct. File i = new File("C:\\a\\b\\"); is an object not a folder. In order to create the folder you need to state ; File i = new File("C:\\a\\b\\"); i.mkdirs(); System. out. println( i.isDirectory()); ----> will return true

import java.io.File; class A { public static void main( String [] args) { File f = new File( "C:\\a\\b\\"); f.mkdirs(); } } The above code will give: a) compiler error b) runtime error c) compile and create the subfolders a and b d) none of the above

c is correct. Note: The main method does not need to declare that it throws Exception but it does if creating via import java.nio.file.Files; i.e. File f = new File( "C:\\a\\b\\Log.txt"); f.createNewFile(); }

import java.nio.file.*; class A { public static void main ( String[] args) throws Exception { Path src = Paths.get( "C:\\a\\log1.txt"); Path des = Paths.get( "C:\\a\\log2.txt"); Files.copy(src, des); } } Where log2.txt does not exist. The above code will give: a) compiler error b) runtime error c) compile and will copy the contents of log1.txt to log2.txt d) none of the above

c is correct. Note: if log2.txt exists then it will throw a FileAlreadyExistsException

import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths.get( "C:\\a\\","b\\File.txt"); System. out. println(p1); } } File location does not exist physically in memory. The above code will give: a) compiler error b) runtime error c) compile and print "C:\\a\\b\\File.txt" d) none of the above

c is correct. Paths.get( "C:\\a\\","b\\File.txt"); is syntactically correct. You can also use: Paths.get( "C:\\a\\", "b\\","File.txt"); or Path p1 = Paths.get( "C:\\a\\b\\","File.txt");

File a = new File("c:\\a"); File f = new File(a,"f.txt"); System. out. println( f.createNewFile()); System. out. println( f.exists());The folders exist and the file already exists. The above code will give: a) compiler error b) runtime error c) Compile and Print "false true" d) None of the above

c is correct. Remember File constructor can take (File, String) (String) (String,String) params

public static void main(String[] args) throws Exception { File i = new File("C:\\a\\b\\"); System. out. println( i.delete()); System. out. println(i.delete()); i = new File("C:\\a\\"); System. out. println(i.delete()); } Assume the above folders exist. The above code will give: a) compiler error b) runtime error c) compile and delete a and b folders and return true d) none of the above

c is correct. The first delete method call delete subfolder b. A File reference i is then reappointed to a new File Object containing folder a. The second delete method call then deletes this folder a.

public static void main(String[] args) throws Exception { File i = new File("C:\\a\\b\\"); File f = new File(i,"m.txt"); f.createNewFile(); System. out. println( f.isFile());} The above code will give: a) compiler error b) runtime error c) compile and print true d) none of the above

c is correct. this code creates a new file in the subdirectory b

You can use Java's ____ class to create objects that contain information about files or directories, such as their locations, sizes, creation dates, and whether they even exist. a. Directory b. Property c. Path d. File

c. Path

____ applications require that a record be accessed immediately while a client is waiting. a. Sequential b. Dependent c. Real-time d. Batch

c. Real-time

FileSystems is a class that contains ____ methods, which assist in object creation. a. factory b. file c. abstract d. system

c. abstract

Because the backslash character starts the escape sequence in Java, you must use two ____ in a string that describes a Path in the DOS operating system. a. dashes b. quotes c. backslashes d. periods

c. backslashes

Some text files are ____ files that contain facts and figures, such as a payroll file that contains employee numbers, names, and salaries. a. application b. volatile c. data d. program

c. data

The ____ method returns the last Path element in a list of pathnames. a. toString() b. getNameCount() c. getFileName() d. getName(int)

c. getFileName()

The BufferedWriter class contains a ____ method that uses the current platform's line separator. a. lineSeparator() b. systemSeparator() c. newLine() d. newSeparator()

c. newLine()

Any of the file input or output methods in a Java program might throw an exception, so all the relevant code in the class is placed in a ____ block. a. finally b. throw c. try d. catch

c. try

InputStream object 's helper methods

can be used to read to stream or to do other operations on the stream. - public void close() throws IOException{} - protected void finalize()throws IOException {} - public int read(int r)throws IOException{} - public int read(byte[] r) throws IOException{} - public int available() throws IOException{}

If parent class method didn't declare an exception then the subclass overridden method

cannot declare checked exception but can declare unchecked exception

in versions prior to Java 7, each _____ clause can handle only 1 type of exception

catch class (700) ~however, a catch clause can handle more than 1 type of exception ~this can reduce a lot of duplicated code in a try statement that needs to catch multiple exceptions, but performs the same operation for each one

The + operator

chains together items within a single println() statement

those that do not inherit from *Error* or *RuntimeException* are _____

checked exceptions (703) ~you should handle these exceptions in your program

*exception objects* are created from _____ in the Java API

classes (682)

When a program is finished using a file, it should do this.

close the file

What method am I? Closes the stream and releases any system resources associated with it.

close() located in FileWriter - BufferedWriter - PrintWriter

void close() [DataOutputStream method]

closes the file (714)

void close() [DataInputStream method]

closes the file (716)

Arrays

collections of similar objects

non-executing program statements that provide documentation are called

comments

After the write and save a Java application file, you ______ it

compile + resave

A _______ translates high-level language statements into machine code

compiler

absolute path

complete path name with all directories listed; doesn't need any more information to locate the file on a system

Text Files

contain data that can be read in a text editor because the data has been encoded using ASCII or Unicode

binary files

contains data that has not been encoded as text; the content cannot be viewed in a text editor

What is the output of this program? class area { int width; int length; int volume; area() { width = 5; length = 6; } void volume() { volume = width * height * length; } } class cons_method { public static void main(String args[]) { area obj = new area(); obj.volume(); System.out.println(obj.volume); } } a) 0 b) 1 c) 25 d) 30

d

What is the output of this program? class exception_handling { public static void main(String args[]) { try { System.out.print("Hello" + " " + 1 / 0); } finally { System.out.print("World"); } } } a) Hello b) World c) Compilation Error d) First Exception then World

d

What is the output of this program? class exception_handling { public static void main(String args[]) { try { int a, b; b = 0; a = 5 / b; System.out.print("A"); } catch(ArithmeticException e) { System.out.print("B"); } finally { System.out.print("C"); } } } a) A b) B c) AC d) BC

d

What is the output of this program? class Output { static void main(String args[]) { int x , y = 1; x = 10; if(x != 10 && x / 0 == 0) System.out.println(y); else System.out.println(++y); } } a) 1 b) 2 c) Runtime Error d) Compilation Error

d

Which of these can be used to diffrentiate two or more methods having same name? a) Parameters data type b) Number of parameters c) Return type of method d) All of the mentioned

d

Which of these data tupe can be used for a method having a return statement in it? a) void b) int c) float d) All of the mentioned

d

Which of these keywords must be used to handle the exception thrown by try block in some rational manner? a) try b) finally c) throw d) catch

d

Which of these statement is incorrect? a) Two or more methods with same name can be diffrenciated on the basis of their parameters data type. b) Two or more method having same name can be diffrentiated on basis of number of parameters. c) Any already defined method in java's library can be defined again in the program with diffrent data type of parameters. d) If a method is returning a value the calling statement must have a varible to store that value.

d

Path is an: a) abstract class b) static class c) class d) interface

d is correct

import java.io.Console; class A { public static void main(String[] args) { Console c = System. console(); char[] n = c. readPassword( "%s", "Enter password: "); System. out. println( "Password is: "+n); } } Consider the user entered mark. The above code will give: a) compiler error b) runtime error c) compile and print mark d) Address of password e.g. [C@139eeda

d is correct.

public static void main(String[] args) throws Exception { File i = new File("C:\\a\\b\\"); System. out. println(i.delete()); System. out. println( i.delete()); } Assume the above folders exist. The above code will give: a) compiler error b) runtime error c) compile and delete a and b folders and return true d) none of the above

d is correct. It deletes b subfolder and returns true. the second call to the delete method i.delete() attempts to delete the same subfolder b but it does not exist therefore returns false

import java.io.File; class A { public static void main(String[] args) throws Exception { File dir = new File("C:\\a\\b\\"); dir.mkdirs(); File f = new File(dir, "MyFile.txt"); } } The above code will give: a) compiler error b) runtime error c) compile and print create an empty file "MyFile.txt" in a\b folder d) none of the above

d is correct. It will create the folders a and b but not the file "MyFile.txt" as f.createNewFile(); should be declared after File f = new File(dir, "MyFile.txt");

public static void main(String[] args) throws Exception { File i = new File("C:\\a\\b\\"); File f = new File(i,"m.txt"); System. out. println( f.isFile());} The above code will give: a) compiler error b) runtime error c) compile and print true d) none of the above

d is correct. You need to call the method f.createNewFile(); after File f = new File(i,"m.txt"); it will then return through

public static void main(String[] args) throws Exception { File i = new File("C:\\a\\b\\"); i.mkdir(); System. out. println( i.isDirectory()); } The above code will give: a) compiler error b) runtime error c) compile and print true d) none of the above

d is correct. i.mkdir(); therefore doesn't create folders ----> makes one folder only. however if i.mkdir(); is replaced with i.mkdirs(); this would work fine.

public static void main(String[] args) throws Exception { File i = new File("C:\\a\\b\\"); System. out. println( i.delete()); } Assume the above folders exist. The above code will give: a) compiler error b) runtime error c) compile and delete a and b folders and return true d) none of the above

d is correct. it will delete b sub folder only.

public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileWriter fw = new FileWriter(f); BufferedWriter bw = new BufferedWriter(fw); bw.write("a1"); bw.write("b1"); } The above code will give: a) compiler error b) runtime error c) compile and print "a1b1" d) none of the above

d is correct. myFile.txt is still open. You must call bw.flush(); bw.close(); after completing writing to the file.

public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileWriter fw = new FileWriter(f); BufferedWriter bw = new BufferedWriter(fw); bw.write("a"); bw.write("b"); bw.flush(); bw.close(); } The above code will give: a) compiler error b) runtime error c) compile and write a b (On seperate lines) d) none of the above

d is correct. will write "ab" (without spaces). To write a and b on separate lines you need to get the character for your particular operating system e.g. bw.write("a"); bw.write( System. lineSeparator()); bw.write("b");

A(n) ____ is a holding place for bytes that are waiting to be read or written. a. ByteChannel b. FileChannel c. InputStream d. ByteBuffer

d. ByteBuffer

You can use Java's ____ class to create your own random access files. a. Path b. FileStream c. File d. FileChannel

d. FileChannel

A ____ is a group of characters that has some meaning. a. record b. file c. byte d. field

d. field

The String class ____ method accepts an argument that identifies the field delimiter and returns an array of Strings. a. tokens() b. divide() c. tokenize() d. split()

d. split()

FACT

data can be stored in a file in its *raw binary format* (713)

_____ deals with *thrown exceptions*

default exception handler (682)

Variable names cannot start with a

digit

Given the following statement, which statement will write "Calvin" to the file DiskFile.txt? PrintWriter diskOut = new PrintWriter("DiskFile.txt");

diskOut.println("Calvin");

This type of loop always executes at least once.

do-while

This type of loop is ideal in situations where you always want the loop to iterate at least once.

do-while loop

In a java program, you must use _______ to separate classes, objects, and methods

dots

Moon's gravity is 17 percent of earth's. Write a program for your weight on the moon.

double moonweight; double earthweight; earthweight = 165; moonweight = earthweight * 0.17; System.out.println(earthweight + " earth-pounds is equivalent to " + moonweight + " moon-pounds.");

exception handler

each catch clause (can have more than one) is called this.

What should follow try block

either catch or finally

Exception handling

enables a program to deal with exceptional situations and continues its normal execution

a(n) _____ is an object that is generated in memory as the result of an error or an unexpected event

exception (681,682)

a(n) _____ is a section of code that responds to *exceptions* when they are *thrown*

exception handler (682)

File -FileWriter- FileReader - BufferedReader - BufferedWriter - PrintWriter are located in java.lang true or false

false

File -FileWriter- FileReader - BufferedReader - BufferedWriter - PrintWriter do not need to have be wrapped in a try/catch block or declare that method throws an Exception. true or false

false

Path is located in java.io.file.Path. True or false?

false it is located in: java.nio.file.Path

Files Path and Paths existed in Java 6. True or false

false. All were created in Java 7. Only File existed in Java 6.

Compilers less than Java 7 uses static methods on File to create files and directories. True or false

false. Compilers <Java 7 uses instance methods on File to create files and directories. e.g. File f = new File("C:\\a\\b\\Log.txt"); f.mkdirs(); f..createNewFile();


संबंधित स्टडी सेट्स

Chapter 14 Real Estate Financing

View Set

A Level Further Maths CP2 Methods in Differential Equations

View Set