Question
stringlengths 1
113
| Answer
stringlengths 22
6.98k
|
|---|---|
What are the Types of Synchronization?
|
There are two types of synchronization
1.Process Synchronization
2.Thread Synchronization
Here, we will discuss only thread synchronization.
|
What is Thread Synchronization?
|
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1.Mutual Exclusive
1.Synchronized method.
2.Synchronized block.
3.Static synchronization.
2.Cooperation (Inter-thread communication in java)
|
What is Mutual Exclusive?
|
Mutual Exclusive helps keep threads from interfering with one another while sharing data. It can be achieved by using the following three ways:
1.By Using Synchronized Method
2.By Using Synchronized Block
3.By Using Static Synchronization
|
What is Concept of Lock in Java?
|
Synchronization is built around an internal entity known as the lock or monitor. Every object has a lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.
|
Can you provide the Java Synchronized Method?
|
f you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.
|
Can you give me an Example of synchronized method by using annonymous class?
|
In this program, we have created the two threads by using the anonymous class, so less coding is required.
TestSynchronization3.java
//Program of synchronized method by using annonymous class
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
public class TestSynchronization3{
public static void main(String args[]){
final Table obj = new Table();//only one object
Thread t1=new Thread(){
public void run(){
obj.printTable(5);
}
};
Thread t2=new Thread(){
public void run(){
obj.printTable(100);
}
};
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
|
What is Synchronized Block in Java?
|
Synchronized block can be used to perform synchronization on any specific resource of the method.
Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines, in such cases, we can use synchronized block.
If we put all the codes of the method in the synchronized block, it will work same as the synchronized method.
|
Can you give me an Example of Synchronized Block?
|
Let's see the simple example of synchronized block.
TestSynchronizedBlock1.java
class Table
{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronizedBlock1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
|
What is Static Synchronization?
|
If you make any static method as synchronized, the lock will be on the class not on object.
|
What is Problem without static synchronization?
|
Suppose there are two objects of a shared class (e.g. Table) named object1 and object2. In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock. But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock. We don't want interference between t1 and t3 or t2 and t4. Static synchronization solves this problem.
|
Can you give me an Example of Static Synchronization?
|
In this example we have used synchronized keyword on the static method to perform static synchronization.
TestSynchronization4.java
class Table
{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}
}
class MyThread2 extends Thread{
public void run(){
Table.printTable(10);
}
}
class MyThread3 extends Thread{
public void run(){
Table.printTable(100);
}
}
class MyThread4 extends Thread{
public void run(){
Table.printTable(1000);
}
}
public class TestSynchronization4{
public static void main(String t[]){
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
Output:
1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
|
What is Deadlock in Java?
|
Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.
|
Can you provide an Example of Deadlock in Java?
|
TestDeadlockExample1.java
public class TestDeadlockExample1 {
public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
// t2 tries to lock resource2 then resource1
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}
Output:
Thread 1: locked resource 1
Thread 2: locked resource 2
|
Can you give me More Complicated Deadlocks?
|
A deadlock may also include more than two threads. The reason is that it can be difficult to detect a deadlock. Here is an example in which four threads have deadlocked:
Thread 1 locks A, waits for B
Thread 2 locks B, waits for C
Thread 3 locks C, waits for D
Thread 4 locks D, waits for A
Thread 1 waits for thread 2, thread 2 waits for thread 3, thread 3 waits for thread 4, and thread 4 waits for thread 1.
|
How to avoid deadlock?
|
A solution for a problem is found at its roots. In deadlock it is the pattern of accessing the resources A and B, is the main issue. To solve the issue we will have to simply re-order the statements where the code is accessing shared resources.
|
How to Avoid Deadlock in Java?
|
Deadlocks cannot be completely resolved. But we can avoid them by following basic rules mentioned below:
Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the main reason for a deadlock condition. It normally happens when you give locks to multiple threads.
Avoid Unnecessary Locks: The locks should be given to the important threads. Giving locks to the unnecessary threads that cause the deadlock condition.
Using Thread Join: A deadlock usually happens when one thread is waiting for the other to finish. In this case, we can use join with a maximum time that a thread will take.
|
What is Inter-thread Communication in Java?
|
Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class:
-wait()
-notify()
-notifyAll()
|
Can you give me the wait() method?
|
wait() method
The wait() method causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception.
Method: public final void wait()throws InterruptedException
Description: It waits until object is notified.
Method: public final void wait(long timeout)throws InterruptedException
Description: It waits for the specified amount of time.
|
Can you give me the notify() method?
|
notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.
Syntax:
public final void notify()
|
Can you give me the notifyAll() method?
|
notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()
|
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
|
It is because they are related to lock and object has a lock.
|
What is the Difference between wait and sleep?
|
Difference between wait and sleep?
Let's see the important differences between wait and sleep methods.
Wait(): The wait() method releases the lock.
Sleep(): The sleep() method doesn't release the lock.
Wait(): It is a method of Object class
Sleep(): It is a method of Thread class
Wait(): It is the non-static method
Sleep(): It is the static method
Wait(): It should be notified by notify() or notifyAll() methods
Sleep(): After the specified amount of time, sleep is completed.
|
Can you provide an Example of Inter Thread Communication in Java?
|
Let's see the simple example of inter thread communication.
Test.java
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
|
What is Interrupting a Thread?
|
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the interrupt flag to true. Let's first see the methods provided by the Thread class for thread interruption.
The 3 methods provided by the Thread class for interrupting a thread
-public void interrupt()
-public static boolean interrupted()
-public boolean isInterrupted()
|
Can you give me an Example of interrupting a thread that stops working?
|
In this example, after interrupting the thread, we are propagating it, so it will stop working. If we don't want to stop the thread, we can handle it where sleep() or wait() method is invoked. Let's first see the example where we are propagating the exception.
TestInterruptingThread1.java
class TestInterruptingThread1 extends Thread{
public void run(){
try{
Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[]){
TestInterruptingThread1 t1=new TestInterruptingThread1();
t1.start();
try{
t1.interrupt();
}catch(Exception e){System.out.println("Exception handled "+e);}
}
}
download this example
Output:
Exception in thread-0
java.lang.RuntimeException: Thread interrupted...
java.lang.InterruptedException: sleep interrupted
at A.run(A.java:7)
|
Can you provide an Example of interrupting a thread that doesn't stop working?
|
In this example, after interrupting the thread, we handle the exception, so it will break out the sleeping but will not stop working.
TestInterruptingThread2.java
class TestInterruptingThread2 extends Thread{
public void run(){
try{
Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
System.out.println("Exception handled "+e);
}
System.out.println("thread is running...");
}
public static void main(String args[]){
TestInterruptingThread2 t1=new TestInterruptingThread2();
t1.start();
t1.interrupt();
}
}
Output:
Exception handled
java.lang.InterruptedException: sleep interrupted
thread is running...
|
Can you give me an Example of interrupting thread that behaves normally?
|
If thread is not in sleeping or waiting state, calling the interrupt() method sets the interrupted flag to true that can be used to stop the thread by the java programmer later.
TestInterruptingThread3.java
class TestInterruptingThread3 extends Thread{
public void run(){
for(int i=1;i<=5;i++)
System.out.println(i);
}
public static void main(String args[]){
TestInterruptingThread3 t1=new TestInterruptingThread3();
t1.start();
t1.interrupt();
}
}
Output:
1
2
3
4
5
|
What about isInterrupted and interrupted method?
|
The isInterrupted() method returns the interrupted flag either true or false. The static interrupted() method returns the interrupted flag afterthat it sets the flag to false if it is true.
TestInterruptingThread4.java
public class TestInterruptingThread4 extends Thread{
public void run(){
for(int i=1;i<=2;i++){
if(Thread.interrupted()){
System.out.println("code for interrupted thread");
}
else{
System.out.println("code for normal thread");
}
}//end of for loop
}
public static void main(String args[]){
TestInterruptingThread4 t1=new TestInterruptingThread4();
TestInterruptingThread4 t2=new TestInterruptingThread4();
t1.start();
t1.interrupt();
t2.start();
}
}
Output:
Code for interrupted thread
code for normal thread
code for normal thread
code for normal thread
|
What is Reentrant Monitor in Java?
|
According to Sun Microsystems, Java monitors are reentrant means java thread can reuse the same monitor for different synchronized methods if method is called from the method.
|
What is the Advantage of Reentrant Monitor?
|
It eliminates the possibility of single thread deadlocking
|
What is Java I/O?
|
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
|
What is Stream in Java?
|
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and an error message to the console.
System.out.println("simple message");
System.err.println("error message");
Let's see the code to get input from console.
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
|
What is OutputStream?
|
Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral device or socket.
|
What is InputStream?
|
Java application uses an input stream to read data from a source; it may be a file, an array, peripheral device or socket.
|
What is OutputStream class?
|
OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.
|
Can you give me a Useful methods of OutputStream?
|
Useful methods of OutputStream
Method: public void write(int)throws IOException
Description: is used to write a byte to the current output stream.
Method: public void write(byte[])throws IOException
Description: is used to write an array of byte to the current output stream.
Method: public void flush()throws IOException
Description: flushes the current output stream.
Method: public void close()throws IOException
Description: is used to close the current output stream.
|
What is InputStream class?
|
InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes.
|
Can you provide a Useful method of InputStream?
|
Useful methods of InputStream
Method: public abstract int read()throws IOException
Description: reads the next byte of data from the input stream. It returns -1 at the end of the file.
Method: public int available()throws IOException
Description: returns an estimate of the number of bytes that can be read from the current input stream.
Method: public void close()throws IOException
Description: is used to close the current input stream.
|
What is Java FileOutputStream Class?
|
Java FileOutputStream is an output stream used for writing data to a file.
If you have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through FileOutputStream class. But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream.
|
How to use the FileOutputStream class declaration?
|
Let's see the declaration for Java.io.FileOutputStream class:
public class FileOutputStream extends OutputStream
|
FileOutputStream class methods
Method: protected void finalize()
Description: It is used to clean up the connection with the file output stream.
Method: void write(byte[] ary)
Description: It is used to write ary.length bytes from the byte array to the file output stream.
Method: void write(byte[] ary, int off, int len)
Description: It is used to write len bytes from the byte array starting at offset off to the file output stream.
Method: void write(int b)
Description: It is used to write the specified byte to the file output stream.
Method: FileChannel getChannel()
Description: It is used to return the file channel object associated with the file output stream.
Method: FileDescriptor getFD()
Description: It is used to return the file descriptor associated with the stream.
Method: void close()
Description: It is used to closes the file output stream.
|
|
What is Java FileInputStream Class?
|
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class.
|
What is Java FileInputStream class declaration?
|
Let's see the declaration for java.io.FileInputStream class:
public class FileInputStream extends InputStream
|
Can you give me the Java FileInputStream class methods?
|
Java FileInputStream class methods
Method: int available()
Description: It is used to return the estimated number of bytes that can be read from the input stream.
Method: int read()
Description: It is used to read the byte of data from the input stream.
Method: int read(byte[] b)
Description: It is used to read up to b.length bytes of data from the input stream
Method: int read(byte[] b, int off, int len)
Description: It is used to read up to len bytes of data from the input stream.
Method: long skip(long x)
Description: It is used to skip over and discards x bytes of data from the input stream.
Method: FileChannel getChannel()
Description: It is used to return the unique FileChannel object associated with the file input stream.
Method: FileDescriptor getFD()
Description: It is used to return the FileDescriptor object.
Method: protected void finalize()
Description: It is used to ensure that the close method is call when there is no more reference to the file input stream.
Method: void close()
Description: It is used to closes the stream.
|
What is Java BufferedOutputStream Class?
|
Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the syntax for adding the buffer in an OutputStream:
OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testout.txt"));
|
What is Java BufferedOutputStream class declaration?
|
Let's see the declaration for Java.io.BufferedOutputStream class:
public class BufferedOutputStream extends FilterOutputStream
|
Can you provide the Java BufferedOutputStream class constructors?
|
Java BufferedOutputStream class constructors
Constructor: BufferedOutputStream(OutputStream os)
Description: It creates the new buffered output stream which is used for writing the data to the specified output stream.
Constructor: BufferedOutputStream(OutputStream os, int size)
Description: It creates the new buffered output stream which is used for writing the data to the specified output stream with a specified buffer size.
|
What are the Java BufferedOutputStream class methods?
|
Java BufferedOutputStream class methods
Method: void write(int b)
Description: It writes the specified byte to the buffered output stream.
Method: void write(byte[] b, int off, int len)
Description: It write the bytes from the specified byte-input stream into a specified byte array, starting with the given offset
Method: void flush()
Description: It flushes the buffered output stream.
|
What is Java BufferedInputStream Class?
|
Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the performance fast.
The important points about BufferedInputStream are:
-When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the contained input stream, many bytes at a time.
-When a BufferedInputStream is created, an internal buffer array is created.
|
What is the class declaration for Java BufferedInputStream?
|
Let's see the declaration for Java.io.BufferedInputStream class:
public class BufferedInputStream extends FilterInputStream
|
What are the Java BufferedInputStream class constructors?
|
Java BufferedInputStream class constructors
Constructor: BufferedInputStream(InputStream IS)
Description: It creates the BufferedInputStream and saves it argument, the input stream IS, for later use.
Constructor: BufferedInputStream(InputStream IS, int size)
Description: It creates the BufferedInputStream with a specified buffer size and saves it argument, the input stream IS, for later use.
|
What are the Java BufferedInputStream class methods?
|
Java BufferedInputStream class methods
Method: int available()
Description: It returns an estimate number of bytes that can be read from the input stream without blocking by the next invocation method for the input stream.
Method: int read()
Description: It read the next byte of data from the input stream.
Method: int read(byte[] b, int off, int ln)
Description: It read the bytes from the specified byte-input stream into a specified byte array, starting with the given offset.
Method: void close()
Description: It closes the input stream and releases any of the system resources associated with the stream.
Method: void reset()
Description: It repositions the stream at a position the mark method was last called on this input stream.
Method: void mark(int readlimit)
Description: It sees the general contract of the mark method for the input stream.
Method: long skip(long x)
Description: It skips over and discards x bytes of data from the input stream.
Method: boolean markSupported()
Description: It tests for the input stream to support the mark and reset methods.
|
What is Java SequenceInputStream Class?
|
Java SequenceInputStream class is used to read data from multiple streams. It reads data sequentially (one by one).
|
What is the class declaration for Java SequenceInputStream?
|
Let's see the declaration for Java.io.SequenceInputStream class:
public class SequenceInputStream extends InputStream
|
What are the Constructors of SequenceInputStream class?
|
Constructors of SequenceInputStream class
Constructor: SequenceInputStream(InputStream s1, InputStream s2)
Description: creates a new input stream by reading the data of two input stream in order, first s1 and then s2.
Constructor: SequenceInputStream(Enumeration e)
Description: creates a new input stream by reading the data of an enumeration whose type is InputStream.
|
What are the Methods of SequenceInputStream class?
|
Methods of SequenceInputStream class
Method: int read()
Description: It is used to read the next byte of data from the input stream.
Method: int read(byte[] ary, int off, int len)
Description: It is used to read len bytes of data from the input stream into the array of bytes.
Method: int available()
Description: It is used to return the maximum number of byte that can be read from an input stream.
Method: void close()
Description: It is used to close the input stream.
|
Can you give me a Java SequenceInputStream Example?
|
In this example, we are printing the data of two files testin.txt and testout.txt.
package com.javatpoint;
import java.io.*;
class InputStreamExample {
public static void main(String args[])throws Exception{
FileInputStream input1=new FileInputStream("D:\\testin.txt");
FileInputStream input2=new FileInputStream("D:\\testout.txt");
SequenceInputStream inst=new SequenceInputStream(input1, input2);
int j;
while((j=inst.read())!=-1){
System.out.print((char)j);
}
inst.close();
input1.close();
input2.close();
}
}
Here, we are assuming that you have two files: testin.txt and testout.txt which have following information:
testin.txt:
Welcome to Java IO Programming.
testout.txt:
It is the example of Java SequenceInputStream class.
After executing the program, you will get following output:
Output:
Welcome to Java IO Programming. It is the example of Java SequenceInputStream class.
|
What is Java ByteArrayOutputStream Class?
|
Java ByteArrayOutputStream class is used to write common data into multiple files. In this stream, the data is written into a byte array which can be written to multiple streams later.
The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.
The buffer of ByteArrayOutputStream automatically grows according to data.
|
What is the class declaration for Java ByteArrayOutputStream?
|
Java ByteArrayOutputStream class is used to write common data into multiple files. In this stream, the data is written into a byte array which can be written to multiple streams later.
The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.
The buffer of ByteArrayOutputStream automatically grows according to data.
|
What are the Java ByteArrayOutputStream class constructors?
|
Constructors of Java ByteArrayOutputStream class
Constructor: ByteArrayOutputStream()
Description: Creates a new byte array output stream with the initial capacity of 32 bytes, though its size increases if necessary.
Constructor: ByteArrayOutputStream(int size)
Description: Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.
|
What are the Java ByteArrayOutputStream class methods?
|
Methods of Java ByteArrayOutputStream class
Method: int size()
Description: It is used to returns the current size of a buffer.
Method: byte[] toByteArray()
Description: It is used to create a newly allocated byte array.
Method: String toString()
Description: It is used for converting the content into a string decoding bytes using a platform default character set.
Method: String toString(String charsetName)
Description: It is used for converting the content into a string decoding bytes using a specified charsetName.
Method: void write(int b)
Description: It is used for writing the byte specified to the byte array output stream.
Method: void write(byte[] b, int off, int len
Description: It is used for writing len bytes from specified byte array starting from the offset off to the byte array output stream.
Method: void writeTo(OutputStream out)
Description: It is used for writing the complete content of a byte array output stream to the specified output stream.
Method: void reset()
Description: It is used to reset the count field of a byte array output stream to zero value.
Method: void close()
Description: It is used to close the ByteArrayOutputStream.
|
What is Java ByteArrayInputStream Class?
|
The ByteArrayInputStream is composed of two words: ByteArray and InputStream. As the name suggests, it can be used to read byte array as input stream.
Java ByteArrayInputStream class contains an internal buffer which is used to read byte array as stream. In this stream, the data is read from a byte array.
The buffer of ByteArrayInputStream automatically grows according to data.
|
What are the Java ByteArrayInputStream class constructors?
|
Constructors of Java ByteArrayInputStream class
Constructor: ByteArrayInputStream(byte[] ary)
Description: Creates a new byte array input stream which uses ary as its buffer array.
Constructor: ByteArrayInputStream(byte[] ary, int offset, int len)
Description: Creates a new byte array input stream which uses ary as its buffer array that can read up to specified len bytes of data from an array.
|
What are the Java ByteArrayInputStream class methods?
|
Methods of Java ByteArrayInputStream class
Method: int available()
Description: It is used to return the number of remaining bytes that can be read from the input stream.
Method: int read()
Description: It is used to read the next byte of data from the input stream.
Method: int read(byte[] ary, int off, int len)
Description: It is used to read up to len bytes of data from an array of bytes in the input stream.
Method: boolean markSupported()
Description: It is used to test the input stream for mark and reset method.
Method: long skip(long x)
Description: It is used to skip the x bytes of input from the input stream.
Method: void mark(int readAheadLimit)
Description: It is used to set the current marked position in the stream.
Method: void reset()
Description: It is used to reset the buffer of a byte array.
Method: void close()
Description: It is used for closing a ByteArrayInputStream.
|
What is Java DataOutputStream Class?
|
Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way.
Java application generally uses the data output stream to write data that can later be read by a data input stream.
|
What is the dedclaration for Java DataOutputStream?
|
Let's see the declaration for java.io.DataOutputStream class:
public class DataOutputStream extends FilterOutputStream implements DataOutput
|
What are the Java DataOutputStream class methods?
|
Methods of Java DataOutputStream class
Method: int size()
Description: It is used to return the number of bytes written to the data output stream.
Method: void write(int b)
Description: It is used to write the specified byte to the underlying output stream.
Method: void write(byte[] b, int off, int len)
Description: It is used to write len bytes of data to the output stream.
Method: void writeBoolean(boolean v)
Description: It is used to write Boolean to the output stream as a 1-byte value.
Method: void writeChar(int v)
Description: It is used to write char to the output stream as a 2-byte value.
Method: void writeChars(String s)
Description: It is used to write string to the output stream as a sequence of characters.
Method: void writeByte(int v)
Description: It is used to write a byte to the output stream as a 1-byte value.
Method: void writeBytes(String s)
Description: It is used to write string to the output stream as a sequence of bytes.
Method: void writeInt(int v)
Description: It is used to write an int to the output stream
Method: void writeShort(int v)
Description: It is used to write a short to the output stream.
Method: void writeShort(int v)
Description: It is used to write a short to the output stream.
Method: void writeLong(long v)
Description: It is used to write a long to the output stream.
Method: void writeUTF(String str)
Description: It is used to write a string to the output stream using UTF-8 encoding in portable manner.
Method: void flush()
Description: It is used to flushes the data output stream.
|
What is Java DataInputStream Class?
|
Java DataInputStream class allows an application to read primitive data from the input stream in a machine-independent way.
Java application generally uses the data output stream to write data that can later be read by a data input stream.
|
What is the declaration for Java DataInputStream?
|
Let's see the declaration for java.io.DataInputStream class:
public class DataInputStream extends FilterInputStream implements DataInput
|
What are the Java DataInputStream class Methods?
|
Methods of Java DataInputStream class
Method: int read(byte[] b)
Description: It is used to read the number of bytes from the input stream.
Method: int read(byte[] b, int off, int len)
Description: It is used to read len bytes of data from the input stream.
Method: int readInt()
Description: It is used to read input bytes and return an int value.
Method: byte readByte()
Description: It is used to read and return the one input byte.
Method: char readChar()
Description: It is used to read two input bytes and returns a char value.
Method: double readDouble()
Description: It is used to read eight input bytes and returns a double value.
Method: boolean readBoolean()
Description: It is used to read one input byte and return true if byte is non zero, false if byte is zero.
Method: int skipBytes(int x)
Description: It is used to skip over x bytes of data from the input stream.
Method: String readUTF()
Description: It is used to read a string that has been encoded using the UTF-8 format.
Method: void readFully(byte[] b)
Description: It is used to read bytes from the input stream and store them into the buffer array.
Method: void readFully(byte[] b, int off, int len)
Description: It is used to read len bytes from the input stream.
|
What is Java FilterOutputStream Class?
|
Java FilterOutputStream class implements the OutputStream class. It provides different sub classes such as BufferedOutputStream and DataOutputStream to provide additional functionality. So it is less used individually.
|
What isi the class declaration for Java FilterOutputStream?
|
Let's see the declaration for java.io.FilterOutputStream class:
public class FilterOutputStream extends OutputStream
|
What are the Java FilterOutputStream class Methods?
|
Methods of Java FilterOutputStream class
Method: void write(int b)
Description: It is used to write the specified byte to the output stream.
Method: void write(byte[] ary)
Description: It is used to write ary.length byte to the output stream.
Method: void write(byte[] b, int off, int len)
Description: It is used to write len bytes from the offset off to the output stream.
Method: void flush()
Description: It is used to flushes the output stream.
Method: void close()
Description: It is used to close the output stream.
|
What is Java FilterInputStream Class?
|
Java FilterInputStream class implements the InputStream. It contains different sub classes as BufferedInputStream, DataInputStream for providing additional functionality. So it is less used individually.
|
What is the class declaration for Java FilterInputStream?
|
Let's see the declaration for java.io.FilterInputStream class
public class FilterInputStream extends InputStream
|
What are the Java FilterInputStream class Methods?
|
Methods of Java FilterInputStream class
Method: int available()
Description: It is used to return an estimate number of bytes that can be read from the input stream.
Method: int read()
Description: It is used to read the next byte of data from the input stream.
Method: int read(byte[] b)
Description: It is used to read up to byte.length bytes of data from the input stream.
Method: long skip(long n)
Description: It is used to skip over and discards n bytes of data from the input stream.
Method: boolean markSupported()
Description: It is used to test if the input stream support mark and reset method.
Method: void mark(int readlimit)
Description: It is used to mark the current position in the input stream.
Method: void reset()
Description: It is used to reset the input stream.
Method: void close()
Description: It is used to close the input stream.
|
What is Java - ObjectStreamClass?
|
ObjectStreamClass act as a Serialization descriptor for class. This class contains the name and serialVersionUID of the class.
|
What is Java ObjectStreamField class?
|
Fields of Java - ObjectStreamClass
Modifier and Type: static ObjectStreamField[]
Field: NO_FIELDS
Description: serialPersistentFields value indicating no serializable fields
|
What is Java Console Class?
|
The Java Console class is be used to get input from console. It provides methods to read texts and passwords.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class is introduced since 1.5.
|
What is the class declaration for Java Console?
|
Let's see the declaration for Java.io.Console class:
public final class Console extends Object implements Flushable
|
What are the Java Console class methods?
|
Methods of Java Console class
Method: Reader reader()
Description: It is used to retrieve the reader object associated with the console
Method: String readLine()
Description: It is used to read a single line of text from the console.
Method: String readLine(String fmt, Object... args)
Description: It provides a formatted prompt then reads the single line of text from the console.
Method: char[] readPassword()
Description: It is used to read password that is not being displayed on the console.
Method: char[] readPassword(String fmt, Object... args)
Description: It provides a formatted prompt then reads the password that is not being displayed on the console.
Method: Console format(String fmt, Object... args)
Description: It is used to write a formatted string to the console output stream.
Method: Console printf(String format, Object... args)
Description: It is used to write a string to the console output stream.
Method: PrintWriter writer()
Description: It is used to retrieve the PrintWriter object associated with the console.
Method: void flush()
Description: It is used to flushes the console.
|
How to get the object of Console?
|
System class provides a static method console() that returns the singleton instance of Console class.
public static Console console(){}
Let's see the code to get the instance of Console class.
Console c=System.console();
|
Can you give me a Java Console Example?
|
import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
Output:
Enter your name: Nakul Jain
Welcome Nakul Jain
|
Can you give me a Java Console Example to read password?
|
import java.io.Console;
class ReadPasswordTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string
System.out.println("Password is: "+pass);
}
}
Output:
Enter password:
Password is: 123
|
What is Java FilePermission Class?
|
Java FilePermission class contains the permission related to a directory or file. All the permissions are related with path. The path can be of two types:
1) D:\\IO\\-: It indicates that the permission is associated with all sub directories and files recursively.
2) D:\\IO\\*: It indicates that the permission is associated with all directory and files within this directory excluding sub directories.
|
What is the class declaration for Java FilePermission?
|
Let's see the declaration for Java.io.FilePermission class:
public final class FilePermission extends Permission implements Serializable
|
What are the Methods of FilePermission class?
|
Methods of FilePermission class
Method: ByteArrayOutputStream()
Description: Creates a new byte array output stream with the initial capacity of 32 bytes, though its size increases if necessary.
Method: ByteArrayOutputStream(int size)
Description: Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.
|
What are the Java FilePermission class methods?
|
Methods of Java FilePermission class
Method: int hashCode()
Description: It is used to return the hash code value of an object.
Method: String getActions()
Description: It is used to return the "canonical string representation" of an action.
Method: boolean equals(Object obj)
Description: It is used to check the two FilePermission objects for equality.
Method: boolean implies(Permission p)
Description: It is used to check the FilePermission object for the specified permission.
Method: PermissionCollection newPermissionCollection()
Description: It is used to return the new PermissonCollection object for storing the FilePermission object.
|
Can you give me a Java FilePermission Example?
|
Let's see the simple example in which permission of a directory path is granted with read permission and a file of this directory is granted for write permission.
package com.javatpoint;
import java.io.*;
import java.security.PermissionCollection;
public class FilePermissionExample{
public static void main(String[] args) throws IOException {
String srg = "D:\\IO Package\\java.txt";
FilePermission file1 = new FilePermission("D:\\IO Package\\-", "read");
PermissionCollection permission = file1.newPermissionCollection();
permission.add(file1);
FilePermission file2 = new FilePermission(srg, "write");
permission.add(file2);
if(permission.implies(new FilePermission(srg, "read,write"))) {
System.out.println("Read, Write permission is granted for the path "+srg );
}else {
System.out.println("No Read, Write permission is granted for the path "+srg); }
}
}
Output:
Read, Write permission is granted for the path D:\IO Package\java.txt
|
What is Java Writer?
|
It is an abstract class for writing to character streams. The methods that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses will override some of the methods defined here to provide higher efficiency, functionality or both.
|
Can you give me a Java Writer Example?
|
import java.io.*;
public class WriterExample {
public static void main(String[] args) {
try {
Writer w = new FileWriter("output.txt");
String content = "I love my country";
w.write(content);
w.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Done
output.txt:
I love my country
|
What is Java Reader?
|
Java Reader is an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). Most subclasses, however, will override some of the methods to provide higher efficiency, additional functionality, or both.
Some of the implementation class are BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, StringReader
|
What is Java FileWriter Class?
|
Java FileWriter class is used to write character-oriented data to a file. It is character-oriented class which is used for file handling in java.
Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to write string directly.
|
What is the declaration for Java FileWriter?
|
Let's see the declaration for Java.io.FileWriter class:
public class FileWriter extends OutputStreamWriter
|
What are the Constructors of FileWriter class?
|
Constructors of FileWriter class
Constructor: FileWriter(String file)
Description: Creates a new file. It gets file name in string.
Constructor: FileWriter(File file)
Description: Creates a new file. It gets file name in File object.
|
What are the Methods of FileWriter class?
|
Methods of FileWriter class
Method: void write(String text)
Description: It is used to write the string into FileWriter.
Method: void write(char c)
Description: It is used to write the char into FileWriter.
Method: void write(char[] c)
Description: It is used to write char array into FileWriter.
Method: void flush()
Description: It is used to flushes the data of FileWriter.
Method: void close()
Description: It is used to close the FileWriter.
|
Can you give mee a Java FileWriter Example?
|
In this example, we are writing the data in the file testout.txt using Java FileWriter class.
package com.javatpoint;
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
Output:
Success...
testout.txt:
Welcome to javaTpoint.
|
What is Java FileReader Class?
|
Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.
It is character-oriented class which is used for file handling in java.
|
What is Java FileReader class declaration?
|
Let's see the declaration for Java.io.FileReader class:
public class FileReader extends InputStreamReader
|
Can you give me the Constructors of FileReader class?
|
Constructors of FileReader class
Constructor: FileReader(String file)
Description: It gets filename in string. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException.
Constructor: FileReader(File file)
Description: It gets filename in file instance. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.