Updates
  • Starting New Weekday Batch for Java Full Stack Developer on 24th June 2024 @ 02:00 PM to 04:00 PM
  • Starting New Weekend Batch for Java Full Stack Developer on 06th July 2024 @ 11:00 AM to 02:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 08th July 2024 @ 04:00 PM to 06:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 29th July 2024 @ 10:00 AM to 12:00 PM
Join Course

java.lang.System

• System class is a built in class which is available in java.lang package.
• It is a final type of class, so the class cannot become a sub class of java.lang.System class.
• There is only one constructor in java.lang.System class which is default constructor and it has private access modifier.

            
class JTC{
	public static void main(String arg[]){

		StringBuilder s1 = new StringBuilder("Hello");
		StringBuilder s2 = s1.append("JTC");

		System.out.println("s1 :- "+s1);
		System.out.println("s2 :- "+s2);
		System.out.println("s1 == s2 :- "+(s1 == s2));
	}
} 

In the above example as we can see in class JTC we have a main method and in main method we are creating an object of System class using their default constructor; as we have discussed that the default constructor of java.lang.System class has private access and that is the reason we are getting the error message at the time of compilation: System () has private access in System.

Java.lang.System class

public final class java.lang.System {
public static final java.io.InputStream in;
public static final java.io.PrintStream out;
public static final java.io.PrintStream err;
public static void setIn(java.io.InputStream);
public static void setOut(java.io.PrintStream);
public static void setErr(java.io.PrintStream);
public static java.io.Console console();
public static java.nio.channels.Channel inheritedChannel() throws java.io.IOException;
public static void setSecurityManager(java.lang.SecurityManager);
public static java.lang.SecurityManager getSecurityManager();
public static native long currentTimeMillis();
public static native long nanoTime();
public static native void arraycopy(java.lang.Object, int, java.lang.Object, int, int);
public static native int identityHashCode(java.lang.Object);
public static java.util.Properties getProperties();
public static java.lang.String lineSeparator();
public static void setProperties(java.util.Properties);
public static java.lang.String getProperty(java.lang.String);
public static java.lang.String getProperty(java.lang.String, java.lang.String);
public static java.lang.String setProperty(java.lang.String, java.lang.String);
public static java.lang.String clearProperty(java.lang.String);
public static java.lang.String getenv(java.lang.String);
public static java.util.Map<java.lang.String, java.lang.String> getenv();
public static void exit(int);
public static void gc();
public static void runFinalization();
public static void runFinalizersOnExit(boolean);
public static void load(java.lang.String);
public static void loadLibrary(java.lang.String);
public static native java.lang.String mapLibraryName(java.lang.String);
static {};
}

• Important member of java.lang.System class: -

1. public static final java.io.InputStream in;

Access Modifier: - public
Types of Variable: - static final variable
Data Type: - java.io.InputStream
Variable Name: - in
Functionality: - It stores the java.io.InputStream type object reference and that object is configured with keyboard by default. Hence Java program using “in” variable accept keyboard inputs by default.

            
import java.util.Scanner;

class A{
	public static void main(String arg[]){

		System.out.println("Enter Input :- ");
		Scanner s1 = new Scanner(System.in);
		String input = s1.nextLine();
		System.out.println("Input is :- "+input);
	}
}
    Enter Input :-
    34
    Input is :- 34
            

In the above program we have a class which is A and in main method of class A we are creating an object of java.util.Scanner class, which enables taking in different types of inputs in java program like int, double and String etc.

As we can see that at the time of Scanner class object creation, we are passing System.in as argument. This means we are defining the source of input and as we know System.in has a default input source which is the keyboard. So, in this example we take the input from keyboard.

2. public static void setIn(java.io.InputStream); :-

Access Modifier: - public
Types of Member: - static method
Return Type: - void
Method Name: - setIn()
Parameter: - java.io.InputStream
Functionality: - By default System.in takes the input from keyboard. However, using setIn() methods we can change the source of input as per the requirement.

            
import java.io.FileInputStream;

class JTC {

   public static void main(String[] args) throws Exception {
    
      // existing file
      System.setIn(new FileInputStream("file.txt"));

      // read first character from the file
      char c1 = (char)System.in.read();
      // returns the first character
      System.out.println(c1);              
   }
}

File.txt:-

In this example we are taking the input from file.txt file, as we know System.in contains java.io.InputStream type object which is configured with keyboard by default.
As we can see in this example that first we are creating an object of java.io.FileInputStream class (new FileInputStream (“file.txt”)) which is the sub class of java.io.InputStream class and at the time of FileInputStream class object creation we are passing “file.txt” as an argument which is the source file name from where we will take the input. If required source file is not available on their location then we get an exception at runtime which is java.io.FileNotFoundException

After the creation of java.io.FileOutputStream class object we pass it as an argument of System.setIn(new FileInputStream(“file.txt”)) method which is dedicated to change the object reference of System.in.

In the next section we are using read() method of java.io.InputStream class which is dedicated to read the next byte of data from the Input Stream; because the return type of read() method is int so we are typecasting the return into char type and thereafter storing this return in the char type variable char c1, and finally we are printing the value of c1.

3. public static final java.io.PrintStream out;: -

Access Modifier: - public
Types of Variable: - static final variable
Data Type: - java.io.PrintStream
Variable Name: - out
Functionality: - It stores the java.io.PrintStream class object reference. Using this object we supply the output of a particular destination, by default destination of System.out object is console and that is the reason we get all the output on console by default.

4. public static void setOut(java.io.PrintStream); :-

Access Modifier: - public
Types of Member: - static method
Return Type: - void
Method Name: - setOut()
Parameter: - java.io.PrintStream
Functionality: - As we know default source of System.out object is console but using setOut method we can change the destination as per the business logic, like we do with a file.

            
import java.io.*;

class JTC {

   public static void main(String[] args) throws Exception {

    
      // create file
      FileOutputStream f = new FileOutputStream("file.txt");

      System.setOut(new PrintStream(f));

      // this text will get redirected to file
      System.out.println("Welcome to the JTC TUTORIAL !!!");
   }
}

In the above example we will understand how we can change the default destination of System.out object using System.setOut().

In the first section of the example we are creating an object of java.io.FileOutputStream class (FileOutputStream f = new FileOutputStream("file.txt")) which is dedicated to create a file on a location and open it in write mode.

Thereafter we invoke System.setOut() and pass an object of java.io.PrintStream class which is configured with FileOutputStream class object (System.setOut(new PrintStream(f))). This code is dedicated to create a new object of java.io.PrintStream class which uses file.txt as destination and their reference is set into System.out.

And finally output of System.out.println(“Welcome to the JTC TUTORIAL !!!”) comes into the file.txt.

5. public static final java.io.PrintStream err; :-

Access Modifier: - public
Types of Variable: - static final variable
Data Type: - java.io.PrintStream
Variable Name: - err
Functionality: - The method yields standard error output stream which is almost similar to the System.out, but generally we use this output stream to display error messages or other information that should come to the immediate attention of a user. In normal cmd we get the same output as System.out, but on certain IDE like eclipse when we use System.err then we get the output in Red colour that represents the error message.

            
class A{
public static void main(String arg[]){
			System.out.println("Normal Text");
			System.err.println("Error Text");
		}
}
    Normal Text
    Error Text
            
6. public static void setErr(java.io.PrintStream); :-

Access Modifier: - public
Types of Member: - static method
Return Type: - void
Method Name: - setErr()
Parameter: - java.io.PrintStream
Functionality: - The default destination of System.err is console as System.out. setErr() method is dedicated to change the destination of System.err as per the requirement.

            
import java.io.*;

class JTC {

   public static void main(String[] args) throws Exception {
    
      // create file
      FileOutputStream f = new FileOutputStream("file.txt");

      System.setErr(new PrintStream(f));

      System.err.println("This is the error message");
   }
}
            

In the above example we will understand how we can change the default destination of System.err object using Syste.setErr().

In the first section of the example we are creating an object of java.io.FileOutputStream class (FileOutputStream f = new FileOutputStream("file.txt")) which is dedicated to create a file on a location and open it in write mode.

Thereafter we are invoking System.setErr() and pass an object of java.io.PrintStream class which is configured with FileOutputStream class object (System.setOut(new PrintStream(f))), this code is dedicated to create a new object of java.io.PrintStream class which uses file.txt as destination and set their reference into System.err.

Finally output of System.err.println(“This is the error message") comes into the file.txt.

7. public static void exit(int);

Access Modifier: - public
Types of Member: - static method
Return Type: - void
Method Name: - exit()
Parameter: - int
Functionality: - It terminates the current running Java Virtual Machine, internally it invokes the java.lang.Runtime class exit(int) method and int type parameter represent the status code, when we pass a non-zero value then it indicates the abnormal termination.
Abnormal termination means that the JVM has been terminated abnormally without the proper closure of all the system resources . In normal termination all the system resources are closed properly before the termination of the program.

            
class A{
	public static void main(String arg[]){
		System.out.println("Before Exit()");
		System.exit(0);
		System.out.println("After Exit()");
	}
}
    Before Exit()
            

In the above example as we can see that we are invoking System.exit(0) method. Once the control moves to the exit() method invocation occurs immediately and the JVM terminates.

8. public static native void arraycopy(java.lang.Object, int, java.lang.Object, int, int);:-

Access Modifier: - public
Types of Member: - static method
Return Type: - void
Method Name: - arraycopy()
Parameter: - java.lang.Object, int, java.lang.Object, int, int
Functionality: - arraycopy() method of java.lang.System class is used to copy element of one array to another array. The first parameter java.lang.Object is the source from which array has to copied. First the int parameter specifies the index position of the source array from where the array has to be copied, next java.lang.Object parameter is a destination array in which array has to be copied. Thereafter int parameter specifies the index of destination array where you need to store the copy elements, lastly the int parameter specifies the number of parameters that do not have to be copied.

            
class A{
	public static void main(String arg[]){

		String source[] = {"Welcome","To","JTC","Tutorial","This","Is","System","Class"};

		String destination[] = new String [8];
		
		System.out.println("---Destnation Array Before Operation---");
		
		for(int i = 0; i <= destination.length-1;i++){
			System.out.println("Index :- "+i+" Value :- "+destination[i]);
		}

		System.arraycopy(source,1,destination,1,4);
		
		System.out.println("---Destnation Array After Operation---");
		
		for(int i = 0; i <= destination.length-1;i++){
			System.out.println("Index :- "+i+" Value :- "+destination[i]);
		}

	}
}
    ---Destnation Array Before Operation---
    Index :- 0 Value :- null
    Index :- 1 Value :- null
    Index :- 2 Value :- null
    Index :- 3 Value :- null
    Index :- 4 Value :- null
    Index :- 5 Value :- null
    Index :- 6 Value :- null
    Index :- 7 Value :- null
    ---Destnation Array After Operation---
    Index :- 0 Value :- null
    Index :- 1 Value :- To
    Index :- 2 Value :- JTC
    Index :- 3 Value :- Tutorial
    Index :- 4 Value :- This
    Index :- 5 Value :- null
    Index :- 6 Value :- null
    Index :- 7 Value :- null
            

In the above example we can see that first we have String type array (String source[] = {"Welcome","To","JTC","Tutorial","This","Is","System","Class"}) it is the source array from which we want to copy the data. After that we have declared a dynamic String type array (String destination [] = new String [8]), where we want to store the copied elements from source array.

As we can see, we are traversing the destination array using for loop before arraycopy () method invocation and that is the reason all the elements of destination [] array is null.

Finally we invoke the System.arraycopy(source,1destination,1,4). This statement represents that copy operation will start from source[1], it stores the copied elements into destination from 1st index and last argument of arraycopy() which is 4 i.e. only 4 elements will copy from source[] array.