hereral/Clara-Training-Data huggingface dataset:
Question: Can you provide the Java - PipedReader constructor?
Answer: Constructor: PipedReader(int pipeSize) 
Description: It creates a PipedReader so that it is not yet connected and uses the specified pipe size for the pipe's buffer.

Constructor: PipedReader(PipedWriter src)
Description: It creates a PipedReader so that it is connected to the piped writer src.

Constructor: PipedReader(PipedWriter src, int pipeSize)
Description: It creates a PipedReader so that it is connected to the piped writer src and uses the specified pipe size for the pipe's buffer.

Constructor: PipedReader()
Description: It creates a PipedReader so that it is not yet connected.
Question: Can you give me the Java - PipedReader method?
Answer: Modified and type: void
Method: close()
Description: It closes this piped stream and releases any system resources associated with the stream.

Modified and type: void
Method: connect(PipedWriter src)
Description: It causes this piped reader to be connected to the piped writer src.

Modified and type: int
Method: read()
Description: It reads the next character of data from this piped stream.

Modified and type: int
Method: read(char[] cbuf, int off, int len)
Description: It reads up to len characters of data from this piped stream into an array of characters.
 
Modified and type: boolean
Method: ready()
Description: It tells whether this stream is ready to be read.
Question: Can you provide Java - PipedReader example?
Answer: import java.io.PipedReader;  
import java.io.PipedWriter;  
  
public class PipeReaderExample2 {  
    public static void main(String[] args) {  
        try {  
  
            final PipedReader read = new PipedReader();  
            final PipedWriter write = new PipedWriter(read);  
  
            Thread readerThread = new Thread(new Runnable() {  
                public void run() {  
                    try {  
                        int data = read.read();  
                        while (data != -1) {  
                            System.out.print((char) data);  
                            data = read.read();  
                        }  
                    } catch (Exception ex) {  
                    }  
                }  
            });  
  
            Thread writerThread = new Thread(new Runnable() {  
                public void run() {  
                    try {  
                        write.write("I love my country\n".toCharArray());  
                    } catch (Exception ex) {  
                    }  
                }  
            });  
  
            readerThread.start();  
            writerThread.start();  
  
        } catch (Exception ex) {  
            System.out.println(ex.getMessage());  
        }  
  
    }  
}  

Output:
I love my country
Question: What is Java FilterWriter?
Answer: Java FilterWriter class is an abstract class which is used to write filtered character streams.

The sub class of the FilterWriter should override some of its methods and it may provide additional methods and fields also.
Question: What is Java FilterWriter fields?
Answer: Modifier: protected
Type: Writer
Field: out
Description: The underlying character-output stream.
Question: Can you provide the Java FilterWriters constructor?
Answer: Modifier: protected
Constructor:  FilterWriter(Writer out)
Description:It creates InputStream class Object
Question: Can you give me the Java FilterWriter method?
Answer: Modifier and Type : void
Method: close()
Description:It closes the stream, flushing it first.

Modifier and Type :void
Method:flush()
Description:It flushes the stream.t

Modifier and Type : void
Method: write(char[] cbuf, int off, int len)
Description:It writes a portion of an array of characters.

Modifier and Type :void
Method:write(int c)
Description:It writes a single character.

Modifier and Type :void
Method: write(String str, int off, int len)
Description:It writes a portion of a string.
Question: Can you provide the Java FilterWriter example?
Answer: import java.io.*;  
class CustomFilterWriter extends FilterWriter {  
    CustomFilterWriter(Writer out) {  
        super(out);  
    }  
    public void write(String str) throws IOException {  
        super.write(str.toLowerCase());  
    }  
}  
public class FilterWriterExample {  
    public static void main(String[] args) {  
        try {  
            FileWriter fw = new FileWriter("Record.txt");   
            CustomFilterWriter filterWriter = new CustomFilterWriter(fw);             
            filterWriter.write("I LOVE MY COUNTRY");  
            filterWriter.close();  
            FileReader fr = new FileReader("record.txt");  
            BufferedReader bufferedReader = new BufferedReader(fr);  
            int k;  
            while ((k = bufferedReader.read()) != -1) {  
                System.out.print((char) k);  
            }  
            bufferedReader.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
} 

Output:
i love my country

While running the current program if the current working directory does not contain the file, a new file is created and CustomFileWriter will write the text "I LOVE MY COUNTRY" in lowercase to the file.
Question: What is Java FilterReader?
Answer: Java FilterReader is used to perform filtering operation on reader stream. It is an abstract class for reading filtered character streams.

The FilterReader provides default methods that passes all requests to the contained stream. Subclasses of FilterReader should override some of its methods and may also provide additional methods and fields.
Question: What is Java FilterReader Field?
Answer: Modifier: protected
Type: Reader
Field: in
Description: The underlying character-input stream.
Question: Can you provide the Java FilterReader constructor?
Answer: Modifier: protected
Constructor: FilterReader(Reader in)
Description:  It creates a new filtered reader.
Question: Can you give me the Java FilterReader method?
Answer: Modifier and Type:void
Method: close()
Description: It closes the stream and releases any system resources associated with it.

Modifier and Type:void
Method: mark(int readAheadLimit)
Description: It marks the present position in the stream.

Modifier and Type: boolean
Method: markSupported()
Description: It tells whether this stream supports the mark() operation.

Modifier and Type: boolean
Method: ready()
Description:   It tells whether this stream is ready to be read.

Modifier and Type:int
Method: read()
Description:  It reads a single character.

Modifier and Type:int
Method: read(char[] cbuf, int off, int len)
Description:  It reads characters into a portion of an array.

Modifier and Type: void
Method: reset()
Description:  It resets the stream.

Modifier and Type: long
Method:  skip(long n)
Description:  It skips characters.
Question: Can you provide the Java FilterReader example?
Answer: In this example, we are using "javaFile123.txt" file which contains "India is my country" text in it. Here, we are converting whitespace with question mark '?'.

import java.io.*;  
class CustomFilterReader extends FilterReader {  
    CustomFilterReader(Reader in) {  
        super(in);  
    }  
    public int read() throws IOException {  
        int x = super.read();  
        if ((char) x == ' ')  
            return ((int) '?');  
        else  
            return x;  
    }  
}  
public class FilterReaderExample {  
    public static void main(String[] args) {  
        try  {  
            Reader reader = new FileReader("javaFile123.txt");  
            CustomFilterReader fr = new CustomFilterReader(reader);  
            int i;  
            while ((i = fr.read()) != -1) {  
                System.out.print((char) i);  
            }  
            fr.close();  
            reader.close();  
        } catch (Exception e) {  
            e.getMessage();  
        }  
    }  
}  

Output:
India?is?my?country
Question: What is Java File Class?
Answer: The File class is an abstract representation of file and directory pathname. A pathname can be either absolute or relative.

The File class have several methods for working with directories and files such as creating new directories or files, deleting and renaming directories or files, listing the contents of a directory etc.
Question: Can you provide the Java File Class fields?
Answer: Modifier:static
Type:String
Field:pathSeparator
Description: It is system-dependent path-separator character, represented as a string for convenience.

Modifier:static
Type:char
Field:pathSeparatorChar
Description: It is system-dependent path-separator character.

Modifier:static
Type:String
Field:separator
Description: It is system-dependent default name-separator character, represented as a string for convenience.

Modifier:static 
Type:char
Field:separatorChar
Description:  It is system-dependent default name-separator character
Question: Can you give the Java File Class constructors?
Answer: 
Constructor: File(File parent, String child)
Description: It creates a new File instance from a parent abstract pathname and a child pathname string.

Constructor: File(String pathname)
Description: It creates a new File instance by converting the given pathname string into an abstract pathname.

Constructor: File(String parent, String child)
Description: It creates a new File instance from a parent pathname string and a child pathname string.

Constructor: File(URI uri)
Description: It creates a new File instance by converting the given file: URI into an abstract pathname.
Question: Can you give the Java File Class methods?
Answer: Modifier and Type: static File
Method: createTempFile(String prefix, String suffix)
Description: It creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

Modifier and Type:boolean
Method: createNewFile()
Description: It atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.

Modifier and Type:boolean
Method: canWrite()
Description: It tests whether the application can modify the file denoted by this abstract pathname.String[]

Modifier and Type:boolean
Method: canExecute()
Description: It tests whether the application can execute the file denoted by this abstract pathname.

Modifier and Type:boolean
Method: canRead()
Description: It tests whether the application can read the file denoted by this abstract pathname.

Modifier and Type:boolean
Method:  isAbsolute()
Description: It tests whether this abstract pathname is absolute.

Modifier and Type:boolean
Method: isDirectory()
Description:It tests whether the file denoted by this abstract pathname is a directory.

Modifier and Type: boolean
Method: isFile()
Description: It tests whether the file denoted by this abstract pathname is a normal file.

Modifier and Type:String
Method: getName()
Description: It returns the name of the file or directory denoted by this abstract pathname.

Modifier and Type:String
Method: getParent()
Description: It returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

Modifier and Type:Path
Method: toPath()
Description: It returns a java.nio.file.Path object constructed from the this abstract path.

Modifier and Type:URI
Method: toURI()
Description: It constructs a file: URI that represents this abstract pathname.

Modifier and Type: File[]
Method: listFiles()
Description: It returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname

Modifier and Type: long
Method: getFreeSpace()
Description: It returns the number of unallocated bytes in the partition named by this abstract path name.

Modifier and Type: String[]
Method: list(FilenameFilter filter)
Description: It returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

Modifier and Type: boolean
Method: mkdir()
Description: It creates the directory named by this abstract pathname.
Question: Java FileDescriptor
Answer: FileDescriptor class serves as an handle to the underlying machine-specific structure representing an open file, an open socket, or another source or sink of bytes. The handle can be err, in or out.

The FileDescriptor class is used to create a FileInputStream or FileOutputStream to contain it.
Question: What is Java FileDescriptor field?
Answer: Modifier:static
Type:FileDescriptor
Field:err
Description: A handle to the standard error stream.

Modifier:static
Type:FileDescriptor
Field:in
Description:A handle to the standard input stream.


Modifier:static
Type:FileDescriptor
Field:out
Description:  A handle to the standard output stream.
Question: Can you give me the Java FileDescriptor constructor?
Answer: Constructor:  FileDescriptor()
Description: Constructs an (invalid) FileDescriptor object.
Question: Can you give me the Java FileDescriptor method?
Answer: Modifier and Type: void
Method: sync()
Description: It force all system buffers to synchronize with the underlying device.

Modifier and Type: boolean
Method: valid()
Description: It tests if this file descriptor object is valid.
Question: Can you provide the Java FileDescriptor example?
Answer: import java.io.*;  
public class FileDescriptorExample {  
    public static void main(String[] args) {  
        FileDescriptor fd = null;  
        byte[] b = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58 };  
        try  {  
            FileOutputStream fos = new FileOutputStream("Record.txt");  
            FileInputStream fis = new FileInputStream("Record.txt");  
            fd = fos.getFD();  
            fos.write(b);  
            fos.flush();  
            fd.sync();// confirms data to be written to the disk  
            int value = 0;  
            // for every available bytes  
            while ((value = fis.read()) != -1) {  
                char c = (char) value;// converts bytes to char  
                System.out.print(c);  
            }  
            System.out.println("\nSync() successfully executed!!");  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}  


Output:
0123456789:
Sync() successfully executed!!

Record.txt:
0123456789:
Question: What is Java - RandomAccessFile?
Answer: This class is used for reading and writing to random access file. A random access file behaves like a large array of bytes. There is a cursor implied to the array called file pointer, by moving the cursor we do the read write operations. If end-of-file is reached before the desired number of byte has been read than EOFException is thrown. It is a type of IOException.
Question: Can you give me the Java - RandomAccessFile constructor?
Answer: Constructor: RandomAccessFile(File file, String mode)
Description: Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.

Constructor: RandomAccessFile(String name, String mode)
Description: Creates a random access file stream to read from, and optionally to write to, a file with the specified name.
Question: Can you give me the Java - RandomAccessFile method?
Answer: 
Modifier and Type:void 
Method: close()
Description: It closes this random access file stream and releases any system resources associated with the stream.

Modifier and Type: FileChannel
Method: getChannel()
Description: It returns the unique FileChannel object associated with this file.

Modifier and Type: int
Method: readInt()
Description:  It reads a signed 32-bit integer from this file.

Modifier and Type: String
Method: readUTF()
Description: It reads in a string from this file.

Modifier and Type: void
Method: seek(long pos)
Description: It sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

Modifier and Type: void
Method:  writeDouble(double v)
Description: It converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an eight-byte quantity, high byte first.

Modifier and Type: void
Method:writeFloat(float v)
Description:It converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a four-byte quantity, high byte first.

Modifier and Type:void
Method: write(int b)
Description: It writes the specified byte to this file.

Modifier and Type: int
Method: read()
Description: It reads a byte of data from this file.
 
Modifier and Type:long
Method: length()
Description: It returns the length of this file. 

Modifier and Type:void
Method: seek(long pos)
Description: It sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
Question: Can you provide the Java - RandomAccessFile example?
Answer: import java.io.IOException;  
import java.io.RandomAccessFile;  
  
public class RandomAccessFileExample {  
    static final String FILEPATH ="myFile.TXT";  
    public static void main(String[] args) {  
        try {  
            System.out.println(new String(readFromFile(FILEPATH, 0, 18)));  
            writeToFile(FILEPATH, "I love my country and my people", 31);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
    private static byte[] readFromFile(String filePath, int position, int size)  
            throws IOException {  
        RandomAccessFile file = new RandomAccessFile(filePath, "r");  
        file.seek(position);  
        byte[] bytes = new byte[size];  
        file.read(bytes);  
        file.close();  
        return bytes;  
    }  
    private static void writeToFile(String filePath, String data, int position)  
            throws IOException {  
        RandomAccessFile file = new RandomAccessFile(filePath, "rw");  
        file.seek(position);  
        file.write(data.getBytes());  
        file.close();  
    }  
}  

The myFile.TXT contains text "This class is used for reading and writing to random access file."
after running the program it will contains

This class is used for reading I love my country and my peoplele.
Question: What is Java Scanner?
Answer: Scanner class in Java is found in the java.util package. Java provides various ways to read input from the keyboard, the java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default. It provides many methods to read and parse various primitive values.

The Java Scanner class is widely used to parse text for strings and primitive types using a regular expression. It is the simplest way to get input in Java. By the help of Scanner in Java, we can get input from the user in primitive types such as int, long, double, byte, float, short, etc.

The Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

The Java Scanner class provides nextXXX() methods to return the type of value such as nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc. To get a single character from the scanner, you can call next().charAt(0) method which returns a single character
Question: What is Java Scanner Class Declaration?
Answer: public final class Scanner  
          extends Object  
          implements Iterator<String>
Question: How to get Java Scanner?
Answer: To get the instance of Java Scanner which reads input from the user, we need to pass the input stream (System.in) in the constructor of Scanner class. For Example:

Scanner in = new Scanner(System.in);  

To get the instance of Java Scanner which parses the strings, we need to pass the strings in the constructor of Scanner class. For Example:

Scanner in = new Scanner("Hello Javatpoint");
Question: Can you give me the Java Scanner Class Constructors?
Answer: Sn:1
Constructor: Scanner(File source)
Description: It constructs a new Scanner that produces values scanned from the specified file.

Sn:2
Constructor: Scanner(File source, String charsetName)
Description: It constructs a new Scanner that produces values scanned from the specified file.


Sn:3
Constructor: Scanner(InputStream source)
Description: It constructs a new Scanner that produces values scanned from the specified input stream.


Sn:4
Constructor: Scanner(InputStream source, String charsetName)
Description: It constructs a new Scanner that produces values scanned from the specified input stream


Sn:5
Constructor: Scanner(Readable source)
Description: It constructs a new Scanner that produces values scanned from the specified source.


Sn:6
Constructor: Scanner(String source)
Description: It constructs a new Scanner that produces values scanned from the specified string.


Sn:7
Constructor: Scanner(ReadableByteChannel source)
Description:  It constructs a new Scanner that produces values scanned from the specified channel.


Sn:8
Constructor:  Scanner(ReadableByteChannel source, String charsetName)
Description: It constructs a new Scanner that produces values scanned from the specified channel.


Sn:9
Constructor: Scanner(Path source)
Description: It constructs a new Scanner that produces values scanned from the specified file.


Sn:10
Constructor: Scanner(Path source, String charsetName)
Description: It constructs a new Scanner that produces values scanned from the specified file.
Question: Can you provide Java Scanner Class example?
Answer: Let's see a simple example of Java Scanner where we are getting a single input from the user. Here, we are asking for a string through in.nextLine() method.

import java.util.*;  
public class ScannerExample {  
public static void main(String args[]){  
          Scanner in = new Scanner(System.in);  
          System.out.print("Enter your name: ");  
          String name = in.nextLine();  
          System.out.println("Name is: " + name);             
          in.close();             
          }  
}  

Output:
Enter your name: sonoo jaiswal
Name is: sonoo jaiswal
Question: What is Serialization and Deserialization in Java?
Answer: Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization where byte-stream is converted into an object. The serialization and deserialization process is platform-independent, it means you can serialize an object on one platform and deserialize it on a different platform.

For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for deserialization we call the readObject() method of ObjectInputStream class.

We must have to implement the Serializable interface for serializing the object.
Question: What are the Advantages of Java Serialization?
Answer: It is mainly used to travel object's state on the network (that is known as marshalling).
Question: What is java.io.Serializable interface?
Answer: Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so that the objects of these classes may get a certain capability. The Cloneable and Remote are also marker interfaces.

The Serializable interface must be implemented by the class whose object needs to be persisted.

The String class and all the wrapper classes implement the java.io.Serializable interface by default.

Let's see the example given below:

Student.java

import java.io.Serializable;  
public class Student implements Serializable{  
 int id;  
 String name;  
 public Student(int id, String name) {  
  this.id = id;  
  this.name = name;  
 }  
}  
In the above example, Student class implements Serializable interface. Now its objects can be converted into stream. The main class implementation of is showed in the next code.
Question: What is the ObjectOutputStream class?
Answer: The ObjectOutputStream class is used to write primitive data types, and Java objects to an OutputStream. Only objects that support the java.io.Serializable interface can be written to streams.

Constructor: public ObjectOutputStream(OutputStream out) throws IOException {}
Description: It creates an ObjectOutputStream that writes to the specified OutputStream.

Important Methods
1)  public final void writeObject(Object obj) throws IOException {} - It writes the specified object to the ObjectOutputStream.
2) public void flush() throws IOException {} - It flushes the current output stream.
3) public void close() throws IOException {} - It closes the current output stream.
Question: What is the ObjectInputStream class?
Answer: An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.

Constructor: public ObjectInputStream(InputStream in) throws IOException {}
Description: It creates an ObjectInputStream that reads from the specified InputStream.

Important Methods 

1)  public final Object readObject() throws IOException, ClassNotFoundException{} - It reads an object from the input stream.
2) public void close() throws IOException {} - It closes ObjectInputStream.
Question: Can you provide an Example of Java Serialization?
Answer: In this example, we are going to serialize the object of Student class from above code. The writeObject() method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file named f.txt.

Persist.java

import java.io.*;    
class Persist{    
 public static void main(String args[]){    
  try{    
  //Creating the object    
  Student s1 =new Student(211,"ravi");    
  //Creating stream and writing the object    
  FileOutputStream fout=new FileOutputStream("f.txt");    
  ObjectOutputStream out=new ObjectOutputStream(fout);    
  out.writeObject(s1);    
  out.flush();    
  //closing the stream    
  out.close();    
  System.out.println("success");    
  }catch(Exception e){System.out.println(e);}    
 }    
}    


Output:
success
Question: Can you provide an Example of Java Deserialization?
Answer: Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization. Let's see an example where we are reading the data from a deserialized object.

Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization. Let's see an example where we are reading the data from a deserialized object.

Depersist.java

import java.io.*;  
class Depersist{  
 public static void main(String args[]){  
  try{  
  //Creating stream to read the object  
  ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));  
  Student s=(Student)in.readObject();  
  //printing the data of the serialized object  
  System.out.println(s.id+" "+s.name);  
  //closing the stream  
  in.close();  
  }catch(Exception e){System.out.println(e);}  
 }  
}  

Output:
211 ravi
Question: Can you give me the Java Serialization with Inheritance (IS-A Relationship)?
Answer: If a class implements Serializable interface then all its sub classes will also be serializable. Let's see the example given below:

SerializeISA.java

import java.io.Serializable;    
class Person implements Serializable{    
 int id;    
 String name;    
 Person(int id, String name) {    
  this.id = id;    
  this.name = name;    
 }    
}    
class Student extends Person{    
 String course;    
 int fee;    
 public Student(int id, String name, String course, int fee) {    
  super(id,name);    
  this.course=course;    
  this.fee=fee;    
 }    
}    
public class SerializeISA  
{    
 public static void main(String args[])  
 {    
    try{    
  //Creating the object    
  Student s1 =new Student(211,"ravi","Engineering",50000);    
  //Creating stream and writing the object    
  FileOutputStream fout=new FileOutputStream("f.txt");    
  ObjectOutputStream out=new ObjectOutputStream(fout);    
  out.writeObject(s1);    
  out.flush();    
  //closing the stream    
  out.close();    
  System.out.println("success");    
  }catch(Exception e){System.out.println(e);}    
  try{    
  //Creating stream to read the object    
  ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));    
  Student s=(Student)in.readObject();    
  //printing the data of the serialized object    
  System.out.println(s.id+" "+s.name+" "+s.course+" "+s.fee);    
  //closing the stream    
  in.close();    
  }catch(Exception e){System.out.println(e);}    
 }    
}  

Output:
success
211 ravi Engineering 50000


The SerializeISA class has serialized the Student class object that extends the Person class which is Serializable. Parent class properties are inherited to subclasses so if parent class is Serializable, subclass would also be.
Question: Can you give me the Java Serialization with Aggregation (HAS-A Relationship)?
Answer: If a class has a reference to another class, all the references must be Serializable otherwise serialization process will not be performed. In such case, NotSerializableException is thrown at runtime.

Address.java
class Address{    
 String addressLine,city,state;    
 public Address(String addressLine, String city, String state) {    
  this.addressLine=addressLine;    
  this.city=city;    
  this.state=state;    
 }    
}    

Student.java
import java.io.Serializable;  
public class Student implements Serializable{  
 int id;  
 String name;  
 Address address;//HAS-A  
 public Student(int id, String name) {  
  this.id = id;  
  this.name = name;  
 }  
}  

Since Address is not Serializable, you cannot serialize the instance of the Student class.
Question: Can you provide the Java Serialization with the static data member?
Answer: If there is any static data member in a class, it will not be serialized because static is the part of class not object.

Employee.java

class Employee implements Serializable{  
 int id;  
 String name;  
 static String company="SSS IT Pvt Ltd";//it won't be serialized  
 public Student(int id, String name) {  
  this.id = id;  
  this.name = name;  
 }  
}
Question: What is Java Serialization with array or collection?
Answer: Rule: In case of array or collection, all the objects of array or collection must be serializable. If any object is not serialiizable, serialization will be failed.
Question: What is Externalizable in java?
Answer: The Externalizable interface provides the facility of writing the state of an object into a byte stream in compress format. It is not a marker interface.

The Externalizable interface provides two methods:
-public void writeExternal(ObjectOutput out) throws IOException
-public void readExternal(ObjectInput in) throws IOException
Question: Can you provide the Java Transient Keyword?
Answer: If you don't want to serialize any data member of a class, you can mark it as transient.

Employee.java

class Employee implements Serializable{  
 transient int id;  
 String name;  
 public Student(int id, String name) {  
  this.id = id;  
  this.name = name;  
 }  
}  

Now, id will not be serialized, so when you deserialize the object after serialization, you will not get the value of id. It will return default value always. In such case, it will return 0 because the data type of id is an integer.
Question: Can you give me the SerialVersionUID?
Answer: The serialization process at runtime associates an id with each Serializable class which is known as SerialVersionUID. It is used to verify the sender and receiver of the serialized object. The sender and receiver must be the same. To verify it, SerialVersionUID is used. The sender and receiver must have the same SerialVersionUID, otherwise, InvalidClassException will be thrown when you deserialize the object. We can also declare our own SerialVersionUID in the Serializable class. To do so, you need to create a field SerialVersionUID and assign a value to it. It must be of the long type with static and final. It is suggested to explicitly declare the serialVersionUID field in the class and have it private also. For example:

private static final long serialVersionUID=1L;  

Now, the Serializable class will look like this:

Employee.java

import java.io.Serializable;    
class Employee implements Serializable{    
 private static final long serialVersionUID=1L;    
 int id;    
 String name;    
 public Student(int id, String name) {    
  this.id = id;    
  this.name = name;    
 }    
}
Question: What is Java transient Keyword?
Answer: In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the type of data stored in that instance. Deserialization performs exactly opposite operation. It converts the byte sequence into original object data. During the serialization, when we do not want an object to be serialized we can use a transient keyword.
Question: Why to use the transient keyword?
Answer: The transient keyword can be used with the data members of a class in order to avoid their serialization. For example, if a program accepts a user's login details and password. But we don't want to store the original password in the file. Here, we can use transient keyword and when JVM reads the transient keyword it ignores the original value of the object and instead stores the default value of the object.

Syntax:

private transient <member variable>;  

Or

transient private <member variable>;
Question: When to use the transient keyword?
Answer: 1)The transient modifier can be used where there are data members derived from the other data members within the same instance of the class.
2)This transient keyword can be used with the data members which do not depict the state of the object.
3)The data members of a non-serialized object or class can use a transient modifier.
Question: Can you provide an Example of Java Transient Keyword?
Answer: Let's take an example, we have declared a class as Student, it has three data members id, name and age. If you serialize the object, all the values will be serialized but we don't want to serialize one value, e.g. age then we can declare the age data member as transient.

In this example, we have created two classes Student and PersistExample. The age data member of the Student class is declared as transient, its value will not be serialized.

If you deserialize the object, you will get the default value for transient variable.

Let's create a class with transient variable.

PersistExample.java

import java.io.*;      
public class Student implements Serializable{    
 int id;    
 String name;    
 transient int age;//Now it will not be serialized    
 public Student(int id, String name,int age) {    
  this.id = id;    
  this.name = name;    
  this.age=age;    
 }    
}    
class PersistExample{    
 public static void main(String args[])throws Exception{    
  Student s1 =new Student(211,"ravi",22);//creating object    
  //writing object into file    
  FileOutputStream f=new FileOutputStream("f.txt");    
  ObjectOutputStream out=new ObjectOutputStream(f);    
  out.writeObject(s1);    
  out.flush();    
  out.close();    
  f.close();    
  System.out.println("success");    
 }    
}    
Output:
success


Now write the code for deserialization.

DePersist.java

import java.io.*;    
class DePersist{    
 public static void main(String args[])throws Exception{    
  ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));    
  Student s=(Student)in.readObject();    
  System.out.println(s.id+" "+s.name+" "+s.age);    
  in.close();    
 }    
}    

Output:
211 ravi 0


As you can see, printing age of the student returns 0 because value of age was not serialized.
In this article, we have discussed use of transient keyword in Java, where to use transient keyword and implementation of transient keyword in a Java program.
Question: What is Java Networking?
Answer: Java Networking is a concept of connecting two or more computing devices together so that we can share resources.

Java socket programming provides facility to share data between different computing devices.
Question: What is the Advantage of Java Networking?
Answer: 1.Sharing resources
2.Centralize software management

The java.net package supports two protocols,

1.TCP: Transmission Control Protocol provides reliable communication between the sender and receiver. TCP is used along with the Internet Protocol referred as TCP/IP.
2.UDP: User Datagram Protocol provides a connection-less protocol service by allowing packet of data to be transferred along two or more nodes
Question: What is Java Networking Terminology?
Answer: The widely used Java networking terminologies are given below:
1.IP Address
2.Protocol
3.Port Number
4.MAC Address
5.Connection-oriented and connection-less protocol
6.Socket

1) IP Address

IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets that range from 0 to 255.
It is a logical address that can be changed.

2) Protocol

A protocol is a set of rules basically that is followed for communication. For example:
-TCP
-FTP
-Telnet
-SMTP
-POP etc.
3) Port Number

The port number is used to uniquely identify different applications. It acts as a communication endpoint between applications.
The port number is associated with the IP address for communication between two applications.

4) MAC Address

MAC (Media Access Control) address is a unique identifier of NIC (Network Interface Controller). A network node can have multiple NIC but each with unique MAC address.
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.

5) Connection-oriented and connection-less protocol

In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but slow. The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast. The example of connection-less protocol is UDP.

6) Socket

A socket is an endpoint between two way communications.
Question: What is java.net package?
Answer: The java.net package can be divided into two sections:

1. A Low-Level API: It deals with the abstractions of addresses i.e. networking identifiers, Sockets i.e. bidirectional data communication mechanism and Interfaces i.e. network interfaces.
2. A High Level API: It deals with the abstraction of URIs i.e. Universal Resource Identifier, URLs i.e. Universal Resource Locator, and Connections i.e. connections to the resource pointed by URLs.

The java.net package provides many classes to deal with networking applications in Java. A list of these classes is given below:

-Authenticator
-CacheRequest
-CacheResponse
-ContentHandler
-CookieHandler
-CookieManager
-DatagramPacket
-DatagramSocket
-DatagramSocketImpl
-InterfaceAddress
-JarURLConnection
-MulticastSocket
-InetSocketAddress
-InetAddress
-Inet4Address
-Inet6Address
-IDN
-HttpURLConnection
-HttpCookie
-NetPermission
-NetworkInterface
-PasswordAuthentication
-Proxy
-ProxySelector
-ResponseCache
-SecureCacheResponse
-ServerSocket
-Socket
-SocketAddress
-SocketImpl
-SocketPermission
-StandardSocketOptions
-URI
-URL
-URLClassLoader
-URLConnection
-URLDecoder
-URLEncoder
-URLStreamHandler

List of interfaces available in java.net package:

-ContentHandlerFactory
-CookiePolicy
-CookieStore
-DatagramSocketImplFactory
-FileNameMap
-SocketOption<T>
-SocketOptions
-SocketImplFactory
-URLStreamHandlerFactory
-ProtocolFamily
Question: What is Java Socket Programming?
Answer: Java Socket programming is used for communication between the applications running on different JRE.

Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket and DatagramPacket classes are used for connection-less socket programming.

The client in socket programming must know two information:
1.IP Address of Server, and
2.Port number.

Here, we are going to make one-way client and server communication. In this application, client sends a message to the server, server reads the message and prints it. Here, two classes are being used: Socket and ServerSocket. The Socket class is used to communicate client and server. Through this class, we can read and write message. The ServerSocket class is used at server-side. The accept() method of ServerSocket class blocks the console until the client is connected. After the successful connection of client, it returns the instance of Socket at server-side.
Question: What is Socket class?
Answer: A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket.

Method:  public InputStream getInputStream()
Description: returns the InputStream attached with this socket.

Method:  public OutputStream getOutputStream()
Description: returns the OutputStream attached with this socket.

Method: public synchronized void close()
Description:closes this socket
Question: Can you provide the ServerSocket class?
Answer: The ServerSocket class can be used to create a server socket. This object is used to establish communication with the clients.

Method: public Socket accept()
Description: returns the socket and establish a connection between server and client.

Method: public synchronized void close()
Description:  closes the server socket.
Question: Can you provide an Example of Java Socket Programming?
Answer: Creating Server:

To create the server application, we need to create the instance of ServerSocket class. Here, we are using 6666 port number for the communication between the client and server. You may also choose any other port number. The accept() method waits for the client. If clients connects with the given port number, it returns an instance of Socket.

ServerSocket ss=new ServerSocket(6666);  
Socket s=ss.accept();//establishes connection and waits for the client   

Creating Client:

To create the client application, we need to create the instance of Socket class. Here, we need to pass the IP address or hostname of the Server and a port number. Here, we are using "localhost" because our server is running on same system.
Socket s=new Socket("localhost",6666);  

Let's see a simple of Java socket programming where client sends a text and server receives and prints it.


File: MyServer.java

import java.io.*;  
import java.net.*;  
public class MyServer {  
public static void main(String[] args){  
try{  
ServerSocket ss=new ServerSocket(6666);  
Socket s=ss.accept();//establishes connection   
DataInputStream dis=new DataInputStream(s.getInputStream());  
String  str=(String)dis.readUTF();  
System.out.println("message= "+str);  
ss.close();  
}catch(Exception e){System.out.println(e);}  
}  
}  

File: MyClient.java
import java.io.*;  
import java.net.*;  
public class MyClient {  
public static void main(String[] args) {  
try{      
Socket s=new Socket("localhost",6666);  
DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
dout.writeUTF("Hello Server");  
dout.flush();  
dout.close();  
s.close();  
}catch(Exception e){System.out.println(e);}  
}  
} 
To execute this program open two command prompts and execute each program at each command prompt
Question: What is Java URL?
Answer: The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide Web.

A URL contains many information:

1.Protocol: In this case, http is the protocol.
2.Server name or IP Address: In this case, www.javatpoint.com is the server name.
3.Port Number: It is an optional attribute. If we write http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is not mentioned in the URL, it returns -1.
4.File Name or directory name: In this case, index.jsp is the file name.
Question: Can you give me the Constructors of Java URL class?
Answer: URL(String spec)
Creates an instance of a URL from the String representation.

URL(String protocol, String host, int port, String file)
Creates an instance of a URL from the given protocol, host, port number, and file.

URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates an instance of a URL from the given protocol, host, port number, file, and handler.

URL(String protocol, String host, String file)
Creates an instance of a URL from the given protocol name, host name, and file name.

URL(URL context, String spec)
Creates an instance of a URL by parsing the given spec within a specified context.

URL(URL context, String spec, URLStreamHandler handler)
Creates an instance of a URL by parsing the given spec with the specified handler within a given context.
Question: Can you give me the Commonly used methods of Java URL class?
Answer: The java.net.URL class provides many methods. The important methods of URL class are given below.

Method: public String getProtocol()
Description: it returns the protocol of the URL.

Method:public String getHost()
Description: it returns the host name of the URL.

Method: public String getPort()
Description: it returns the Port Number of the URL.

Method: public String getFile()
Description:  it returns the file name of the URL.

Method: public String getAuthority()
Description: it returns the authority of the URL.

Method: public String toString()
Description: it returns the string representation of the URL.

Method:public String getQuery()
Description: it returns the query string of the URL.

Method: public String getDefaultPort()
Description: it returns the default port of the URL.

Method: public URLConnection openConnection()
Description: it returns the instance of URLConnection i.e. associated with this URL.

Method: public boolean equals(Object obj)
Description: it compares the URL with the given object.

Method: public Object getContent()
Description: it returns the content of the URL.

Method: public String getRef()
Description:  it returns the anchor or reference of the URL.

Method: public URI toURI()
Description: it returns a URI of the URL.
Question: Can you provide an Example of Java URL class?
Answer: //URLDemo.java  

import java.net.*;  
public class URLDemo{  
public static void main(String[] args){  
try{  
URL url=new URL("http://www.javatpoint.com/java-tutorial");  
  
System.out.println("Protocol: "+url.getProtocol());  
System.out.println("Host Name: "+url.getHost());  
System.out.println("Port Number: "+url.getPort());  
System.out.println("File Name: "+url.getFile());  
  
}catch(Exception e){System.out.println(e);}  
}  
} 

Output:
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
Question: What is Java URLConnection Class?
Answer: The Java URLConnection class represents a communication link between the URL and the application. It can be used to read and write data to the specified resource referred by the URL.
Question: What is the URL?
Answer: -URL is an abbreviation for Uniform Resource Locator. An URL is a form of string that helps to find a resource on the World Wide Web (WWW).

-URL has two components:

1.The protocol required to access the resource.
2.The location of the resource.
Question: What are the Features of URLConnection class?
Answer: 1.URLConnection is an abstract class. The two subclasses HttpURLConnection and JarURLConnection makes the connetion between the client Java program and URL resource on the internet.
2.With the help of URLConnection class, a user can read and write to and from any resource referenced by an URL object.
3.Once a connection is established and the Java program has an URLConnection object, we can use it to read or write or get further information like content length, etc.

Constructor: protected URLConnection(URL url)
Description: It constructs a URL connection to the specified URL.
Question: How to get the object of URLConnection Class?
Answer: The openConnection() method of the URL class returns the object of URLConnection class.

Syntax:
public URLConnection openConnection()throws IOException{}