This is one of the useful class in java which is present in java.lang package. We can't instantiate this class manually means we can't create object of this class but still this class is having empty constructor. You can't
create sub-class of System class because it is final by nature. This class gives us in, out and err streams. All these three streams are public static and final by nature. These streams are public so that you can
access them from outside of System class, static so that you can access them without creating object of System class and final for avoiding overriding of these streams. These streams are already open and are ready to
process data. Let's take a look at each one of these.
1. System.in:-
This is of type InputStream. This is connected to keyboard by default but we can redirect this to some other input device. InputStream class is from java.io package and abstract by nature. InputStream class is superclass of all byte oriented input streams. This class is not having any constructor.
2. System.out:-
This is of type PrintStream. This is connected to monirot by default but we can redirect this to some other output device. PrintStream class is from java.io package. This class is having many different constructors.
3. System.err:-
This is of type PrintStream. This is connected to monitor by default but we can redirect to some other output device.
Now lets see one example of redirecting stream to some other resource. In below example we are redirecting out stream to file.
import java.io.*;
class SystemClass
{
public static void main(String[] args) throws Exception
{
File f = new File("c:\\java\\test.txt");
PrintStream fout = new PrintStream(f);
System.setOut(fout);
System.out.print("This is test."); // This output will be written in test.txt file.
}
}
In this way you can play wilth other streams.
Another important facility provided by System class is System.arraycopy() function. This is native function in System class which is static by nature so you can use it directly. This function will perform faster than our
normal array copy logic. Here is one simple example of arraycopy function.
class SystemClass
{
public static void main(String[] args)
{
int srcAry[] = new int[10];
int destAry[] = new int[10];
for(int i = 0; i < 10; i++)
{
srcAry[i] = i;
destAry[i] = -1;
System.out.print("\nSrc : " + srcAry[i] + " ::: destAry : " + destAry[i]);
}
System.arraycopy(srcAry, 0, destAry, 0, 4);
System.out.print("\n\n\n\n\n");
for(int i = 0; i < 10; i++)
{
System.out.print("\nSrc : " + srcAry[i] + " ::: destAry : " + destAry[i]);
}
}
}
System class provides another native method called System.identityHashCode(). This is static method. It will return same hash code for one program execution for one object.
You can continue reading here,
http://tech-world-brij.blogspot.in/2013/05/system-class-2-java.html
No comments:
Post a Comment