catalogue

  • 4.0.0.1 Describe the common classes in Java IO, byte stream, character stream, interface, implementation class, method blocking.
  • 4.0.0.2 What is a Bit, what is a Byte, what is a Char, what are their lengths and what are the differences?
  • 4.0.0.3 What is the difference between character stream and byte stream? How do I select a byte stream or character stream? What is a buffer and what does it do?
  • 4.0.0.4 Which modes are used in IO flow? What are the advantages of the adapter pattern and decorator pattern used in IO flows?
  • 4.0.0.5 What is your understanding of NIO? What are the main differences between NIO and IO? How do NIO and IO affect application design?
  • 4.0.0.9 How Can I Clone objects? What are the ways of cloning? What is the difference between deep clone and shallow clone? What meaning is deep clone and shallow clone say respectively?
  • 4.0.1.0 Does shallow copy create new objects? What is copied for the base type? How to implement shallow copy? Will the object address value be the same before and after shallow copy?
  • 4.0.1.1 Which stream is used to perform a large number of byte stream reads from hard disk, why? What should I pay attention to?

Good news

  • Summary of blog notes [October 2015 to present], including Java basic and in-depth knowledge points, Android technology blog, Python learning notes, etc., including the summary of bugs encountered in daily development, of course, I also collected a lot of interview questions in my spare time, updated, maintained and corrected for a long time, and continued to improve… Open source files are in Markdown format! Also open source life blog, since 2012, accumulated a total of 500 articles [nearly 1 million words], will be published on the Internet, reprint please indicate the source, thank you!
  • Link address:Github.com/yangchong21…
  • If you feel good, you can star, thank you! Of course, also welcome to put forward suggestions, everything starts from small, quantitative change causes qualitative change! All blogs will be open source to GitHub!

4.0.0.1 Describe the common classes in Java IO, byte stream, character stream, interface, implementation class, method blocking.

  • Output stream and input stream
    • The input stream is from external files to memory, and the output stream is mainly from memory to files.
  • Common classes in IO
    • There are many classes in IO streams. IO streams are mainly divided into character streams and byte streams. Byte streams of abstract class InputStream and OutputStream, their subclass FileInputStream, FileOutputStream, BufferedOutputStream, etc. Character streams BufferedReader and Writer, etc. All implement Closeable, Flushable, Appendable interfaces. The input and output in the program are stored as streams, which are actually byte files.
  • Method blocking in IO stream
    • A blocking method in Java means that when a program calls a modified method, it must wait for input data to be available or detect the end of input or throw an exception. Otherwise, the program will stay on the statement and will not execute the following statement. Such as the read() and readLine() methods.
    • Tech blog summary

4.0.0.2 What is a Bit, what is a Byte, what is a Char, what are their lengths and what are the differences?

  • What is a Bit?
    • Bit The smallest binary unit, the value 0 or 1 for the operation part of the computer
  • What is a byte
    • Byte is the smallest unit of data that a computer can manipulate. The value consists of 8 bits (-128-127).
  • What is a character
    • Char is the smallest unit that a user can read or write. In Java, it consists of 16 bits (0-65535).
  • What’s the difference
    • A Bit is the smallest unit that a computer can recognize only 0 or 1

4.0.0.3 What is the difference between character stream and byte stream? How do I select a byte stream or character stream? What is a buffer and what does it do?

  • Character stream and byte stream
    • To output binary data one by one to a device, or to read binary data one by one from a device, no matter what the input or output device is, we’re going to do this in a uniform way, and we’re going to describe it in an abstract way, and we’re going to call it an IO stream, The corresponding abstract classes are OutputStream and InputStream, and the different implementation classes represent different input and output devices that operate on bytes.
    • In applications, it is often necessary to output or read a piece of text that is completely characters. is byte stream ok? Everything in a computer ultimately exists as binary bytes. For the characters “China”, the corresponding bytes are first obtained and then written to the output stream. When we read, the first thing we read is bytes, but to display it as characters, we need to convert bytes to characters. Because the need is so extensive, a wrapper class for character streams has been provided.
    • The underlying device will always only accept byte data, and sometimes to write a string to the underlying device, you need to convert the string to byte and then write it. A character stream is a wrapper around a byte stream, while a character stream accepts strings directly, internally converting them into bytes and writing them to the underlying device, which provides a little convenience for writing or reading strings to IO devices.
    • Tech blog summary
    • The use of character stream and byte stream is very similar, but in fact byte stream operations do not go through the buffer (memory) but directly operate on the text itself, whereas character stream operations go through the buffer (memory) and then through the buffer to operate on the file.
  • How do I select a byte stream or character stream?
    • A character stream is a Java virtual machine that converts bytes into 2-byte Unicode characters
    • If it’s audio files, pictures, songs, use byte streams (to avoid data loss)
    • If it is related to Chinese (text), use character stream better.
  • What is a buffer and what does it do?
    • Buffer zone is a special area of memory, in many cases, when a program needs frequent operation resources (e.g., file or database) performance will be very low, so in order to improve performance can be part of the data read and write to the cache area temporarily, after can be directly read and write data from the area, thus significantly improve the performance.
    • Operations on Java character streams are buffered, so if we want to actively flush the buffer to a file during a character stream operation, we can use the Flush () method.

4.0.0.4 Which modes are used in IO flow? What are the advantages of the adapter pattern and decorator pattern used in IO flows?

  • Which patterns are used in IO streams
    • Probably decorator mode and adapter mode!
    • Be aware of the role of decorator patterns and adapter patterns; Secondly, you can give an example to illustrate its function vividly. Finally, a brief description of what it takes to accomplish this functionality.
  • Talk about the advantages of the adapter pattern and decorator pattern used in IO flows
    • Decorator pattern: Dynamically adding additional responsibilities to an object (an extension of existing functionality).
      // Decorate InputStreamReader as BufferedReader to be buffered. BufferedReader bufferedReader = new BufferedReader(inputStreamReader);Copy the code
      • 1. It must hold a decorated object (as a member variable).
      • 2. It must have the same interface as the object being decorated (polymorphic calls, extension needs).
      • 3. It can add extra functionality to the object being decorated.
      • For example, in an IO stream, the FilterInputStream class is the decorator role. It implements all the interfaces of the InputStream class and holds a reference to an object instance of InputStream. BufferedInputStream is the concrete decorator implementer. The purpose of this decorator class is to keep data read by InputStream in memory to improve read performance.
    • Adapter pattern: Transform the interface of one class into another interface that the customer expects, allowing incompatible interfaces to work together.
      // ADAPTS the FileInputStream stream to the InputStreamReader character stream to manipulate the file string. FileInputStream fileInput = new FileInputStream(file); InputStreamReader inputStreamReader = new InputStreamReader(fileInput);Copy the code
      • 1. The adapter object implements the original interface
      • 2. Adapter objects combine an object that implements the new interface
      • 3. Calls to the adapter’s original interface methods are delegated to a specific method of an instance of the new interface (override the old interface method to invoke the new interface function.)
      • For example, in an IO stream, the InputStreamReader class inherits the Reader interface, but to create it it must pass in an instance of InputStream in the constructor. InputStreamReader is simply an adaptation of the InputStream to the Reader. InputStreamReader implements the Reader interface and holds a reference to InputStream. In this case, the adapter is the InputStreamReader class, the source role is the instance object represented by InputStream, and the target interface is the Reader class.
      • The adaptor pattern is mainly to convert one interface into another. Its purpose is to reuse the interface by changing it. The decorator mode is not to change the interface of the decorator object, but to maintain the original interface, but enhance the function of the original object, or change the method of the original object to improve performance.
  • Take advantage of design patterns
    • Decorator mode is to add some new functionality to an object, and it is dynamic. It requires that the decorator object implements the same interface as the decorator object, and that the decorator object holds instances of the decorator object (decorator between various character streams, decorator between various byte streams).
    • Tech blog summary
    • The adapter pattern is to translate the interface of one class into the expected representation of another. The purpose is to eliminate class compatibility problems (character stream and byte stream compatibility) caused by interface mismatches.

4.0.0.5 What is your understanding of NIO? What are the main differences between NIO and IO? How do NIO and IO affect application design?

  • What is your understanding of NIO?
    • A traditional IO stream is blocking, listening for a ServerSocket all the time, and when a method like read is called, it waits until data arrives or the buffer is full. The accept call also blocks until there is a client connection. After each client connects, the server starts a thread to handle the client’s request. And multithreading handles multiple connections. Each thread has its own stack space and takes up some CPU time. Each thread blocks when the outside is not ready. The result of blocking is a lot of process context switching.
    • For NIO, it is non-blocking, core class:
      • 1.Buffer provides Buffer support for all primitive types.
      • 2.Charset encoding and decoding solution
      • 3.Channel A new raw I/O abstraction for reading and writing Buffer types. A Channel can be thought of as a connection to a particular device, program, or network.
  • What are the main differences between NIO and IO?
    • The main difference
      IO NIO Stream-oriented Buffer-oriented blocking IO non-blocking IO no selectorCopy the code
    • Flow oriented vs. buffer oriented
      • The first big difference between Java IO and NIO is that IO is stream-oriented and NIO is buffer-oriented. JavaIO stream-oriented means that one or more bytes are read from the stream at a time until all bytes are read without being cached anywhere. In addition, it cannot move data back and forth in a stream. If you need to move data read from the stream back and forth, you need to cache it into a buffer first. JavaNIO has a slightly different buffer-oriented approach. The data is read into a buffer that it processes later and can be moved back and forth in the buffer as needed. This adds flexibility to the process. However, you also need to check that the buffer contains all the data you need to process. Also, you need to make sure that when more data is read into the buffer, you don’t overwrite the unprocessed data in the buffer.
    • Blocking and non-blocking IO
      • The various streams of Java IO are blocked. This means that when a thread calls read() or write(), the thread blocks until some data is read, or data is written entirely. The thread can’t do anything else in the meantime. JavaNIO non-blocking mode, make a thread from one channel to send request to read data, but it can only get the currently available data, if there is no data are available, they will not get everything, rather than keep thread block, so until the data can be read before, the thread can continue to do other things. The same is true for non-blocking writes. A thread requests to write some data to a channel, but without waiting for it to write completely, the thread can do something else in the meantime. Threads typically spend the idle time of non-blocking IO performing IO operations on other channels, so a single thread can now manage multiple input and output channels.
    • The selector
      • Java NIO’s selector allows a single thread to monitor multiple input channels. You can register multiple channels to use a selector, and then use a single thread to “select” channels: channels that already have input to process, or channels that are ready to be written. This selection mechanism makes it easy for a single thread to manage multiple channels.
  • How do NIO and IO affect application design?
    • Whether you choose the IO or NIO toolkit, there are several aspects that may affect your application design:Tech blog summary
      • 1. API calls to NIO or IO classes.
      • 2. Data processing.
      • 3. Number of threads used to process data.
    • API call
      • Of course, API calls using NIO look different from those using IO, but that’s not surprising because instead of just reading byte by byte from an InputStream, the data must be read into the buffer before being processed.
    • The data processing
      • Data processing is also affected by using a pure NIO design compared to an IO design. In IO design, we read data byte by byte from InputStream or Reader.
      • Note that processing status is determined by how long the program executes. In other words, as soon as the reader.readline () method returns, you know that the line of text is read, and readLine() blocks until the entire line is read, that’s why. You also know that this line contains names; Likewise, when the second readline() call returns, you know that this line contains ages and so on. As you can see, the handler only runs when new data is read in and knows what data is at each step. Once a running thread has processed some of the data read in, that thread does not roll back the data (which is mostly the case).

4.0.0.9 How Can I Clone objects? What are the ways of cloning? What is the difference between deep clone and shallow clone? What meaning is deep clone and shallow clone say respectively?

  • There are two ways to implement object cloning:
    • 1. Implement Cloneable interface and rewrite clone() method in Object class;
    • 2. Implement Serializable interface, clone through object serialization and deserialization, you can realize the real deep clone, the code is as follows.
    • Note: if one of the above two conditions is not met, then cloning cannot be done!
  • What are the ways of cloning?
    • Cloning (copying) is a common operation in Java to quickly obtain a copy of an object. Cloning is divided into deep cloning and shallow cloning.
    • Shallow clone: Create a new object with the same attributes as the original object. For non-basic attributes, the new object still points to the memory address of the object pointed to by the original attribute.
    • Clone: When a new object is created, other objects referenced in the property will also be cloned, instead of pointing to the original object address.
  • What is the difference between deep clone and shallow clone?Tech blog summary
    • Both deep and shallow clones allocate a new region of the heap, depending on whether the object referenced by the object attribute needs to be cloned (recursively).
  • Java’s clone() method
    • 1. The clone method makes a copy of the object and returns it to the caller. In general, the Clone () method meets the requirement
    • 2. For any object x, there is x.lone ()! =x because the cloned object is not the same object as the original object
    • 3. For any object x, there is x.lone ().getClass()= = x.getclass ()// The cloned object has the same type as the original object
    • 4. If the equals() method of object x is properly defined, x.lone ().equals(x) should be true
  • Attention issues:
    • Cloning based on serialization and deserialization is not only a deep clone, but also a generic qualification that can check whether the Object to be cloned supports serialization. This check is done by the compiler and does not throw an exception at runtime. This scheme is significantly better than clone method using Object.
  • The code is shown below
    • Clone is a shallow clone if the object implements Cloneable override and the Clone method does nothing. Using an object stream to write an object to a stream and then read it out is a deep clone.
    public class MyUtil {  
      
        private MyUtil() {  
            throw new AssertionError();  
        }  
      
        public static <T> T clone(T obj) throws Exception {  
            ByteArrayOutputStream bout = new ByteArrayOutputStream();  
            ObjectOutputStream oos = new ObjectOutputStream(bout);  
            oos.writeObject(obj);  
      
            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());  
            ObjectInputStream ois = new ObjectInputStream(bin);  
            return(T) ois.readObject(); / / description: It makes no sense to call the close method of ByteArrayInputStream or ByteArrayOutputStream object  static void main(String[] args) { try { Person p1 = new Person("Hao LUO", 33, new Car("Benz", 300)); p1.clone(); Person p2 = MyUtil. Clone (p1); P2.getcar ().setbrand ()"BYD"); Println (p1); Person (p1); Person (p1); } catch (Exception e) { e.printStackTrace(); }}}Copy the code

4.0.1.0 Does shallow copy create new objects? What is copied for the base type? How to implement shallow copy? Will the object address value be the same before and after shallow copy?

  • Does shallow copy create new objects?

    • A new object is created. A shallow copy is a bitwise copy of an object that creates a new object with an exact copy of the original object’s property values.
  • What is copied for the base type?

    • If the property is of a primitive type, the value of the primitive type is copied. If the property is a memory address (reference type), the memory address is copied, so if one object changes the address, the other object will be affected.
    • In the figure above, the SourceObject has a property of type int “field1” and a reference property of type refObj (referencing an object of type ContainedObject). When a shallow copy of the SourceObject is made, CopiedObject is created, which has a property “field2” containing the copy value of “field1” and a reference still to refObj itself. Since “field1” is a basic type, we just copy its value to “field2”, but since “refObj” is a reference type, CopiedObject points to the same address as “refObj”. So any changes made to “refObj” in the SourceObject will affect CopiedObject.
  • How to implement shallow copy? Will the object address value be the same before and after shallow copy?

    • Let’s look at an example of shallow copy implementation
    public class Subject {
     
       private String name; 
       public Subject(String s) { 
          name = s; 
       } 
    
       public String getName() { 
          return name; 
       } 
    
       public void setName(String s) { name = s; }}Copy the code
    Public class Student implements Cloneable {private Subject implements Cloneable; private String name; public Student(String s, String sub) { name = s; subj = new Subject(sub); } public SubjectgetSubj() { 
          return subj; 
       } 
     
       public String getName() { 
          return name; 
       } 
     
       public void setName(String s) { name = s; } /** * rewriteclone() method * @return 
        */ 
       public Object clone() {// shallow copy try {// call the parent directlyclone() methodreturn super.clone(); 
          } catch (CloneNotSupportedException e) { 
             returnnull; }}}Copy the code
    private void test1(){// Stud = new stud ()"Yang Chong"."Rain of Xiaoxiang Swords");
        System.out.println("Original object:" + stud.getName() + "-"+ stud.getSubj().getName()); Stud = (stud) stud. Clone (); System.out.println("Copy object:" + clonedStud.getName() + "-"+ clonedStud.getSubj().getName()); // Whether the original object is the same as the copied object: system.out.println ("Is the original object the same as the copied object?"+ (stud == clonedStud)); // The name attribute of the original object is the same as that of the copied object. System.out.println("Is the name attribute of the original object the same as that of the copied object?"+ (stud.getName() == clonedStud.getName())); // The subj property of the original object is the same as that of the copied object. System.out.println("Is the subj property of the original object the same as that of the copied object?" + (stud.getSubj() == clonedStud.getSubj()));
    
        stud.setName("Xiao Yang is funny.");
        stud.getSubj().setName("Xiaoxiang Swordrain Warrior");
        System.out.println("Updated original object:" + stud.getName() + "-" + stud.getSubj().getName());
        System.out.println("Clone object after updating original object:" + clonedStud.getName() + "-" + clonedStud.getSubj().getName());
    }
    Copy the code
    • The following output is displayed:
    /com.ycbjie.other I/ system. out: original object: Other I/System. Out: Copy object: Other I/System. Out: Whether the original object and the copied object are the same:falseOther I/System. Out: Indicates whether the name attribute of the original object is the same as that of the copied object.trueOther I/System. Out: Indicates whether the subj attribute of the original object is the same as that of the copied object.true/com.ycbjie. Other I/System. Out: Other I/System. Out: Clone object after updating the original object: Yang Chong - Xiaoxiang Jianyu HeroCopy the code
    • The conclusion can be drawn
      • In this example, the Student class to be copied implements the Clonable interface to override the Clone () method of the Object class and then calls the super.clone() method inside the method. From the output we can see that changes made to the “name” attribute of the original object stud do not affect the copy object clonedStud, but changes made to the “name” attribute of the reference object subj do.
    • It can be concluded from the case that the original object and the copy object are different, that is, the address value has changed, but the attributes inside are still the same.

4.0.1.1 Which stream is used to perform a large number of byte stream reads from hard disk, why? What should I pay attention to?

  • Which stream is used to do a lot of reads from hard disk on the byte stream, why?
    • Since the byte stream is explicitly read, it must be inputStream or one of its subclasses, and since it is read in large numbers, it must be efficient to think of buffer streams. Tech blog summary
    • BufferedInputStream is the BufferedInputStream of InputStream. Using BufferedInputStream prevents the actual write operation every time data is read, representing the use of a buffer. Unbuffered operations write one byte for every byte read. Since disk IO operations are much slower than memory operations, unbuffered streams are inefficient. A buffered stream that reads many bytes at a time but does not write to disk, but is stored in memory first. When the buffer size is enough, write to disk at once. This method can reduce the number of disk operations, and speed up a lot! It also reduces disk damage.

The other is introduced

01. About blog summary links

  • 1. Tech blog round-up
  • 2. Open source project summary
  • 3. Life Blog Summary
  • 4. Himalayan audio summary
  • 5. Other summaries

02. About my blog

  • My personal website: www.yczbj.org, www.ycbjie.cn
  • Github:github.com/yangchong21…
  • Zhihu: www.zhihu.com/people/yang…
  • Jane: www.jianshu.com/u/b7b2c6ed9…
  • csdn:my.csdn.net/m0_37700275
  • The Himalayan listening: www.ximalaya.com/zhubo/71989…
  • Source: China my.oschina.net/zbj1618/blo…
  • Soak in the days of online: www.jcodecraeer.com/member/cont.
  • Email address: [email protected]
  • Blog: ali cloud yq.aliyun.com/users/artic… 239.headeruserinfo.3.dT4bcV
  • Segmentfault headline: segmentfault.com/u/xiangjian…
  • The Denver nuggets: juejin. Cn/user / 197877…