Java I/O, Streams and Threads

java.io package: buffers, streams, FileReader, Scanner, System.in/System.out. Links: basic I/O oracle tutorial, java io classes overview table, nice book

27 flashcards · Programming Languages · by lakesare

  1. System.out.println vs System.out.print?

    System.out.println puts a /n after printing a string.

  2. How to prompt user for input?

    import java.util.Scanner; Scanner scanner = new Scanner(System.in); String value = scanner.nextLine(); import java.util.Scanner; class EchoWithPromptNew{ public static void main(String[] args){ Scanner scanner = new Scanner(System.in); String value = scanner.nextLine(); System.out.println("You typed in " + value); } }

  3. Scanner scanner = new Scanner(System.in); String value = scanner.______() What are the possible methods?

    nextLine() - for string nextByte() nextShort() nextInt() nextLong() ... Links: docs

  4. Name 2 possible arguments for: import java.util.Scanner; Scanner in = new Scanner(???);

    new Scanner(new java.io.FileReader("fff.txt")); new Scanner(System.in);

  5. Both System.in and new FileReader() have a method .read() defined on them. What can .read() return? 1. System.in.read(); //=> ??? 2. FileReader fileReader = new FileReader("fff.dat"); fileReader.read(); //=> ???

    It always returns an int, either: Unicode int of character just read in -1 is we reached end of file. We must therefore cast the value just read in as a character in order to print it out properly.

  6. Byte stream VS character stream?

  7. FileReader class in Java vs in Js?

    Java: convenience class for reading files as character streams. Js: can read character/binary/etc files, but does not stream. Java's FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.

  8. What's a buffered stream?

    When BufferedReader prestreams characters into a buffer for performance (in order to avoid overhead of e.g. writing to disk). A program can convert an unbuffered stream into a buffered stream: inputStream = new BufferedReader(new FileReader("xanadu.txt")); Consider writing to a file. This is an expensive operation. If in your code you write one byte at a time, then each write of a byte is going to be very costly. So a common way to improve performance is to store the data that you are writing i…

  9. How does buffered output stream function?

    Buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

  10. What's a buffer flush?

    When we clear the buffer by outputting everything in it to the native API.

  11. What does scan function do in reactive programming?

    Scan is fundamentally similar to reduce but unlike reduce, returns all the intermediate accumulator values as a stream.

  12. java.io package is subdivided into classes that operate on byte streams and on character streams. Name their corresponding classes.

    Classes that operate: on byte streams: ...InputStream, ...OutputStream on character streams: ...Reader, ...Writer ___ Reader and InputStream define similar APIs but for different data types. For example, Reader contains these methods for reading characters and arrays of characters: int read() int read(char cbuf[]) int read(char cbuf[], int offset, int length) InputStream defines the same methods but for reading bytes and arrays of bytes: int read() int read(byte cbuf[]) int read(byte cbuf[], in…

  13. Streams can be subdivided into: connection streams chain streams What streams are these? FileOutputStream fileStream = new FileOutputStream('MyGame.ser'); ObjectOutputStream objectStream = new ObjectOutputStream(fileStream); objectStream.writeObject(someObject); objectStream.close()

    FileOutputStream - connection (connects to sources such as files or network sockets) ObjectOutputStream - chain (work only if chained to other streams)

  14. This is code to serialize someObject: FileOutputStream fileStream = new FileOutputStream('MyGame.ser'); ObjectOutputStream objectStream = new ObjectOutputStream(fileStream); objectStream.writeObject(someObject); objectStream.close(); What state of someObject is NOT saved in MyGame.ser?

    static variables transient variables

  15. What to do if you want to serialize an object of class that developer forgot to make implements Serializable?

    Subclass it and add implements Serializable to the subclass.

  16. Write a method that attempts to open a file and deserialize its contents into ArrayList<String>. public static ArrayList<String> deserialize(String filename){}

  17. How to wait for a request now? ServerSocket serverSocket = new ServerSocket(3000);

    Socket accept = serverSocket.accept(); Program is blocked until request comes in, and then method returns a sock on some anonymous port to communicate with the client.

  18. ServerSocket serverSocket = new ServerSocket(3000); Socket acceptSocket = serverSocket.accept(); Name 2 methods acceptSocket has.

    InputStream hi = acceptSocket.getInputStream(); OutputStream hi = acceptSocket.getOutputStream();

  19. Thread myThread = new Thread(threadJob); What's inside of threadJob argument?

    Instance of some class that implements Runnable interface. public class MyRunnable implements Runnable{ public void run(){} } Runnable threadJob = new MyRunnable(); Runnable is in the java.lang package, so we don't need to import it.

  20. Name 4 values (out of 6) from Thread.State Enum.

    NEW RUNNABLE BLOCKED WAITING TIMED_WAITING TERMINATED NEW – newly created thread that has not yet started the execution RUNNABLE – either running or ready for execution but it’s waiting for resource allocation BLOCKED – waiting to acquire a monitor lock to enter or re-enter a synchronized block/method WAITING – waiting for some other thread to perform a particular action without any time limit TIMED_WAITING – waiting for some other thread to perform a specific action for a specified period TERM…

  21. Create a thread in the NEW and RUNNABLE states.

    A NEW thread is a thread that’s been created but not yet started. It remains in this state until we start it using the .start() method. Thread t = new Thread(someRunnable); t.getState(); //=> NEW t.start(); t.getState(); //=> RUNNABLE

  22. What is the difference between BLOCKED and WAITING thread states?

    In the BLOCKED state, a thread is about to enter a synchronized block, but there is another thread currently running inside a synchronized block on the same object. The first thread must then wait for the second thread to exit its block. In the WAITING state, a thread is waiting for a signal from another thread. This happens typically by calling Object.wait(), or Thread.join(). The thread will then remain in this state until another thread calls Object.notify(), or dies. Any thread can enter th…

  23. What's a thread deadlock?

    Deadlock describes a situation where two or more threads are BLOCKED forever, waiting for each other to release a lock.

  24. Declare and reference an enum in java.

    public class Test { enum Level { LOW, MEDIUM, HIGH } public static void main(String[] args) { Level myVar = Level.MEDIUM; // related: take a note that we must NOT prefix enum's constants if we do switch with the enum! switch(myVar) { case LOW: System.out.println("Low level"); break; case MEDIUM: System.out.println("Medium level"); break; case HIGH: System.out.println("High level"); break; } } }

  25. Why use serialVersionUID?

    If you don't mention serialVersionUID, upon serialization it will get assigned to the automatically-generated hash based on class name and etc. If you change something else, you will get InvalidClassExceptions exception upon deserizaliation! To avoid it - set serialVersionUID yourself!

  26. What does myThread.join() do?

    Parent thread goes into a WAITING state until myThread thread terminates. Prevents the main thread from executing any further method until new myThread.join() is finished.

  27. How to make 2 threads run one after another?

    Right now both threads start, then thread_1 stops execution of the main method (.join()) while both threads are already running. (=> 0_0_1_1_2_2_3_3_4_4_5_5_6_6_7_7_8_8_9_9_10_10)