9 March 2017

Java | Important classes

BufferedReader vs Scanner
  • BufferedReader has a bigger buffer (8192 chars) than the one using in scanner (1024 chars). Use BufferedReader if you want to get long String from a stream.
  • BufferedReader is synchronized or thread safe while scanner is not
  • Use scanner if you want to parse a file and use BufferedReader if you want to read line by line
  • To use readLine() method, you have to create BufferedReader object and put a class that extends Reader object as a parameter: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); The parameter of the InputStreamReader is your input source, in this example we get an input from the console. System.in Be sure to put BufferedReader object in try block to manage the resources.
using BufferedReader in try block
Serializable
Let's think about a game. After some hours of playing game, you might want to have a break. You want to save the current state of your game so you can continue later from the same point. When saving a game or an application. You want to save the state of objects that have been created during the runtime of your application. In Java an Object cannot be stored in a file as an Object. It can only be stored if it converted to a stream (of bytes) beforehand. The process of converting is called serialization.

Some reasons for serialization are:
  • An object is created on the heap and the heap is for temporary storage. Only serialized objects can be saved as a file
  • To transmit data or state of an object to different location through the network
To make an Object serializable the class muss implement Serializable interface
make a class serializable
This is how you save an object into a file.
save an object as a file
And to retrieve the saved object.
retrieve the state of an object from a file

No comments:

Post a Comment