Java serialization

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

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

file channel

3 stream intermediate operations for transformation

filter(Predicate<? super T> predicate) map(Function<? super T, ? extends R> mapper) flatMap(Function<? super T, ? extends Stream<? extends R>> mapper) e.g. List<String> zero = Arrays.asList(); List<String> one = Arrays.asList("Bonobo"); List<String> two = Arrays.asList("Mama Gorilla", "Baby Gorilla"); Stream<List<String>> animals = Stream.of(zero, one, two); animals.flatMap(l -> l.stream()).forEach(System.out::println);

Common operations

filter, map, reduce, find, match, sort, etc

FilterInputStream

filters an InputStream

internal iterations - looping with lambdas - forEach method of collections

forEach(Consumer)

kinds of files

formatted vs binary -text file: looks like text from cout -binary: saved in raw memory format(int is 4-byte)

JaveScript

function warn() { alert ("Danger, Will Robinson!") } function getConfirmation(){ let retVal = confirm("Continue?") if( retVal == true){ return true} else{ return false} } function getValue(){ let retVal = prompt("Enter name: ", "Ramya") }

secondary storage devices

hard disks, flash drives, DVDs and more

stream of bytes

how Java views a file

Deserializing an Object

https://www.tutorialspoint.com/java/java_serialization.htm

URIs (Uniform Resource Identifiers)

identify data on the Internet.

cin.get(ch) returns TRUE

if end of file char has NOT been read and FALSE otherwise

cin.eof() returns TRUE

if end of file char has been read and FALSE otherwise

FALSE (input command "cin" will return a value)

if the variable is NOT read successfully

TRUE (input command "cin" will return a value)

if the variable is read successfully

Write an if statement that checks whether an ifstream object called foobar has reached the end of file or has encountered an error.

if(foobar)

Write a statement that will read the contents of an ifstream object called ifile into an array called buff.

ifile.read( (char*)buff, sizeof(buff) );

Read in variable x into file in1;

ifstream in1; in1.open("hi.txt"); in1>> x;

read and process input from file until you've reached the end of the file

ifstream in1; open.in1("hi.txt"); while(!in1.eof()) { //reads and process input from file }

Name three stream classes commonly used for disk I/O.

ifstream, ofstream, and fstream

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(); } } } }

exmple for serialization

import java.io.*; public class SerializeDemo { public static void main(String [] args) { Employee e = new Employee(); e.name = "Reyan Ali"; e.address = "Phokka Kuan, Ambehta Peer"; e.SSN = 11122333; e.number = 101; try { FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.printf("Serialized data is saved in /tmp/employee.ser"); } catch (IOException i) { i.printStackTrace(); } } }

dettach file from stream object

in1.close();

stream classes are related to each other through

inheritance

"<<" is which operator

insertion operator

Random files are also called ____________________ files.

instant access direct access

Write a declarator for main() that will enable command-line arguments.

int main(int argc, char *argv[] )

cascading

intermixing manipulators and other output statements with insertion operator

The base class for most stream classes is the ________ class.

ios

relative path

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

Uniform Resource Identifier (URI)

is a more general form of the Uniform Resource Locators (URLs) that are used to locate websites.

Buffering

is an I/O-performance-enhancement technique

the default way for opening an output file:

is to create a brand new file and begin writing from the beginning if another file with the same name exists, it will be overwritten

Class Scanner

is used extensively to input data from the keyboard. This class can also read data from a file

Output stream "ofstream"

is used to print program output

Input stream "ifstream"

is used to read user input

built-in functional interfaces package

java.util.function

3 stream intermediate operations for extracting/combining substreams

limit(long n) skip(long n) Stream.concat(Stream<? extends T> s1, Stream<? extends T> s2) p.s. stateful operation limit and skip

what to do after attaching file

make sure it is valid. test true and false of stream object

ParallelStreams

multiple assembly lines

transient

must be declared on an object if it is in a class that implements serializable, but it is not serializable

Thrift

namespace java edu.nwmissouri.csis struct Book{ 1: i64 id 2: string title } service BookService { User createBook(1: string title) }

lambda expressions

pass function as a parameter store behavior in a variable

reative path

path expressed in reference to another directory

absolute path

path from root directory

userful member functions of input stream class

peek(), get() review eof();

stream intermediate operation that is useful for debugging

peek(Consumer<? super T> action) p.s. stateless operation

"cout << float_variable"

prints digits and decimal point

"cout << string_variable"

prints sequence of characters

"cout << int_variable"

prints sequence of digits

"cout << char_variable"

prints single character

list( ) method

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

Class System

provides methods setIn, setOut and setErr to redirect the standard input, output and error streams, respectively.

Files class

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

member function of output stream class that prints out

put() ostream& put(char c);

read method (binary)

reads a single byte as an integer

"cin >> float_variable"

reads digits and decimal point

cin.get(ch)

reads next character from input stream in ch

"cin >> string_variable

reads sequence of characters

"cin << int_variable"

reads sequence of digits

"cin >> char_variable"

reads single character

serialized object

sequence of bytes that contains an object's data and type information

text file (formatted text)

simply made of readable text characters looks like the output that is typically printed to the screen through the cout object

ignore()

skips designated characters or up to a delimeter

what happens once close function is used

stream object doesnt get deleted, it can be reused and attached to another file

stream manipulator

symbol or function used by placing it on the right side of insertion operator

open( )

takes in filename as an argument out1.open("outfile1.txt"); // for ofstreams -- call create bob.open("clients.dat"); //brand new file for output in1.open("infile.txt"); // for ifstreams--call try to open joe.open("clients.dat"); //existing files for input

Define what current position means when applied to files.

the byte location at which the next read or write operation will take place

Filtering

the filter stream provides additional functionality, such as aggregating bytes into meaningful primitive-type units.

to use file stream objects:

they need to be attatched to files before

close ( )

to detach a file from stream object when finished with it in1.close( ); closes the file--does not get rid of stream object stream object can now be used to attach to another file, if deisred

another version of toMap() for parallel processing

toConcurrentMap(**)

stream classes can only be passed as reference T or F

true

you can pass variable type of child into function parameters of parent

true

object declaration is same as regular declaration T or F

true, a class is a type

Class

type used to declare objects

sequential file

typically written or read from start to finish

to open a file in append mode:

use an extra parameter in the open( ) function ofstream fout; //create file stream fout.open("file.txt", ios::app) //open file in append mode

attach to file:

use member function : "open" i1.open("hi.txt");

How can we output integer digits in reverse order?

use modulo operator to calculate least significant convert digit into corresponding ascii character print this ascii character to the output use division to remove the least significant digit repeat until there are no more digits to output

file

used for long-term retention of data

SERIALIZATION is used to pass on to another object via the OutputStream class

which can be sent over the network.

cin.peek()

will look ahead one hcaracter without reading

cin.unget()

will undo the last get from the input stream

cout.put(ch)

will write one character ch onto output stream

JSON

{ "book": { "id": 123, "title": "Object Thinking", "author": "David West", "published": { "by": "Microsoft Press", "year": 2004 } } }

"stream"

"a sequence of data elements made available over time"

input stream

"cin" command in C++, where characters that are typed by the user are processed one at a time to read variables of different types

output stream

"cout" command in C++, where variable values are converted into ascii characters and the displayed one at a time on the monitor

library to create file stream objects

#include <fstream>

PrintStream

(a subclass of FilterOutputStream) performs text output to the specified stream.

System.in

(standard input stream) object normally inputs bytes from the keyboard

System.err

(the standard error stream object) normally outputs character-based error messages to the screen.

System.out

(the standard output stream object) normally outputs character data to the screen

three stream objects

- System.in - System.out - System.err

a class to be serialized successfully, two conditions must be met

- The class must implement the java.io.Serializable interface. - All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Stream

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

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.

what is optional

- either a wrapper for an object or no object - intended to be null safe

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);

reduction or terminal operation

-consumes the stream pipeline. -it does not produce another stream like intermediate operations. -it produces a result or a side-effect.

ObjectInputStream class

-deserializing an object -retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type. public final Object readObject() throws IOException, ClassNotFoundException

For the File Input Stream, what are some commonly used methods?

1. read() -returns an int which contains the byte value of the byte read 2. close() -all streams must be closed

*Create Buffer Streams*

1. unbuffered stream object is passed to the constructor for a buffered stream class. inp = new BufferedReader(new FileReader("x.txt")); out = new BufferedWriter(new FileWriter("c.txt"));

DTD

<!ELEMENT dogs (title, dogList)> <!ELEMENT title (#PCDATA)> <!ELEMENT dogList (dog+)> <!ELEMENT dog EMPTY> <!ATTLIST dog name ID #REQUIRED age CDATA #IMPLIED>

XML

<?*** version="1.0"?> <book id="123"> <title>Object Thinking</title> <author>David West</author> <published> <by>Microsoft Press</by> <year>2004</year> </published> </book>

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.

CookieHandler

A CookieHandler object provides a callback mechanism to hook up a HTTP state management policy implementation into the HTTP protocol handler.

CookieStore

A CookieStore object represents a storage for cookie.

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.

uneditable

A JEditorPane generates HyperlinkEvents only if it is __________

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.

SequenceInputStream

A SequenceInputStream represents the logical concatenation of other input streams.

JarURLConnection

A URL Connection to a Java ARchive (JAR) file or an entry in a JAR file.

HttpURLConnection

A URLConnection with support for HTTP-specific features.

Socket-Exception

A __________ is thrown if the DatagramSocket constructor fails to bind the DatagramSocket to the specified port

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.

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.

FileOutputStream

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

FileFilter

A filter for abstract pathnames.

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.

What is serialization?

A process of saving state of a java object to a sequence of bytes. -this sequence of bytes can be sent over a network or stored to a file.

What is a thread?

A separate process in your computer An in

FileNameMap

A simple interface which provides a mechanism to map between a file name and a MIME type string.

SocketOption

A socket option associated with a socket.

Stream

A stream is a sequence of data items that are conceptually produced one at time. Streams allow manipulate collections of data in declarative way. Stream are "fancy iterators over a collection of data".

UnknownHostException

A(n) __________ is thrown when a server address indicated by a client cannot be resolved

What is SERIALIZATION?

Ability to read or write an object to a stream. This is a process of "FLATTENING" an object.

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.

after seialization then deserialization of the object mechanism

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Console.Out

Allows a program to produce output on the screen

Console.Error

Allows a program to write error messages to the screen

HttpCookie

An HttpCookie object represents an http cookie, which carries state information between server and user agent.

File

An abstract representation of file and directory pathnames.

showDocument

AppletContext method __________causes the browser to access and display a resource.

What is the complexity/Difficulty when dealing with threads?

Arises when multiple threads need to access the same resources.

functional interface for Boolean??

BooleanSupplier boolean getAsBoolean()

Classes avaialable to wrap UnBuffered Streams

Buffer Byte Streams: 1. BufferedInputStream 2. BufferedOutputStream Buffered Char Streams: 1. BufferedReader 2. BufferedWriter

What are the two types of stream data?

Byte based/ Character based.

setFileSelectionMode

Call method specifies what the user can select from the fileChooser

ObjectInputValidation

Callback interface to allow validation of objects within a graph.

Flush

Causes the ObjectOutputStream on the server to send a stream header to the corresponding client's ObjectInputStream

Field

Character or group of characters that has some meaning

Delimiter

Character used to specify the boundary between data items in text files

Occupies space on a section of a storage device, contains a name, and time of creation

Characteristics of a file

URL

Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web.

Record

Collection of fields that contain data about an entity

Computer file

Collection of information stored on a nonvolatile device in a computer system. They exist on permanent storage devices.

Sequence of elements

Collections are about data; Streams are about computations

Path

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

Folder or Directory

Computer users organize their files into ________

Data files

Consist of related records

ObjectStreamConstants

Constants written into the Object Serialization Stream.

File Class

Contained in the System.IO Namespace, and contains methods to access information about files

FileReader

Convenience class for reading character files.

FileWriter

Convenience class for writing character files.

Deserialization

Converts streams of bytes back into objects

CookieManager

CookieManager provides a concrete implementation of CookieHandler, which separates the storage of cookies from the policy surrounding accepting and rejecting cookies.

CookiePolicy

CookiePolicy implementations decide which cookies should be accepted and which should be rejected.

Character, Field, Record, File

Data Hierarchy

Permanent Storage

Data is not lost when a computer loses power, and it is referred to as nonvolatile. This is similar to a program saving data on to a disk.

persistent data

Data maintained in files exists beyond the duration of program execution

IOException

DatagramSocket method send throws a(n) _____ if an error occurs while sending a packet.

Console.In, Console.Out, Console.Error

Default stream objects in C#

StandardSocketOptions

Defines the standard socket options.

Not secure because it is not encrypted, and cumbersome to convert each field to text and combine the fields with delimiters

Disadvantages to writing to a text file

What should you know for the test?

Example of deadlock Example of race condition

What is the difference between printwriter and FileOutputStream?

F.O.S writes to a file as a streams of bytes P.W writes to a file using characters

What class do you need to use to work with Files?

File Class ---> import java.io.FILE

Type out the code used to create a file in Java

File file = new File("fileName"); Creates a file in the directory it was run from

Example

FileInputStream in = new FileInputStream("xanadu.txt"); FileOutputStream out = new FileOutputStream("outagain.txt"); int c; while ((c = in.read()) != -1) { out.write(c);

To write the bytes to a file, an output stream object is needed

FileOutputStream outStream; outStream = new FileOutputStream("Objects.dat"); ObjectOutputStream ObjectOutputFile = new ObjectOutputStream(outStream);

example of FileReader and FileWriter. *This will read character by character and write it.*

FileReader inputStream = new FileReader("xanadu.txt"); FileWriter outputStream = new FileWriter("characteroutput.txt"); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c)

binary files

Files created using byte-based streams - are read by programs that understand the specific content of the file and the ordering of that content.

text files

Files created using character-based streams - can be read by text editors

When you are done with a stream, you will often want to look at its elements. You can call the iterator method, which yields an old-fashioned iterator that you can use to visit the elements. Alternatively, you can call the forEach method to apply a function to each element: stream.forEach(System.out::println); On a parallel stream, the forEach method traverses elements in arbitrary order. If you want to process them in stream order, call forEachOrdered instead.

How to collect results from a stream?

For collecting stream elements to another target, there is a convenient collect method that takes an instance of the Collector interface. The Collectors class provides a large number of factory methods for common collectors. To collect a stream into a list or set, simply call List<String> result = stream.collect(Collectors.toList()); Set<String> result = stream.collect(Collectors.toSet()); TreeSet<String> result = stream.collect(Collectors.toCollection(TreeSet::new));

How to collect stream result to collection?

Use Collectors.toMap: Map<Integer, String> idToName = people.collect( Collectors.toMap(Person::getId, Person::getName));

How to collect stream results to a map?

String[] result = stream.toArray(String[]::new);

How to collect stream results to an array?

If you want to write a method that creates an Optional object, there are several static methods for that purpose, including Optional.of(result) and Optional.empty(). public static Optional<Double> inverse(Double x) { return x == 0 ? Optional.empty() : Optional.of(1 / x); }

How to create optional values?

IntStream stream = IntStream.of(1, 1, 2, 3, 5); stream = Arrays.stream(values, from, to); // values is an int[] array IntStream zeroToNinetyNine = IntStream.range(0, 100); // Upper bound is excluded IntStream zeroToHundred = IntStream.rangeClosed(0, 100); // Upper bound is included

How to create primitive type streams?

Using stream() or parallelStream() methods

How to create stream from Collection interface?

Using the static Stream.of() method. Stream<String> words = Stream.of(contents.split("\\PL+")); Stream<String> song = Stream.of("gently", "down", "the", "stream"); Use Arrays.stream(array, from, to) to make a stream from array elements between positions from (inclusive) and to (exclusive). To make a stream with no elements, use the static Stream.empty method

How to create stream from an array?

Use one of the summarizing(Int|Long|Double) methods: IntSummaryStatistics summary = stream.collect( Collectors.summarizingInt(String::length)); double averageWordLength = summary.getAverage(); double maxWordLength = summary.getMax();

How to reduce the stream results to a sum, average, maximum, or minimum?

Using Seek() method and the SeekOrigin enumeration

How to reposition the file pointer

The key to using Optional effectively is to use a method that either produces an alternative if the value is not present, or consumes the value only if it is present. String result = optionalString.orElse(""); String result = optionalString.orElseGet(() -> Locale.getDefault().getDisplayName()); String result = optionalString.orElseThrow(IllegalStateException::new); optionalValue.ifPresent(v -> results.add(v)); or optionalValue.ifPresent(results::add);

How to use optionals?

Activated, entered and exited

HyperlinkEvent nested class EventType declares three static EventType objects

void PrintRecord(ofstream& fout, int id, double bal); PrintRecord(cout, 12, 34.56); Legal or Illegal

Illegal. parent into child

throw IOException

Industrial strength file, and directory, processing programs require extensive exception handling to recover from such possibilities

getByName

InetAddress static method _____returns an InetAddress object containing the specified IP address

What kind of stream would you use to read data into a program?

Input stream

FilenameFilter

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

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.

RandomAccessFile

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

3 types of Stream Primitive

IntStream LongStream DoubleStream

can you convert from one primitive stream to another

IntStream - asDoubleStream(), asLongStream() LongStream = asDoubleStream() DoubleStream - none mapToInt(XtoYFunction f) mapToLong(XtoYFunction f) mapToDouble(XtoYFunction f)

Primitive Supplier classes and method

IntSupplier - getAsInt() LongSupplier - getAsLong() DoubleSupplier - getAsDouble()

SocketOptions

Interface of methods to get/set socket options.

how to create Primitive Stream

Int|Long|DoubleStream.empty() Int|Long|DoubleStream.generate(Int|Long|DoubleSupplier supplier) Int|Long|DoubleStream.iterate(int|long|double seed, Int|Long|DoubleUnaryOperator f) Int|Long|DoubleStream.of(int|long|double... x) Int|LongStream.range(n, n) Int|LongStream.rangeClosed(n, n) concat(XYZStream a, XYZStream b)

tagging interface

It does not contain methods

SERIALIZATION is also used to save object to some permanent storage

Its state should be written in a serialized form to a file such that the object can be reconstructed at a later time from that file.

setPage

JEditorPane method _____downloads a document and displays it.

FILES_AND_DIRECTORIES

JFileChooser static constant that indicate that files and directories can be selected

A(n) _________ is thrown when a String that is not in proper URL format is passed to a URL constructor

MalformedURLException

EOFException

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

ClassNotFoundException

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

What does the File class contain?

Methods for obtaining file and directory properties ->length of a file ->path of a file ->check if file exists

Console

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

does serialization is jvm dependent

Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform

NOTE

Most of the classes covered in the I/O Streams section are in the java.io package 1. Byte Streams 2. Character Streams 3. Buffered Streams. 4. Data Streams. 5. Object Streams.

value of readObject()

Notice that the return _______ is cast to an Employee reference.

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.

ObjectOutput

ObjectOutput extends the DataOutput interface to include writing of objects.

writeObject

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

DirectoryStream interface

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

Path interface

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.

accept

Once the ServerSocket is created, the server can listen indefinitely (or block) for an attempt by a client to connect. This is accomplished with a call to the ServerSocket method __________

Suppose super class of a new class implement Serializable interface, how can you avoid new class to being serialized?

One of the tricky interview question in Serialization in Java. If Super Class of a Class already implements Serializable interface in Java then its already Serializable in Java, since you can not unimplemented an interface its not really possible to make it Non Serializable class but yes there is a way to avoid serialization of new class. To avoid Java serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method. This is another benefit of customizing java serialization process as described in above Serialization interview question and normally it asked as follow-up question as interview progresses.

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.

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

OutputStream

In console mode programs, the printer can be accessed using the predefined filename ________.

PRN, LPT1

PipedReader

Piped character-input streams.

PipedWriter

Piped character-output streams.

PrintWriter

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

Serialization

Process of converting objects into streams of bytes

ObjectInputStream.GetField

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

ObjectOutputStream.PutField

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

Directory class

Provides information about directories or folders

IDN

Provides methods to convert internationalized domain names (IDNs) between a normal Unicode representation and an ASCII Compatible Encoding (ACE) representation.

Paths class

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

What are the two basic functions you can do with a stream?

Read or write.

read method (text)

Reads each character as an integer, reaches the end of the line when it returns -1

ObjectInputStream

Reads entire objects from a disk

BufferedReader

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

CacheResponse

Represent channels for retrieving resources from the ResponseCache.

URI

Represents a Uniform Resource Identifier (URI) reference.

SecureCacheResponse

Represents a cache response originally retrieved through secure means, such as TLS.

ProxySelector

Selects the proxy server to use, if any, when connecting to the network resource referenced by a URL.

Serializable

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

How many methods Serializable has? If no method then what is the purpose of Serializable interface?

Serializable interface exists in java.io package and forms core of java serialization mechanism. It doesn't have any method and also called Marker Interface in Java. When your class implements java.io.Serializable interface it becomes Serializable in Java and gives compiler an indication that use Java Serialization mechanism to serialize this object.

Binary files

Store software instructions or images, music, etc.

Data processing operations

Stream operations can be executed either sequentially or in parallel

Console.In

Stream that accepts data from the keyboard

2 ways to create infinite streams

Stream.generate(Supplier<T> s) Stream.iterate(T seed, UnaryOperator<T> f) e.g. Stream<String> s1 = Stream.generate(()->"echo"); Stream<String> s2 = Stream.generate(Math::random); Stream<BigInteger> s3 = Stream.iterate(BigInteger.ZERO, n -> n .add(BigInteger.ONE)); p.s. using infinite streams can cause hang

3 ways to create finite streams

Stream.of(T t) Stream.of(T... t) Stream.empty()

Source

Streams consume from a data-providing source such as collections, arrays, or I/O resources.

What is the most important concept about FILE IO?

Streams, the core concept in Java IO.

JEditorPane (from package javax.swing)

Swing GUI component _______ can display the contents of a file on a web server.

False

T or F: Normally, an applet can read files on any server that can be reached over the network

For an object to be serialized, its class must implement the Serializable interface.

TRUE

If a class contains objects of other classes as fields, those classes must also implement the serializable interface, in order to be serialized.

TRUE

InPutStream

The InputStream is used to read data from a source.

Serializing an Object

The ObjectOutputStream class is used -When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.

object output sream

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file.

Besides the file name, what else is required during RandomAccessFile instantiation?

The RandomAccessFile has to specify whether it is a read only or a read and write file.

StreamTokenizer

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

ContentHandler

The abstract class ContentHandler is the superclass of all classes that read an Object from a URLConnection.

Authenticator

The class Authenticator represents an object that knows how to obtain authentication for a network connection.

PasswordAuthentication

The class PasswordAuthentication is a data holder that is used by Authenticator.

BufferedOutputStream

The class implements a buffered output stream.

MulticastSocket

The multicast datagram socket class is useful for sending and receiving IP multicast packets.

What is de-serialization?

The process of building object state back after reading a sequence of bytes from over a network or from a stored file.

TCP (Transmission Control Protocol).

The protocol used for transmission is ________

transient

The value of the SSN field was 11122333 when the object was serialized, but because the field is_____ , this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0. (Look for the example on the https://www.tutorialspoint.com/java/java_serialization.htm)

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

Bridge streams

There are two general-purpose byte-to-character "bridge" streams: *InputStreamReader* and *OutputStreamWriter*. The charset that it uses may be specified by name or may be given explicitly.

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.

StringBufferInputStream Deprecated

This class does not properly convert characters into bytes.

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.

Socket

This class implements client sockets (also called just "sockets").

ServerSocket

This class implements server sockets.

LineNumberInputStream Deprecated

This class incorrectly assumes that bytes adequately represent characters.

SerializablePermission

This class is for Serializable permissions.

NetPermission

This class is for various network permissions.

What is the difference between Serializable and Externalizable interface in Java?

This is most frequently asked questions in Java serialization interview. Here is my version Externalizable provides us writeExternal() and readExternal() method which gives us the flexibility to control java serialization mechanism instead of relying on Java's default serialization. Correct implementation of Externalizable interface can improve the performance of application drastically.

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.

If we want to read line by line then.

Use BufferedReader and PrintWriter which can wrap Filereader and Filewriter and has operations Readline and Println.

How can we output integer digits in correct order?

Use modulo operator to calculate least significant digit Convert digit into corresponding ascii character Save this ascii character in an array of characters Use division to remove least significant digit Repeat until there are no more digits Finally, loop over the array of characters in reverse order and output the digits in the correct order

If your data will be used by only the Java program that generated It:

Use serialization

long n = f.getFilePointer();

Used to find the current position of the pointer

showDocument

Using a URL as an argument to the __________ method of interface AppletContext causes the browser in which an applet is executing to display the URL

Random access memory (RAM)

Usually called temporary storage also referred to as volatile. This is similar to assigning values to a variable.

URLDecoder

Utility class for HTML form decoding.

URLEncoder

Utility class for HTML form encoding.

1. A stream does not store its elements. They may be stored in an underlying collection or generated on demand. 2. Stream operations don't mutate their source. For example, the filter method does not remove elements from a new stream, but it yields a new stream in which they are not present. 3. Stream operations are lazy when possible. This means they are not executed until their result is needed. For example, if you only ask for the first five long words instead of all, the filter method will stop filtering after the fifth match. As a consequence, you can even have infinite streams!

What are differences between streams and collections?

Reductions are terminal operations. They reduce the stream to a non-stream value that can be used in your program.

What are reductions?

- max/min methods Optional<String> largest = words.max(String::compareToIgnoreCase); The findFirst returns the first value in a nonempty collection. It is often useful when combined with filter. Optional<String> startsWithQ = words.filter(s -> s.startsWith("Q")).findFirst();

What are simple reduction method examples?

The Stream interface has two static methods for making infinite streams. The generate method takes a function with no arguments (or, technically, an object of the Supplier<T> interface). Whenever a stream value is needed, that function is called to produce a value. You can get a stream of constant values as Stream<String> echos = Stream.generate(() -> "Echo"); or a stream of random numbers as Stream<Double> randoms = Stream.generate(Math::random); To produce infinite sequences, such as 0 1 2 3 . . . , use the iterate method instead. It takes a "seed" value and a function (technically, a UnaryOperator<T>) and repeatedly applies the function to the previous result. For example, Stream<BigInteger> integers = Stream.iterate(BigInteger.ZERO, n -> n.add(BigInteger.ONE));

What do generate and iterate methods of Stream interface do?

The count method returns the number of elements of a stream.

What does count method do?

the peek method yields another stream with the same elements as the original, but a function is invoked every time an element is retrieved. That is handy for debugging: Object[] powers = Stream.iterate(1.0, p -> p * 2) .peek(e -> System.out.println("Fetching " + e)) .limit(20).toArray(); When an element is actually accessed, a message is printed. This way you can verify that the infinite stream returned by iterate is processed lazily.

What does peek method do?

You can concatenate two streams with the static concat method of the Stream class.

What does stream.concat() do?

An Optional<T> object is a wrapper for either an object of type T or no object. In the former case, we say that the value is present. The Optional<T> type is intended as a safer alternative for a reference of type T that either refers to an object or is null.

What is the optional type?

1. Create a stream. 2. Specify intermediate operations for transforming the initial stream into others, possibly in multiple steps. 3. Apply a terminal operation to produce a result. This operation forces the execution of the lazy operations that precede it. Afterwards, the stream can no longer be used. List<String> words = ... long count = words.stream().filter(w -> w.length() > 12).count(); or you can use parallelStream() instead of stream() In the example, the stream is created with the stream or parallelStream method. The filter method transforms it, and count is the terminal operation.

What is the typical workflow when you work with streams?

What is a race condition?

When 2 or more threads are trying to access data at the same time. This can cause thread interference.

Random Access File

When records are not used in sequence, so records can be accessed in any order

datagram

With _________, individual packets of information are transmitted.

packets

With datagram sockets, individual ____of information are transmitted

Serialization java

Write a file holds flattened or serializable objects then your program read the serializable objects from the file and in flat them back into living

write method (text)

Writes a single character

ObjectOutputStream

Writes entire objects to a disk

BufferedWriter

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

built-in (primitive only) operation

XYZSummaryStatistics summaryStatistics() OptionalDouble average() int|long|double sum() OptionalInt|Long|Double min() OptionalInt|Long|Double max()

What is the output of this program? import java.util.*; class Bitset { public static void main(String args[]) { BitSet obj = new BitSet(5); for (int i = 0; i < 5; ++i) obj.set(i); System.out.print(obj.get(3)); } } a) 2 b) 3 c) 4 d) 5

a

What is the output of this program? import java.util.*; class Bitset { public static void main(String args[]) { BitSet obj = new BitSet(5); for (int i = 0; i < 5; ++i) obj.set(i); obj.clear(2); System.out.print(obj); } } a) {0, 1, 3, 4} b) {0, 1, 2, 4} c) {0, 1, 2, 3, 4} d) {0, 0, 0, 3, 4}

a

What is the output of this program? import java.util.*; class Maps { public static void main(String args[]) { HashMap obj = new HashMap(); obj.put("A", new Integer(1)); obj.put("B", new Integer(2)); obj.put("C", new Integer(3)); System.out.println(obj.keySet()); } } a) [A, B, C] b) {A, B, C} c) {1, 2, 3} d) [1, 2, 3]

a

What is the output of this program? import java.util.*; class Output { public static void main(String args[]) { ArrayList obj = new ArrayList(); obj.add("A"); obj.ensureCapacity(3); System.out.println(obj.size()); } } a) 1 b) 2 c) 3 d) 4

a

Which of these class object has architecture similar to that of array? a) Bitset b) Map c) Hashtable d) All if the mentioned

a

Which of these is the interface of legacy is implemented by Hashtable and Dictionary classes? a) Map b) Enumeration c) HashMap d) Hashtable

a

Which of these method Map class is used to obtain an element in the map having specified key? a) search() b) get() c) set() d) look()

a

Which of these method is used add an element and corresponding key to a map? a) put() b) set() c) redo() d) add()

a

Which of these method of HashSet class is used to add elements to its object? a) add() b) Add() c) addFirst() d) insert()

a

Which of these methods is used to retrieve elements in BitSet object at specific location? a) get() b) Elementat() c) ElementAt() d) getProperty()

a

Which of these standard collection classes implements all the standard functions on list data structure? a) Array b) LinkedList c) HashSet d) AbstractSet

a

A directory

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

end-of-file marker

a count of the total bytes in the file that is recorded in a system-maintained administrative data structure

2 ideal usages of optional

a) consumes the correct value b) produces an alternative

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

15.5 Q2: A serialized object is ________. a. an object represented as a sequence of bytes used to store the object's data in a file b. an object in memory that has been recreated from data in a file c. a standard output stream object used to convert objects in code to data in a file d. None of the above.

a. an object represented as a sequence of bytes used to store the object's data in a file.

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()

15.6 Q2: Which JFileChooser method returns the file the user selected? a. getSelectedFile. b. getFile. c. getOpenDialog. d. showOpenDialog.

a. getSelectedFile.

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

15.6 Q1: Which JFileChooser method specifies what users can select in the dialog? a. setFileSelectionMode b. setSelectionMode c. showOpenDialog d. None of the above

a. setFileSelectionMode.

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()

when error checking to ensure a valid file was attached, pick a technique that is appropriate to the situation

allow user to try again instead of aborting program

object serialization

an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

in a function prototype :

any type can be used as a formal parameter type or return type

Many programs

are "data processing" applications read the input data perform sequence of operations on this data write the output data

Files

are very useful for data processing application

file stream objects need to be:

attached to files before they can be used do this with member function open

The statement f1.write( (char*)&obj1, sizeof(obj1) ); a. writes the member functions of obj1 to f1. b. writes the data in obj1 to f1. c. writes the member functions and the data of obj1 to f1. d. writes the address of obj1 to f1.

b

What is the output of this program? class Output { public static void main(String args[]) { ArrayList obj = new ArrayList(); obj.add("A"); obj.add("D"); obj.ensureCapacity(3); obj.trimToSize(); System.out.println(obj.size()); } } a) 1 b) 2 c) 3 d) 4

b

What is the output of this program? import java.util.*; class Array { public static void main(String args[]) { int array[] = new int [5]; for (int i = 5; i > 0; i--) array[5 - i] = i; Arrays.sort(array); System.out.print(Arrays.binarySearch(array, 4)); } } a) 2 b) 3 c) 4 d) 5

b

What is the output of this program? import java.util.*; class Array { public static void main(String args[]) { int array[] = new int [5]; for (int i = 5; i > 0; i--) array[5 - i] = i; Arrays.sort(array); for (int i = 0; i < 5; ++i) System.out.print(array[i]);; } } a) 12345 b) 54321 c) 1234 d) 5432

b

Which of these classes implements Set interface? a) ArrayList b) HashSet c) LinkedList d) DynamicList

b

Which of these classes provide implementation of map interface? a) ArrayList b) HashMap c) LinkedList d) DynamicList

b

Which of these is the interface of legacy? a) Map b) Enumeration c) HashMap d) Hashtable

b

Which of these method is used to calculate number of bits required to hold the BitSet object? a) size() b) length() c) indexes() d) numberofBits()

b

Which of these method is used to make all elements of an equal to specified value? a) add() b) fill() c) all() d) set()

b

A C++ stream is a. the flow of control through a function. b. a flow of data from one place to another. c. associated with a particular class. d. a file.

b, c

Command-line arguments are a. disagreements in the military. b. typed following a program name at the command prompt. c. accessed through arguments to main(). d. accessible only from disk files.

b, c

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

b. BufferedWriter.newline();

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

15.3 Q1: Which of the following statements is false? a. A Path represents the location of a file or directory. b. Path objects open files and provide file-processing capabilities. c. Class Paths is used to get a Path object representing a file or directory location. d. The static method get of class Paths converts a String representing a file's or directory's location into a Path object.

b. Path objects open files and provide file-processing capabilities. Actually, Path objects do not open files nor do they provide any file-processing capabilities. They specify only the location of a file or directory.

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

b. Reader

15.7.1 Q3: Which of the following statements is false? a. With a BufferedOutputStream each output operation is directed to a buffer large enough to hold the data of many output operations. Transfer to the output device is performed in one large physical output operation when the buffer fills. b. With a BufferedOutputStream, a partially filled buffer can be forced out to the device at any time by invoking the stream object's force method. c. With a BufferedInputStream, many "logical" chunks of data from a file are read as one large physical input operation into a memory buffer. d. With a BufferedInputStream, as a program requests data, it's taken from the buffer. When the buffer is empty, the next actual physical input operation is performed.

b. With a BufferedOutputStream, a partially filled buffer can be forced out to the device at any time by invoking the stream object's force method. Actually, it's the flush method

15.2 Q3: Streams that input bytes from and output bytes to files are known as ________. a. bit-based streams b. byte-based streams c. character-based streams d. Unicode-based streams

b. byte-based streams

15.3 Q6: Files static method ________ receives a Path and returns a boolean indicating whether that Path represents a directory on disk. a. isDiskDirectory b. isDirectory c. isFileDirectory d. isPath

b. isDirectory

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()

15.3 Q4: A(n) ________ path starts from the directory in which the application began executing. a. absolute b. relative c. parallel d. comparative

b. relative.

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

15.5 Q3: Adding the services of one stream to another is known as ________. a. chaining b. wrapping c. adding d. sequencing

b. wrapping.

passing behavior

behavior - block of code to be executed

boolean reduction operations

boolean allMatch(Predicate<? super T> predicate) - returns true if empty stream boolean anyMatch(Predicate<? super T> predicate) - retruns false if empty stream boolean noneMatch(Predicate<? super T> predicate) - returns true if empty stream **short-circuit terminal operations

optional methods for consuming values

boolean isPresent() void ifPresent(Consumer<? super T> consumer)

What is the output of this program? import java.util.*; class Array { public static void main(String args[]) { int array[] = new int [5]; for (int i = 5; i > 0; i--) array[5-i] = i; Arrays.fill(array, 1, 4, 8); for (int i = 0; i < 5 ; i++) System.out.print(array[i]); } } a) 12885 b) 12845 c) 58881 d) 54881

c

What is the output of this program? import java.util.*; class Bitset { public static void main(String args[]) { BitSet obj1 = new BitSet(5); BitSet obj2 = new BitSet(10); for (int i = 0; i < 5; ++i) obj1.set(i); for (int i = 3; i < 13; ++i) obj2.set(i); obj1.and(obj2); System.out.print(obj1); } } a) {0, 1} b) {2, 4} c) {3, 4} d) {3, 4, 5}

c

Which of these is a method of class Date which is used to search weather object contains a date before the specified date? a) after() b) contains() c) before() d) compareTo()

c

Which of these method is used to change an element in a LinkedList Object? a) change() b) set() c) redo() d) add()

c

Which of these method of Array class is used sort an array or its subset? a) binarysort() b) bubblesort() c) sort() d) insert()

c

Which of these methods can be used to delete the last element in a LinkedList object? a) remove() b) delete() c) removeLast() d) deleteLast()

c

Which of these standard collection classes implements a dynamic array? a) AbstractList b) LinkedList c) ArrayList d) AbstractSet

c

15.3 Q3: Which of the following statements is false? a. A DirectoryStream enables a program to iterate through the contents of a directory. b. Character-based input and output can be performed with classes Scanner and Formatter. c. A relative path contains all the directories, starting with the root directory, that lead to a specific file or directory. d. Every file or directory on a disk drive has the same root directory in its path.

c. A relative path contains all the directories, starting with the root directory, that lead to a specific file or directory. Actually, an absolute path contains all the directories, starting with the root directory, that lead to a specific file or directory.

15.3 Q2: Class ________ provides static methods for common file and directory manipulations, including methods for 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. a. File b. FileAndDirectory c. Files d. FilesAndDirectories

c. Files

15.4.2 Q1: What does the following statement do? Scanner scanner = new Scanner(Paths.get("test.txt")); a. Opens a binary file for input. b. Opens a binary file for output. c. Opens a text file for input. d. Opens a text file for output.

c. Opens a text file for input.

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

15.2 Q2: How do methods setIn, setOut and setErr affect the standard input, output and error streams? a. They output data to the standard input, output and error streams. b. They provide the only way to access the standard input, output and error streams. c. They redirect the standard input, output and error streams. d. They empty the standard input, output and error streams.

c. They redirect the standard input, output and error streams.

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

c. abstract

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()

File streams

can be used to input and output data as bytes or characters

Path Object

cannot open a file

read in char ch1,ch2 using no parameter and using parameter version

ch1= cin.get(); ch2=cin.get(); cin.get(ch1).get(ch2);

text files

character-based streams

typeName variableName;

className objectName;

how to create parallelism in stream

collection.parallelStream() stream.parallel()

absolute path

contains all directories, starting with the root directory, that lead to a specific file or directory.

binary file

contains unformatted data, saved in its raw memory format ex: the int 123456789 is saved as a 4-byte chunk of data, the sames as its stored in memory--NOT as the 9 digits as shown

What is the output of this program? import java.util.*; class Linkedlist { public static void main(String args[]) { LinkedList obj = new LinkedList(); obj.add("A"); obj.add("B"); obj.add("C"); obj.addFirst("D"); System.out.println(obj); } } a) [A, B, C] b) [D, B, C] c) [A, B, C, D] d) [D, A, B, C]

d

What is the output of this program? import java.util.*; class Maps { public static void main(String args[]) { TreeMap obj = new TreeMap(); obj.put("A", new Integer(1)); obj.put("B", new Integer(2)); obj.put("C", new Integer(3)); System.out.println(obj.entrySet()); } } a) [A, B, C] b) [1, 2, 3] c) {A=1, B=2, C=3} d) [A=1, B=2, C=3]

d

What is the output of this program? import java.util.*; class hashtable { public static void main(String args[]) { Hashtable obj = new Hashtable(); obj.put("A", new Integer(3)); obj.put("B", new Integer(2)); obj.put("C", new Integer(8)); System.out.print(obj.contains(new Integer(5))); } } a) 0 b) 1 c) true d) false

d

What is the output of this program? import java.util.*; class vector { public static void main(String args[]) { Vector obj = new Vector(4,2); obj.addElement(new Integer(3)); obj.addElement(new Integer(2)); obj.addElement(new Integer(5)); obj.insertElementAt(new Integer(8), 2); System.out.println(obj); } } a) [3, 2, 6] b) [3, 2, 8] c) [3, 2, 6, 8] d) [3, 2, 8, 6]

d

What is the output of this program? import java.util.*; class Output { public static void main(String args[]) { TreeSet t = new TreeSet(); t.add("3"); t.add("9"); t.add("1"); t.add("4"); t.add("8"); System.out.println(t); } } a) [1, 3, 5, 8, 9] b) [3, 4, 1, 8, 9] c) [9, 8, 4, 3, 1] d) [1, 3, 4, 8, 9]

d

What is the output of this program? import java.util.*; class Maps { public static void main(String args[]) { HashMap obj = new HashMap(); obj.put("A", new Integer(1)); obj.put("B", new Integer(2)); obj.put("C", new Integer(3)); System.out.println(obj); } } a) {A 1, B 1, C 1} b) {A, B, C} c) {A-1, B-1, C-1} d) {A=1, B=2, C=3}

d

Which of these class object can be used to form a dynamic array? a) ArrayList b) Map c) Vector d) ArrayList & Map

d

Which of these class object uses key to store value? a) Dictionary b) Map c) Hashtable d) All if the mentioned

d

Which of these is a class which uses String as a key to store the value in object? a) Array b) ArrayList c) Dictionary d) Properties

d

Which of these method can be used to increase the capacity of ArrayList object manually? a) Capacity() b) increaseCapacity() c) increasecapacity() d) ensureCapacity()

d

15.5.2 Q1: When using an ObjectInputStream to read data from a file, what happens when an end-of-file marker is reached? a. Nothing occurs. b. An end-of-file character is read by the program. c. Method readObject returns the value 0. d. An EOFException is thrown.

d. An EOFException is thrown.

15.7.1 Q2: ________ is an I/O-performance-enhancement technique—it reduces the number of I/O operations by combining smaller outputs together in memory; the number of physical I/O operations is much smaller than the number of I/O requests issued by the program. a. Aggregating b. Accumulating c. Amassing d. Buffering

d. Buffering.

You can use Java's ____ class to create your own random access files. a. Path b. FileStream c. File d. FileChannel

d. FileChannel

15.4.1 Q2: When all the contents of a file are truncated, this means that ________. a. the data in the file is saved to a backup file b. the file is deleted c. a FileNotFoundException occurs d. all the data in the file is discarded

d. all the data in the file is discarded

A ____ is a group of characters that has some meaning. a. record b. file c. byte d. field

d. field

15.3 Q5: Path method ________ returns the String name of a file or directory without any location information. a. getStringName b. getFileOrDirectoryName c. getDirectoryName d. getFileName

d. getFileName

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()

"cout" command

does binary to ascii conversion on variable prints output charcters to screen does not print any spaces before or after variable

stream manipulators are alternate ways of

doing tasks performed by member functions. benefit: cascading

to call upon a member function

dot-operator

logic error

error made when using \ as a directory sparator rather than \\ in a string literal

appending

existing files can be opened for output, so that the new output is tacked on to the end

get()

extract next single character and does not skip white space

Write a statement that moves the current position 13 bytes backward in a stream object called f1.

f1.seekg(-13, ios::cur);

you can pass variable type of parent into function parameters of child

false

Creating Directories: 2 useful File utility methods

- mkdir( ) - mkdirs()

Byte Streams

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

How we read and write this data is a key part of program

... Currently we are using cin and cout for input / output ... Input stream "cin" is used to read user input ... Output stream "cout " is used to print program output ... This is only effective for small quantities of data

FILES

... provide long term storage of valuable information ... can contain large quantities o data ... can be viewed and modified by text editors ... can be read and written by programs

2. Character Streams

1. All character stream classes are descended from *Reader and Writer*. 2. character stream classes that specialize in file I/O: *FileReader and FileWriter*. The constructors of these class assume that the default character encoding and the default byte-buffer size.

How do you create a file output stream object?

1. FileOutputStream(file1) - creates a file output stream to write data to file1 2. FileOutStream(pathname)

DatagramSocketImpl

Abstract datagram and multicast socket implementation base class.

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.

While serializing you want some of the members not to serialize? How do you achieve it?

Another frequently asked Serialization interview question. This is also asked as what is the use of transient variable, does transient and static variable gets serialized or not etc. so if you don't want any field to be part of object's state then declare it either static or transient based on your need and it will not be included during Java serialization process.

Character

Any of the letters, numbers, or other special symbols (such as punctuation marks) that comprise data. Also, they are made up of bits

Streams

Assembly line process a collection (source) like a stream Operations - aggregate and terminal operation

What should you always do before creating a file?

Check to see if it exists. This is a good habit. try{ if(!file.exist()){ create file } }

15.7.2 Q2: Which of the following statements is false? a. A LineNumberReader is a buffered character stream that tracks the number of lines read. b. Classes FileReader and FileWriter perform character-based file I/O. c. Class PipedReader and class PipedWriter implement piped-character streams for transferring data between threads. d. Class StringReader and StringWriter read characters from and write characters to Streams, respectively.

Class StringReader and StringWriter read characters from and write characters to Streams, respectively. Actually, class StringReader and StringWriter read characters from and write characters to Strings, respectively.

Files

Class to get information about a file

ObjectInputStream and ObjectOutputStream

Classes (package java.io). which respectively implement the ObjectInput and ObjectOutput interfaces, enable entire objects to be read from or written to a stream

objectinputstream and object output stream

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object

collectors - reducing overloaded

Collectors.reducing(T seed, BinaryOperator<T> op) Collectors.reducing(U identity, Function<? super T,? extends U> mapper, BinaryOperator<U> op)

Sequential access file

Each record is read in order of its position in the file. Each record is stored in order based on the value of the key field

Random access

Efficient because it allows arbitrary access to files. It can only be used on files that support it.

(cin >> variable) is NOT successful when

End of file has been reached Exp: if user enters control-d Unexpected character encountered when reading variable Exp: if user types in "hello" instead of an integer

StreamReader, StreamWriter, and FileStream

File Processing classes

What is a stream (generally speaking)?

Flow of data Sequence of data and bytes or uni-code characters in some sort of sequential queue.

What does flush() do?

Flushes all the data written to the output stream to the destination. Bytes written to output stream may not have been fully written to storage yet. There is a chance data might be stored in memory somewhere. Calling flush guarantees any buffer data is flushed a.k.a written to the file

Predicate

Functional interface that checks if element passes a test. Good for filtering

Stream

Functions as a pipeline or channel between an input device and an application

File position pointer

Holds the byte number of the next byte to be read

For sorting a stream, there are several variations of the sorted method. One works for streams of Comparable elements, and another accepts a Comparator. Stream<String> longestFirst = words.stream().sorted(Comparator.comparing(String::length).reversed());

How to sort a stream?

MalformedURLException, IOException

If JEditorPane method setPage downloads an invalid URL it throws _________. If there is an error it throws __________

EOFException

If an ObjectInputStream is used to read information from the server, an __________ is generated when the client attempts to read a value from a stream on which end-of-stream is detected

Purpose

Lambda expressions let you express instances of single-method classes more compactly. To treat functionality as method argument, or code as data.

Sequential access

Less efficent due to the linear BigO

Functional Interface

One abstract method Many default methods @FunctionalInterface

Pipe lining

Operations can be viewed as a database-like query on the data source.

3 ways to create Optional<T>

Optional.of(T t) Optional.empty() Optional.ofNullable(T t)

ObjectStreamClass

Serialization's descriptor for classes.

False

T or F: UDP is a connection-oriented protocol

False

T or F: With datagram sockets a process establishes a connection to another process

True

T or F: With stream sockets, a process establishes a connection to another process. Data flows in stream. Connection oriented service

optional methods for producing alternative

T orElse(T other) T orElseGet(Supplier<? extends T> other) <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable

overloaded of reduce()

T reduce(T identity, BinaryOperator<T> accumulator) T reduce(T identity, BinaryOperator<T> accumulator) <U> U reduce( U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner) e.g. int result = words.reduce(0, (total, word) -> total + word.length(), (total1, total2) -> total1 + total2);

If an object contains other types of objects as fields, saving its contents can be complicated.

TRUE

If the object is set up properly, even the other objects that it might contain as fields are automatically serialized.

TRUE

It is used only to let the Java compiler know that objects of the class might be serialized.

TRUE

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

TRUE

The resulting set of bytes can be saved to a file for later retrieval.

TRUE

OutPutStream

The OutputStream is used for writing data to a destination.

try/catch block

The ________ tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException.

*NOTE*

The above two I/o are less efficient as each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity. To Overcome this Buffer I/O is implemented in Java.

SocketImpl

The abstract class SocketImpl is a common superclass of all classes that actually implement sockets.

URLConnection

The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL.

URLStreamHandler

The abstract class URLStreamHandler is the common superclass for all stream protocol handlers.

Socket

The allows the server to interact with the client.

InetSocketAddress

This class implements an IP Socket Address (IP address + port number) It can also be a pair (hostname + port number), in which case an attempt will be made to resolve the hostname.

ByteArrayOutputStream

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

FilterOutputStream

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

URLClassLoader

This class loader is used to load classes and resources from a search path of URLs referring to both JAR files and directories.

What are some properties of the FileOutputStream?

This class makes it possible to write to a file as a stream of bytes

InterfaceAddress

This class represents a Network Interface address.

NetworkInterface

This class represents a Network Interface made up of a name, and a list of IP addresses assigned to this interface.

SocketAddress

This class represents a Socket Address with no protocol attachment.

DatagramPacket

This class represents a datagram packet.

f.seek(n);

To move pointer to a certain byte

15.7.1 Q1: Which of the following statements is false? a. InputStream and OutputStream are abstract classes for performing byte-based I/O. b. Tubes are synchronized communication channels between threads. c. A filter stream provides additional functionality, such as aggregating data bytes into meaningful primitive-type units. FilterInputStream and FilterOutputStream are typically extended, so some of their filtering capabilities are provided by their concrete subclasses. d. A PrintStream performs text output. System.out and System.err are PrintStreams.

Tubes are synchronized communication channels between threads. Actually, pipes are synchronized communication channels between threads.

URLs (Uniform Resource Locators).

URIs that specify the locations of documents are called

What code do you need to use if any code is being access by multiple threads?

Use synchronize.

Exception handling in lambdas

Use wrapper lambdas

The call stream.limit(n) returns a new stream that ends after n elements (or when the original stream ends, if it is shorter). This method is particularly useful for cutting infinite streams down to size. Stream<Double> randoms = Stream.generate(Math::random).limit(100);

What does stream.limit(n) do?

The call stream.skip(n) does the exact opposite of stream.limit(n): It discards the first n elements. This is handy when splitting text into words since, due to the way the split method works, the first element is an unwanted empty string. Stream<String> words = Stream.of(contents.split("\\PL+")).skip(1);

What does stream.skip(n) do?

File object

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

Mode bits such as app and ate a. are defined in the ios class. b. can specify if a file is open for reading or writing. c. work with the put() and get() functions. d. specify ways of opening a file.

a, b, d

15.7.2 Q1: The ________ abstract classes are Unicode character-based streams. a. Reader and Writer b. BufferedReader and BufferedWriter c. CharArrayReader and CharArrayWriter d. UnicodeReader and UnicodeWriter

a. Reader and Writer

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

convert primitive stream to Stream

boxed() mapToObj(IntFunction<? extends U> mapper) mapToObj(LongFunction<? extends U> mapper) mapToObj(DoubleFunction<? extends U> mapper)

To write data that contains variables of type float to an object of type ofstream, you should use a. the insertion operator. b. seekg(). c. write(). d. put().

c

some new stream manipulators that correspond to formatting flags

cout.setf(ios::left); is: cout<<left;

set width with a member function and with a stream manipulator

cout.width(); cout<< setw();

default way for opening output file

create brand new file and begin writing from begining

how to get a user entered file name

create space for filename to be stored. C-STYLE STRING char filename[20]; cin>>filename ofstream fout; fout.open(filename);

Which of these are legacy classes? a) Stack b) Hashtable c) Vector d) All of the mentioned

d

True or false: A file pointer always contains the address of the file.

false; file pointer can be a synonym for current position

data needs to be stored somewhere when program is not running thats why we need

file input/output

Write a statement that writes a single character to an object called fileOut, which is of class ofstream.

fileOut.put(ch); (where ch is the character)

binary files

files created using byte-based streams

FilterOutputStream

filters an OutputStream.

collectors - groupingBy

groupingBy(Function<T, K> classifier) groupingBy(Function<T, K> classifier, Collector downstream) groupingBy(Function<T,K> classifier, Supplier<M> mapFactory, Collector downstream) e.g. Map<String, List<Locale>> countryToLocales = locales.collect(Collectors.groupingBy(Locale::getCountry)); Map<String, City> stateToLargestCity = cities.collect(groupingBy(City::getState, maxBy(Comparator.comparing(City::getPopulation))));

test true and false of stream object

if(!in1) { cout<<"sorry bad file"; }

3 ways to use ignore

ignore() -skips one char ignore(3)- skips 3 char ignore(3,'\n')- reads until new line max 3 characters

input filestream usage like cin:

int x, y, z; double a, b, c; in1 >> x >> y >> z; // read 3 ints from file in1 >> a >> b >> c; //reads 3 doubles from file

Connectionless transmission with datagrams

is more like the way mail is carried via the postal service. If a large message will not fit in one envelope, you break it into separate pieces that you place in sequentially numbered envelopes. All of the letters are then mailed at once. The letters could arrive in order, out of order or not at all (the last case is rare).

separator character

is used to separate directories and files in a path.

cin is an __input stream representing

istream

Write the declarator for the overloaded >> operator that takes output from an object of class istream and displays it as the contents of an object of class Sample.

istream& operator >> (istream&, Sample& )

if file with same name exitsts

it will be overwritten

object serialization

java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object

Collectors.mapping

mapping(Function, Collector)

since it is possible for open( ) to fail :

one should always check to make sure there's a valid file attached test the true/false value of the stream object itself a stream that is not attached to a valid file will evaluate to "false" if(!in1) //if in1 not attached to valid file input, abort { cout << "Sorry, bad file."; exit(0); // req <cstdlib> }

appending

opening an existing file for output and tacking the new output on to the end

Java program

opens a file by creating an object and associating a stream of bytes or characters with it.

declare cout and cin

ostream cout; istream cin;

parents and childs of class type

ostream is parent of ofstream istream is parent of ifstream

stream classes in a function

ostream&, istream&, ofstream&, ifstream& can be return type or parameter type

output file stream usage is like cout

out1 << "Hello, world"; out1 << "x + y =" << x + y;

Character-based streams

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.

True or false: Some streams work with input, and some with output.

true

File.separator

use to obtain the local computer's proper seperator character rather than explicitly using /or\.

Object

variable that contains data and has functions associated with it

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

How do you write a byte to an output stream? How do you write multiple bytes to output stream?

write(byte) write(byte[ ])

write method (binary)

writes a single byte

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)

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.

YAML

--- id: 123 title: Object Thinking author: David West published: by: Microsoft Press year: 2004

define stateful vs stateless operation

-incorporate state from previously processed elements when processing the current element -cannot be processed individually, they need to be compared with one another thus requiring information to be retained -can be processed without the need for sharing information between them for processing -retain no state during the execution of the pipeline.

For the File Input Stream, what are some commonly used constructors?

1. File Input Stream (File file) -creates a File input stream by opening a connection to a File object 2. FileInputStream(String pathname) -creates a FileInputStream by opening a connection to a file using its path

Flush in Buffer Steams

1. Flush is valid for only Output streams. 2. Some buffered output classes support autoflush, specified by an optional constructor argument 3. When auto-flush is enabled certain key events cause the buffer to be flushed. e.g autoflush Printwriter object flushes the buffer on every invocation of println or format.

NOTE

1. Programs use byte streams to perform input and output of 8-bit bytes 2. All byte stream classes are descended from InputStream and OutputStream abstract classes. 3. all other stream types are built on byte streams. 4. Byte stream classes that specialize in file I/O: FileInputStream and FileOutputStream are concreate samples of Byte steam. We also have many for different purposes. 5. Its always good practice to close opened stream in finally block.

Closeable

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

LineNumberReader

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

collectors - string

Collectors.joining() Collectors.joining(CharSequence delimiter) Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

collectors - optional

Collectors.maxBy(Predicate<T> test) Collectors.minBy(Predicate<T> test) Collectors.reducing(BinaryOperator<T> op)

collectors - partitioningBy

Collectors.partitioningBy(Predicate<T> classifier) Collectors.partitioningBy(Predicate<T> classifier, Collector downstreamCollector) e.g. Map<Boolean, List<Locale>> englishAndOtherLocales = locales.collect(Collectors.partitioningBy(l -> l.getLanguage().equals("en"))); List<Locale>> englishLocales = englishAndOtherLocales.get(true);

collectors - statistics

Collectors.summarizingInt(ToIntFunction<? super T> mapper) Collectors.summarizingLong(ToLongFunction<? super T> mapper) Collectors.summarizingDouble(ToDoubleFunction<? super T> mapper) double averagingInt|Long|Double(ToInt|Long|DoubleFunction mapper) int|long|double summingXYZ(ToInt|Long|DoubleFunction mapper) e.g. IntSummaryStatistics summary = words.collect(Collectors.summarizingInt(String::length)); void accept(int value) - i/l void accept(long value) - l void accept(double value) - d double getAverage() long getCount(); int|long|double getMax(); int|long|double getMin(); long|double getSum(); void combine(Int|Long|DoubleSummaryStatistics other)

collectors - maps (terminal operation)

Collectors.toMap(Function<T,R> keyMapper, Function<T,R> valueMapper) Collectors.toMap(Function<T,R> keyMapper, Function<T,R> valueMapper, BinaryOperator<U> mergeFunction) Collectors.toMap(Function<T,R> keyMapper, Function<T,R> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M extends Map> mapSupplier) e.g. Map<Integer, String> personNameMap = persons.collect(Person::getId, Person::getName); Map<Integer, Person> personMap = persons.collect(Person::getId, Function.identity()); Map<Integer, Person> personTreeMap = persons.collect(Person::getId, Function.identity(), TreeMap::new);

basic collectors

Collectors.toSet() Collectors.toList() Collectors.toCollection(Supplier<T> t) Collectors.counting() e.g. Collectors.toCollection(TreeSet::new)

C.R.U.D

Create Retrieve Update Delete

Suppose you have a class which you serialized it and stored in persistence and later modified that class to add a new field. What will happen if you deserialize the object already serialized?

It depends on whether class has its own serialVersionUID or not. As we know from above question that if we don't provide serialVersionUID in our code java compiler will generate it and normally it's equal to hashCode of object. by adding any new field there is chance that new serialVersionUID generated for that class version is not the same of already serialized object and in this case Java Serialization API will throw java.io.InvalidClassException and this is the reason its recommended to have your own serialVersionUID in code and make sure to keep it same always for a single class.

Connection-oriented transmission

It is like the telephone system. You dial and are given a connection to the telephone of the person with whom you wish to communicate. The connection is maintained for your phone call, even when you're not talking.

If a class is Serializable but its super class is not, what will be the state of the instance variables inherited from super class after deserialization?

Java serialization process only continues in object hierarchy till the class is Serializable i.e. implements Serializable interface in Java and values of the instance variables inherited from super class will be initialized by calling a constructor of Non-Serializable Super class during deserialization process. Once the constructor chaining is started it wouldn't be possible to stop that, hence even if classes higher in hierarchy implements Serializable interface, their constructor will be executed. As you see from the statement this Serialization interview question looks very tricky and tough but if you are familiar with key concepts it's not that difficult.

What is serialVersionUID? What would happen if you don't define this?

One of my favorite question interview question on Java serialization. SerialVersionUID is an ID which is stamped on object when it get serialized usually hashcode of object, you can use tool serialver to see serialVersionUID of a serialized object . SerialVersionUID is used for version control of object. you can specify serialVersionUID in your class file also. Consequence of not specifying serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch, to learn more about serialversionuid see this article.

What will happen if one of the members in the class doesn't implement Serializable interface?

One of the easy question about Serialization process in Java. If you try to serialize an object of a class which implements Serializable, but the object includes a reference to a non- Serializable class then a 'NotSerializableException' will be thrown at runtime and this is why I always put a SerializableAlert (comment section in my code), one of the code comment best practices, to instruct developer to remember this fact while adding a new field in a Serializable class.

optional reduction operations

Optional<T> max(Comparator<? super T> comparator) Optional<T> min(Comparator<? super T> comparator) Optional<T> findAny() Optional<T> findFirst() Optional<T> reduce(BinaryOperator<T> accumulator) e.g. values.reduce((x,y) -> x+y)

What kind of stream would you use to write data from a program?

Output stream

Draw an Output stream diagram

PROGRAM ---> OUTPUT STREAM ---> DESTINATION (Dest. could be File, Storage unit) In the output stream there is data that is waiting to be produced into something

ProtocolFamily

Represents a family of communication protocols.

CacheRequest

Represents channels for storing resources in the ResponseCache.

ResponseCache

Represents implementations of URLConnection caches.

in.readObject();

Requires a cast if a type is declared Throws a ClassNotFoundException

Draw an Input stream diagram

SOURCE ---> INPUT STREAM ---> PROGRAM In the input stream there is data that is waiting to be consumed by something, in this case, the program

Standard Streams

STDIN, STDOUT and STDERR.

hasNext

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

When an object is serialized, it is converted into a series of bytes that contain the object's data.

TRUE

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.

methods to deal with object stream

The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out − public final void writeObject(Object x) throws IOException The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object − public final Object readObject() throws IOException, ClassNotFoundException This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type.

Can you Customize Serialization process or can you override default Serialization process in Java?

The answer is yes you can. We all know that for serializing an object ObjectOutputStream.writeObject (saveThisobject) is invoked and for reading object ObjectInputStream.readObject() is invoked but there is one more thing which Java Virtual Machine provides you is to define these two methods in your class. If you define these two methods in your class then JVM will invoke these two methods instead of applying default serialization mechanism. You can customize behavior of object serialization and deserialization here by doing any kind of pre or post processing task. Important point to note is making these methods private to avoid being inherited, overridden or overloaded. Since only Java Virtual Machine can call private method integrity of your class will remain and Java Serialization will work as normal. In my opinion, this is one of the best question one can ask in any Java Serialization interview, a good follow-up question is why should you provide a custom serialized form for your object?

Notice that for a class to be serialized successfully, two conditions must be met

The class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

What are the compatible changes and incompatible changes in Java Serialization Mechanism?

The real challenge lies with the change in class structure by adding any field, method or removing any field or method is that with an already serialized object. As per Java Serialization specification adding any field or method comes under compatible change and changing class hierarchy or UN-implementing Serializable interfaces some under non-compatible changes. For the complete list of compatible and non-compatible changes, I would advise reading Java serialization specification.

Proxy

This class represents a proxy setting, typically a type (http, socks) and a socket address.

DatagramSocket

This class represents a socket for sending and receiving datagram packets.

FilePermission

This class represents access to a file or directory.

SocketPermission

This class represents access to a network via sockets.

InetAddress

This class represents an Internet Protocol (IP) address.

Inet4Address

This class represents an Internet Protocol version 4 (IPv4) address.

Inet6Address

This class represents an Internet Protocol version 6 (IPv6) address.

Text files

This contains facts and figures, and also called data files

URLStreamHandlerFactory

This interface defines a factory for URL stream protocol handlers.

ContentHandlerFactory

This interface defines a factory for content handlers.

DatagramSocketImplFactory

This interface defines a factory for datagram socket implementations.

SocketImplFactory

This interface defines a factory for socket implementations.

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.

Which methods are used during Serialization and DeSerialization process in Java?

This is very common interview question in Serialization basically interviewer is trying to know; Whether you are familiar with usage of readObject(), writeObject(), readExternal() and writeExternal() or not. Java Serialization is done by java.io.ObjectOutputStream class. That class is a filter stream which is wrapped around a lower-level byte stream to handle the serialization mechanism. To store any object via serialization mechanism we call ObjectOutputStream.writeObject(saveThisobject) and to deserialize that object we call ObjectInputStream.readObject() method. Call to writeObject() method trigger serialization process in java. one important thing to note about readObject() method is that it is used to read bytes from the persistence and to create object from those bytes and its return an Object which needs to be type cast to correct type.

Which kind of variables is not serialized during Java Serialization?

This question asked sometime differently but the purpose is same whether Java developer knows specifics about static and transient variable or not. Since static variables belong to the class and not to an object they are not the part of the state of the the object so they are not saved during Java Serialization process. As Java Serialization only persist the state of an object and not object itself. Transient variables are also not included in java serialization process and are not the part of the object's serialized state. After this question sometimes interviewer ask a follow-up if you don't store values of these variables then what would be a value of these variable once you deserialize and recreate those object? This is for you guys to think about.

What is multi-threading?

Two or more tasks executing in a program. Many threads can run concurrently in a program.

connectionless

UDP—the User Datagram Protocol—is a _________service. Packets are not guaranteed to be in order. Not as reliable as TCP

The distinct method returns a stream that yields elements from the original stream, in the same order, except that duplicates are suppressed. Stream<String> uniqueWords = Stream.of("merrily", "merrily", "merrily", "gently").distinct();

What does distinct method do?

The reduce method is a general mechanism for computing a value from a stream. The simplest form takes a binary function and keeps applying it, starting with the first two elements. List<Integer> values = . . .; Optional<Integer> sum = values.stream().reduce((x, y) -> x + y); In this case, the reduce method computes v0 + v1 + v2 + . . . , where the vi are the stream elements. The method returns an Optional because there is no valid result if the stream is empty. Often, there is an identity value e such that e op x = x, and you can use that element as the start of the computation. For example, 0 is the identity value for addition. Then call the second form of reduce List<Integer> values = . . .; Integer sum = values.stream().reduce(0, (x, y) -> x + y); The identity value is returned if the stream is empty, and you no longer need to deal with the Optional class.

What does reduce method do?

A stream transformation produces a stream whose elements are derived from those of another stream. - filter() - filter transformation yields a stream with those elements that match a certain condition. Stream<String> longWords = wordList.stream().filter(w -> w.length() > 12); - map() - Often, you want to transform the values in a stream in some way. Use the map method and pass the function that carries out the transformation. Stream<String> lowercaseWords = words.stream().map(String::toLowerCase); When you use map, a function is applied to each element, and the result is a new stream with the results. -flatMap() - yields a stream obtained by concatenating the results of applying mapper to the elements of this stream. (Note that each result is a stream.)

What is stream transformation?

Can we transfer a Serialized object via network?

Yes you can transfer a Serialized object via network because Java serialized object remains in form of bytes which can be transmitter via network. You can also store serialized object in Disk or database as Blob.

the entire process is JVM independent

____ , meaning an object can be serialized on one platform and deserialized on an entirely different platform.

The ObjectOutputStream class

_____ contains many write methods for writing various data types, but one method in particular stands out public final void writeObject(Object x) throws IOException -serializes an Object and sends it to the output stream.

fter a serialized object has been written into a file

_____, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Stream, TCP

__________ sockets and the __________ protocol are more desirable for the vast majority of Java programmers.

What is the output of this program? import java.util.*; class hashtable { public static void main(String args[]) { Hashtable obj = new Hashtable(); obj.put("A", new Integer(3)); obj.put("B", new Integer(2)); obj.put("C", new Integer(8)); obj.clear(); System.out.print(obj.size()); } } a) 0 b) 1 c) 2 d) 3

a

What is the output of this program? import java.util.*; class stack { public static void main(String args[]) { Stack obj = new Stack(); obj.push(new Integer(3)); obj.push(new Integer(2)); obj.pop(); obj.push(new Integer(5)); System.out.println(obj); } } a) [3, 5] b) [3, 2] c) [3, 2, 5] d) [3, 5, 2]

a

Which of these class can generate an array which can increase and decrease in size automatically? a) ArrayList() b) DynamicList() c) LinkedList() d) DynamicList()

a

Which of these method is used to insert value and its key? a) put() b) set() c) insertElement() d) addElement()

a

Which of these method of ArrayList class is used to obtain present size of an object? a) size() b) length() c) index() d) capacity()

a

Which of these methods can be used to obtain a static array from an ArrayList object? a) Array() b) covertArray() c) toArray() d) covertoArray()

a

InputStream and OutputStream

are abstract classes that declare methods for performing byte-based input and output, respectively.

Classes ObjectInputStream and ObjectOutputStream

are high-level streams that contain the methods for serializing and deserializing an object.

Pipes

are synchronized communication channels between threads

What is the output of this program? import java.util.*; class Bitset { public static void main(String args[]) { BitSet obj = new BitSet(5); for (int i = 0; i < 5; ++i) obj.set(i); obj.clear(2); System.out.print(obj.length() + " " + obj.size()); } } a) 4 64 b) 5 64 c) 5 128 d) 4 128

b

What is the output of this program? import java.util.*; class Linkedlist { public static void main(String args[]) { LinkedList obj = new LinkedList(); obj.add("A"); obj.add("B"); obj.add("C"); obj.removeFirst(); System.out.println(obj); } } a) [A, B] b) [B, C] c) [A, B, C, D] d) [A, B, C]

b

What is the output of this program? import java.util.*; class Maps { public static void main(String args[]) { HashMap obj = new HashMap(); obj.put("A", new Integer(1)); obj.put("B", new Integer(2)); obj.put("C", new Integer(3)); System.out.println(obj.get("B")); } } a) 1 b) 2 c) 3 d) null

b

What is the output of this program? import java.util.*; class Output { public static void main(String args[]) { HashSet obj = new HashSet(); obj.add("A"); obj.add("B"); obj.add("C"); System.out.println(obj + " " + obj.size()); } } a) ABC 3 b) [A, B, C] 3 c) ABC 2 d) [A, B, C] 2

b

What is the output of this program? import java.util.*; class hashtable { public static void main(String args[]) { Hashtable obj = new Hashtable(); obj.put("A", new Integer(3)); obj.put("B", new Integer(2)); obj.put("C", new Integer(8)); obj.remove(new String("A")); System.out.print(obj); } } a) {C=8, B=2} b) [C=8, B=2] c) {A=3, C=8, B=2} d) [A=3, C=8, B=2]

b

What is the output of this program? import java.util.*; class properties { public static void main(String args[]) { Properties obj = new Properties(); obj.put("AB", new Integer(3)); obj.put("BC", new Integer(2)); obj.put("CD", new Integer(8)); System.out.print(obj.keySet()); } } a) {AB, BC, CD} b) [AB, BC, CD] c) [3, 2, 8] d) {3, 2, 8}

b

What is the output of this program? import java.util.*; class Arraylist { public static void main(String args[]) { ArrayList obj = new ArrayList(); obj.add("A"); obj.add("B"); obj.add("C"); obj.add(1, "D"); System.out.println(obj); } } a) [A, B, C, D] b) [A, D, B, C] c) [A, D, C] d) [A, B, C]

b

Which of these method is used to remove all keys/values pair from the invoking map? a) delete() b) remove() c) clear() d) removeAll()

b

Which of these object stores association between keys and values? a) Hash table b) Map c) Array d) String

b

Which of these standard collection classes implements a linked list data structure? a) AbstractList b) LinkedList c) HashSet d) AbstractSet

b

15.5 Q1: Which of the following classes enable input and output of entire objects to or from a file? A. SerializedInputStream B. SerializedOutputStream C. ObjectInputStream D. ObjectOutputStream E. Scanner F. Formatter a. A and B. b. C and D. c. C, D, E, F. d. E and F.

b. C and D.

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

15.4.4 Q1: Records in a sequential file are not usually updated in place. Instead ________. a. the updated data is placed in a "surrogate" file b. the entire file is usually rewritten c. the file is truncated d. The above statement is false—records in sequential files are usually updated in place.

b. the entire file is usually rewritten

other operations of Optional (similar to Stream)

boolean filter(Predicate<? super T> predicate) <U> Optional<U> map(Function<? super T, ? extends U> mapper) <U> Optional<U> flatMap(Function<? super T,Optional<U>> mapper) **flatMap - for chaining multiple map optional e.g. Double result = Optional.of (-4.0).flatMap(Test::inverse).flatMap(Test::squareRoot)

What is the name of data member of class Vector which is used to store number of elements in the vector? a) length b) elements c) elementCount d) capacity

c

What is the output of this program? import java.util.*; class Output { public static void main(String args[]) { ArrayList obj = new ArrayList(); obj.add("A"); obj.add(0, "B"); System.out.println(obj.size()); } } a) 0 b) 1 c) 2 d) Any Garbage Value

c

What is the output of this program? import java.util.*; class vector { public static void main(String args[]) { Vector obj = new Vector(4,2); obj.addElement(new Integer(3)); obj.addElement(new Integer(2)); obj.addElement(new Integer(5)); System.out.println(obj.capacity()); } } a) 2 b) 3 c) 4 d) 6

c

What is the output of this program? import java.util.*; class vector { public static void main(String args[]) { Vector obj = new Vector(4,2); obj.addElement(new Integer(3)); obj.addElement(new Integer(2)); obj.addElement(new Integer(5)); System.out.println(obj.elementAt(1)); } } a) 0 b) 3 c) 2 d) 5

c

What is the output of this program? import java.util.*; class vector { public static void main(String args[]) { Vector obj = new Vector(4,2); obj.addElement(new Integer(3)); obj.addElement(new Integer(2)); obj.addElement(new Integer(5)); obj.removeAll(obj); System.out.println(obj.isEmpty()); } } a) 0 b) 1 c) true d) false

c

What is the output of this program? import java.util.*; class Arraylist { public static void main(String args[]) { ArrayList obj1 = new ArrayList(); ArrayList obj2 = new ArrayList(); obj1.add("A"); obj1.add("B"); obj2.add("A"); obj2.add(1, "B"); System.out.println(obj1.equals(obj2)); } } a) 0 b) 1 c) true d) false

c

What is the output of this program? import java.util.*; class hashtable { public static void main(String args[]) { Hashtable obj = new Hashtable(); obj.put("A", new Integer(3)); obj.put("B", new Integer(2)); obj.put("C", new Integer(8)); System.out.print(obj.toString()); } } a) {C=8, B=2} b) [C=8, B=2] c) {A=3, C=8, B=2} d) [A=3, C=8, B=2]

c

15.4.3 Q1: Which of the following statements is true? a. Class Scanner provides the ability to reposition to the beginning of a file with method seek. b. Class Scanner provides the ability to reposition to the beginning of a file with method reposition. c. Class Scanner does not provide the ability to reposition to the beginning of the file. d. If it is necessary to read a sequential file again, the program can simply keep reading—when the end of the file is reached, the Scanner is automatically set to point back to the beginning of the file.

c. Class Scanner does not provide the ability to reposition to the beginning of the file.

____ 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

15.5.1 Q1: What interface must a class implement to indicate that objects of the class can be output and input as a stream of bytes? a. Synchronize b. Deserializable c. Serializable d. ObjectOutput

c. Serializable.

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

15.5.1 Q2: Instance variables that are not to be output with a Serializable object are declared using which keyword? a. private b. ignoreme c. transient d. persistent

c. transient

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{}

eof() can be used with which file stream object

cin

ostream and istream are

classes

Statelessness of functional programming

closures contradict this?

two collect terminal operations

collect(Collector collector) collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner) e.g. HashSet<String> result = stream.collect(HashSet::new, HashSet::add, HashSet::addAll);

set precision with a member function and a stream manipulator

cout.precision(); cout<<setprecision();

call char ch1= 'A', ch2='b'; cascading

cout.put(ch1).put(ch2);

We can output text to an object of class ofstream using the insertion operator << because a. the ofstream class is a stream. b. the insertion operator works with all classes. c. we are actually outputting to cout. d. the insertion operator is overloaded in ofstream.

d

What is the output of this program? import java.util.*; class date { public static void main(String args[]) { Date obj = new Date(); System.out.print(obj); } } a) Prints Present Date b) Runtime Error c) Any Garbage Value d) Prints Present Time & Date

d

Which of these method is used to add an element to the start of a LinkedList object? a) add() b) first() c) AddFirst() d) addFirst()

d

Which of these method is used to make a bit zero specified by the index? a) put() b) set() c) remove() d) clear()

d

Which of these method is used to reduce the capacity of an ArrayList object? a) trim() b) trimSize() c) trimTosize() d) trimToSize()

d

Which of these methods can be used to obtain set of all keys in a map? a) getAll() b) getKeys() c) keyall() d) keySet()

d

Which of these methods can be used to search an element in a list? a) find() b) sort() c) get() d) binaryserach()

d

Which of these methods is used to add elements in vector at specific location? a) add() b) set() c) AddElement() d) addElement()

d

Which of these methods is used to retrieve the elements in properties object at specific location? a) get() b) Elementat() c) ElementAt() d) getProperty()

d

15.3 Q7: Which of the following statements is false? a. Path method isAbsolute returns a boolean indicating whether a Path represents an absolute path to a file or directory. b. Files static method getLastModifiedTime receives a Path and returns a FileTime (package java.nio.file.attribute) indicating when the file was last modified. c. Files static method size receives a Path and returns a long representing the number of bytes in the file or directory. For directories, the value returned is platform specific. d. All of the above are true.

d All of the above are true.

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

15.1 Q1: Which of the following statements is false? a. Storage of data variables and arrays is temporary. b. Data is lost when a local variable "goes out of scope." c. Files are used for long-term retention of large amounts of data. d. Data maintained in files is often called transient data.

d. Data maintained in files is often called transient data.

15.2 Q1: Which of the following classes is not used for file input? a. FileInputStream b. FileReader c. ObjectInputStream d. Formatter

d. Formatter

15.4.1 Q1: Which statement regarding Java files is false? a. Java imposes no structure on a file. b. Notions like "record" do not exist in Java files. c. The programmer must structure files to meet the requirements of applications. d. Records in a Java sequential file are stored in order by record key.

d. Records in a Java sequential file are stored in order by record key.

to create a space to store a filename (as a c-style string)

declare a set of characters: char filename[20]; this declaration allows storage of a string of up to 19 characters a user can enter a single word name into this variable: cin >> filename; can use the variable in open( ) when attaching file to stream ofstream fout; fout.open(filename);

DataInput

describes methods for reading primitive types from an input stream.

Class JFileChooser

displays a dialog that enables the user to easily select files or directories.

stream intermediate operation that are stateful

distinct() sorted() sorted(Comparator<? super T> comparator) **all stateful

DataInputStream and RandomAccessFile

each implement this interface to read sets of bytes and process them as primitive-type values.

Class Formatter

enables formatted data to be output to any text-based stream in a manner similar to method System.out.printf.

member function to know when end of input file has been reached

eof() returns bool value usefule when reading files where size is not known

other terminal operations aside from collect

long count() void forEach(Consumer<? super T> action) void forEachOrdered(Consumer<? super T> action) Object[] toArray()<A> A[] toArray(IntFunction<A[]> generator) e.g. String[] result = words.toArray(String[]::new);

convert Stream to primitive stream

mapToInt(ToIntFunction<? super T> mapper) mapToLong(ToLongFunction<? super T> mapper) mapToDouble(ToDoubleFunction<? super T> mapper)

attributes

member data. data variables contained inside object

associated behaviors

member functions, functions called for an object

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.

Serializable

no methods, but a class has to implement in order to be written by writeObject If an object is saved twice, only one serial is stored

cout and cin are

objects

FormatterClosedException

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

NoSuchElementException

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

FileNotFoundException

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

SecurityException

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

<fstream> includes classes

ofstream and ifstream

call function to print data to files

ofstream because it is for files - ofstream out1; out1.open("txt1.txt"); PrintData(out1,2,3);

declare file stream objects:

ofstream i1; ifstream i2;

open "file.txt in append

ofstream in1; in1.open("file.txt",ios::app);

to declare file stream objects:

ofstream out1, bob; istream in1, joe;

Write a statement that will create an object called salefile of the ofstream class and associate it with a file called SALES.JUN.

ofstream salefile ("SALES.JUN");

Byte-based streams

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

cout is an __ stream representing

output stream; ostream

Formatter

outputs formatted Strings to the specified stream.

two types of stream manipulators

plain and parameterized. to include parameterized: <iomanip>

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

record

serialized object

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

peek()

returns ascii value of next character, does not extract

describe Optional get instance method

returns the wrapped element or NoSuchElementException

flush

rids of elements in a partially filled buffer

root directory

same for every file or directory on a particular disk drive

"cin" command

skips spaces and newlines before reading value then does ascii to binary conversion to read variable stops reading at space or non-matching character

Used with cin, what does the skipws flag accomplish?

skipws causes whitespace characters to be ignored on input so that cin will not assume the input has terminated.

enumerate stateful vs stateless operations

stateful -distinct() -sorted() / sorted(Comparator<T> c) -skip(long n) -limit(long n) stateless -all other

System.exit

static method terminates an application

Sequential-access files

store records in order by the record-key field.

random access file

stores records, all of the same size can read or write single records in place, without affecting the rest of the file

to create file stream objects, we need to include:

the <fstream> library #include <fstream> using namespace std; classes ofstream and istream


संबंधित स्टडी सेट्स

Personal Money Management (Final Exam Review)

View Set

Social Studies SS8H7: The New South

View Set

Introduction aux Sciences du langage et de la communication

View Set

Advantages/Disadvantages of Sole Proprietorship, Partnerships, and Corporations

View Set

Chapter 32: Assessment of Hematologic Function and Treatment Modalities

View Set