Class System in Java

The System class contains several useful methods and member elements. As all the members of the System class are static, we do not need to instantiate this class. We can directly call them By using the System. (member name) like-System.in or System.out etc. System class provides the methods that provide a platform-independent interface to system functionality.

The System class provides access to various information about the operating system environment in which a program is running. For example, the System class defines variables that allow access to the standard I/O streams and methods that allow a program to run the garbage collector and stop the Java virtual machine.

All of the variables and methods in the System class are static. In other words, it is not necessary to create an instance of the System class to use its variables and methods. The System class does not define any public constructors, so it cannot be instantiated.

The System class supports the concept of system properties that can be queried and set. The following properties are guaranteed always to be defined:

 

Property NameMeaning
file.encodingThe character encoding for the default locale
file.encoding.pkgThe package that contains converters between local encodings and Unicode
file.separatorFile separator (‘/’ on UNIX, ‘ \’ on Windows)
java.class.pathThe classpath
java.class.versionJava class version number
java.compilerThe just-in-time compiler to use, if any
java.homeJava installation directory
java.vendorJava vendor-specific string
java.vendor.urlJava vendor URL
java.versionJava version number
line.separatorLine separator(‘ \n’ on UNIX, ‘ \r\n’ on Windows)
os.archOperating system architecture
os.nameOperating system name
os.versionOperating system version
path.separatorPath separator (‘:’ on UNIX, ‘,’ on Windows)
user.dirUser’s current working directory when the properties were initialized
user.homeUser’s home directory
user.languageThe two-letter language code of the default locale
user.nameUser’s account name
user.regionThe two-letter country code of the default locale
user.timezoneThe default time zone

Additional properties may be defined by the run-time environment. The -D command-line option can be used to define system properties when a program is run.

The Runtime class is related to the System class; it provides access to information about the environment in which a program is running.

The structure of Class System in Java is given as:

public final class java.lang.System extends java.lang.Object{
//Member elements:
public static final InputStream in;// This is the standard inputStream and it is already opened by JVM. It is ready to supply input data. This stream takes input from keyboard.But this can be configured to take input from any other  source.
public static final PrintStream err;//This corresponds to standard error Stream.
public static final PrintStream  out; //This is the standard output stream and it is already opened to provide output data.This stream prints output to display or console but can be configured to other output destination.
//Methods:
public static native void arrayCopy(Object Array_Src,int src_position,Object Array_Dest,int dest_position,int length);
public static native long currentTimeMills();
public static void exit(int status);
public static void gc();
public static Properties getProperties();
public static String getProperty(String key);
public static String getProperty(String key,String def);
public static String getenv(String name);
public static SecurityManager getSecurityManager();
public static void load(String fileName);
public static void loadLibrary(String libFileName);
public static void runFinalization();
public static void setProperties(Properties prop);
public static void setSecurityManager(SecurityManager sm);
public static native int identityHashCode(Object obj);
public static void runFinalizersOnExit(boolean value);
public static void setErr(PrintStream err);
public static void setIn(InputStream in);
public static void setOut(PrintStream out);
}
 

The details of the class structure are given as follows:

public static final InputStream in;

public static final InputStream in describes The standard input stream. In an application environment, this variable refers to a java.io.InputStream object that is associated with the standard input for the process running the Java virtual machine.

The value of in can be set using the setIn() method. The value of in can only be set if the currently installed SecurityManager does not throw a SecurityException when the request is made.
Before Java 1.1, it was not final. It has been made final as of Java 1.1 because the unchecked ability to set in is a security hole.

public static final PrintStream err;

public static final PrintStream err describes the standard error stream. In an application environment, this variable refers to a java.io.PrintStream object that is associated with the standard error output for the process running the Java virtual machine. In an applet environment, the PrintStream is likely to be associated with a separate window, although this is not guaranteed.

The value of err can be set using the setErr() method. The value of err can only be set if the
currently installed SecurityManager does not throw a SecurityException when the request is
made.

Before Java 1.1, err was not final. It has been made final as of Java 1.1 because the unchecked ability to set err is a security hole.

public static final PrintStream  out;

public static final PrintStream out describes The standard output stream. In an application environment, this variable refers to a java.io.PrintStream object that is associated with the standard output for the process running the Java virtual machine. In an applet environment, the PrintStream is likely to be associated with a separate window, although this is not guaranteed.

out is the most commonly used of the three I/O streams provided by the System class. Even in GUI-based applications, sending output to this stream can be useful for debugging. The usual idiom for sending output to this stream is:
System.out.println(“Some text”);
The value of out can be set using the setOut() method. The value of out can only be set if the currently installed SecurityManager does not throw a SecurityException when the request is made.

Before to Java 1.1, out was not final. It has been made final as of Java 1.1 because the unchecked ability to set out is a security hole.

public static native void arrayCopy(Object Array_Src,int src_position,Object Array_Dest,int dest_position,int length);

public static native void arrayCopy(Object Array_Src,int src_position,Object Array_Dest,int dest_position,int length) method copies a range of array elements from the src array to the dst array. The number of elements that are copied is specified by length. The elements at positions src_position through src_position+length-1 in src are copied to the positions dst_position through dst_position+length-1 in Array_Dest, respectively.

If Array_Src and Array_Dest refer to the same array, the copying is done as if the array elements were first copied to a temporary array and then copied to the destination array.

Before this method does any copying, it performs several checks. If either Array_Src or Array_Dest is null, the method throws a NullPointerException and Array_Dest is not modified.

If any of the following conditions are true, the method throws an ArrayStoreException, and Array_Dest  is not modified:

  • Either src or Array_Dest  refers to an object that is not an array.
  • Array_Src and Array_Dest  refer to arrays whose element types are different primitive types.
  • Array_Src refers to an array that has elements that contain a primitive type, while Array_Dest  refers to an array that has elements that contain a reference type, or vice versa.

If any of the following conditions are true, the method throws an ArrayIndexOutOfBoundsException, and Array_Dest  is not modified:

  • Array_SrcOffset, Array_DestOffset, or length is negative.
  • Array_SrcOffset+length is greater than Array_Src.length().
  • Array_DestOffset+length is greater than Array_Dest.length().

Otherwise, if an element in the source array being copied cannot be converted to the type of the destination array using the rules of the assignment operator, the method throws an ArrayStoreException when the problem occurs. Since the problem is discovered during the copy operation, the state of the Array_Dest array reflects the incomplete copy operation.

Parameter
Array_Src – The source array.
src_position – An index into the source array.
Array_Dest – The destination array.
dest_position – An index into the destination array.
length – The number of elements to be copied.

public static native long currentTimeMills();

public static native long currentTimeMills() method returns the current time as the number of milliseconds since 00:00:00 UTC, January 1, 1970. It will not overflow until the year 292280995. The java.util.Date class provides more extensive facilities for dealing with times and dates.
This method returns the current time as the number of milliseconds since 00:00:00 UTC, January 1, 1970.

public static void exit(int status);

public static void exit(int status) method causes the Java virtual machine to exit with the given status code. This method works by calling the exit() method of the current Runtime object. By convention, a nonzero status code indicates abnormal termination. This method never returns.

Parameter
status – The exit status code to use.

public static void gc();

public static void gc() method causes the Java virtual machine to run the garbage collector in the current thread. This method works by calling the gc() method of the current Runtime object.

The garbage collector finds objects that will never be used again because there are no live references to them. After it finds these objects, the garbage collector frees the storage occupied by these objects.

The garbage collector is normally run continuously in a thread with the lowest possible priority so that it works intermittently to reclaim storage. The gc() method allows a program to invoke the garbage collector explicitly when necessary.

public static Properties getProperties();

public static Properties getProperties() method returns all of the defined system properties encapsulated in a java.util.Properties object. If there are no system properties currently defined, a set of default system properties is created and initialized. As discussed in the description of the System class, some system properties are guaranteed always to be defined.

This method returns a Properties object that contains the values of all the system properties.

public static String getProperty(String key);

public static String getProperty(String key) method returns the value of the named system property. If there is no definition for the named property, the method returns null. If there are no system properties currently defined, a set of default system properties is created and initialized. As discussed in the description of the System class, some system properties are guaranteed always to be defined.

This method returns the value of the named system property or null if the named property is not defined.

Parameter
key – The name of a system property.

public static String getProperty(String key,String def);

public static String getProperty(String key, String def) method returns the value of the named system property. If there is no definition for the named property, the method returns the default value as specified by the def parameter. If there are no system properties currently defined, a set of default system properties is created and initialized. As discussed earlier in the description of the System class, some system properties are guaranteed to always be defined.

This method returns the value of the named system property, or the default value if the named property is not defined.
Parameter
key -The name of a system property.
def – A default value for the property.

public static String getenv(String name);

public static string getenv(String name) method is obsolete; it always throws an error. Use getProperties() and the -D option instead.
This method returns the value of the environment variable or null if the variable is not defined.
Parameter
name – The name of a system-dependent environment variable.

public static SecurityManager getSecurityManager();

public static SecurityManager getSecurityManager() method returns a reference to the installed SecurityManager object. If there is no SecurityManager object installed, the method returns null.

This method returns a reference to the installed SecurityManager object or null if there is no SecurityManager object installed.

public static void load(String fileName);

public static void load(String fileName) method loads the specified dynamically linked library. This method works by calling the load() method of the current Runtime object.

Parameter
filename – A string that specifies the complete path of the file to be loaded.

public static void loadLibrary(String libFileName);

public static void loadLibrary(String libFileName) method loads the specified dynamically linked library. It looks for the specified library in a platform-specific way. This method works by calling the loadLibrary() method of the current Runtime object.

Parameter
libFileName – A string that specifies the name of a dynamically linked library.

public static void runFinalization();

public static void runFinalization() method causes the Java virtual machine to run the finalize() methods of any objects in the finalization queue in the current thread. This method works by calling the runFinalization() method of the current Runtime object.

When the garbage collector discovers that there are no references to an object, it checks to see if the object has a finalize() method that has never been called. If the object has such a finalize() method, the object is placed in the finalization queue. While there is a reference to the object in the finalization queue, the object is no longer considered garbage collectible.

Normally, the objects in the finalization queue are handled by a separate finalization thread that runs continuously at a very low priority. The finalization thread removes an object from the queue and calls its finalize() method. As long as the finalize() method does not generate a reference to the object, the object again becomes available for garbage collection.
Because the finalization thread runs at a very low priority, there may be a long delay from the time that an object is put on the finalization queue until the time that its finalize() method is called.

The runFinalization() method allows a program to run the finalize() methods explicitly. This can be useful when there is a shortage of some resource that is released by a finalize() method.

 

public static void setProperties(Properties prop);

public static void setProperties(Properties prop) method replaces the current set of system property definitions with a new set of system property definitions that are encapsulated by the given Properties object.

As discussed in the description of the System class, some system properties are guaranteed to always be defined.

Parameter
prop – A reference to a Properties object.

public static void setSecurityManager(SecurityManager sm);

public static void setSecurityManager(SecurityManager sm) method installs the given SecurityManager object. If s is null, then no SecurityManager object is installed. Once a SecurityManager object is installed, any subsequent calls to this method throw a SecurityException.

Parameter
sM – A reference to a SecurityManager object.

public static native int identityHashCode(Object obj);

public static native int identityHashCode(Object obj) method returns the same hashcode value for the specified object as would be returned by the default hashCode() method of Object, regardless of whether or not the object’s class overrides hashCode().

This method returns the identity hashcode value for the specified object.
Parameter
obj – An object.

public static void runFinalizersOnExit(boolean value);

public static void runFinalizersOnExit(boolean value) method specifies whether or not the finalize() methods of all objects that have to finalize() methods are run before the Java virtual machine exits.

By default, the finalizers are not run on exit. This method works by calling the runFinalizersOnExit() method of the current Runtime object.
Parameter
value -A boolean value that specifies whether or not finalization occurs on exit.

public static void setErr(PrintStream err);

public static void setErr(PrintStream err) method sets the standard error stream to be this PrintStream object.
Parameter
err – A PrintStream object to use for the standard error stream.

public static void setIn(InputStream in);

public static void setIn(InputStream in) method sets the standard input stream to be this InputStream object.
Parameter
in – A InputStream object to use for the standard input stream.

public static void setOut(PrintStream out);

public static void setOut(PrintStream out) method sets the standard output stream to be this PrintStream object.
Parameter
out – A PrintStream object to use for the standard output stream.

Apart from these System class also has inherited methods from class- Object. They are as follows:

  • clone()
  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)

Example:

What is System.out.println?

System.out.Prinln() method writes a line to console as output data. The System.out corresponds to the OutputStream as described above and does not need to instantiate the System class. As they are static we can directly call them. pritln() method is defined in the PrintStream class.

From day one while learning Java we use to give this command to print some value to console. It may be for output purposes or debugging purposes.

Now let us understand what is System, what is out and what is println?
The system is a built-in class that is present in java.lang package. This class is of final modifier type so it can not be inherited to other classes. or it can not be instantiated. This package defines a class called System. The System class holds a collection of static methods and variables.the standard input, output and error output of the java runtime are stored in, out, err variables.

out is a static final field (ie, variable)in System class which is of the type PrintStream (a built-in class, contains methods to print the different data values).

static fields and methods must be accessed by using the class name, so ( System.out ).  Simply..out is a static member of type PrinStream class(java.io) declared in the System class. static members of a class can be accessed directly by classname that’s why System.out.out here denotes the reference variable of the type PrintStream class. As this is of type static,

  1. It gets instantiated as soon as the class is loaded.
  2. It creates a mapping with the console where the program is running
  3. The stream becomes open and ready for accepting data.

println() is a public method in PrintStream class to print the data values. Hence to access a method in PrintStream class, we use it out.println() (as nonstatic methods and fields can only be accessed by using the reference variable).

As we discussed println() method is a member of the out object which is a static data member of System class. println() always appends a newline character to the end of the string i.e any subsequent output will start on a new line.

 double x=5;
double y;
y=Math.sqrt(x);
system.out.println("y"+y);

Here + stands for concatenation operator of two strings. The double value of y is converted to an equivalent string and concatenated with the initial string.
Note- There are multiple println() method exists with different parameters.
The code snippet might help you to understand better…

public final class java.lang.System {    
public static final java.io.PrintStream out;     
// some methods . . .     
}     
public class java.io.PrintStream extends.......{     
public void println(....){     
. .     
}     
}

More details to find on java.lang.system class check out here..

So this command can not be altered and package can not be modified. We can not create our own variable to do print.

like

system.XYZ.print(“Test”);

is invalid

==============================================
But surely you can represent this method in different other ways…
One of the way may be–

import java.io.*;
public class Animesh
{
private static PrintStream out = System.out;
public static void main(String args[])
{
out.println("This is good");
}
}

Here instead of System.out.println() we are using out.println()
==============================================
Another way may be–

import javax.swing.JOptionPane;    
import java.io.*;     
public class animesh {
public static void main(String[] args) {
String str=JOptionPane.showInputDialog("enter data");
System.out.println(str);
animesh d=new animesh();
d.print(str);
}
public void print(Object obj){
System.out.println(obj.toString());
}
}

Here I have modified some other way….here instead of System.out.println() I am using d.print(str).These are all wrapper technique on top of System.out.println()  Nothing else!!

How to Run Java Program Without Main Function??

In Java, a static initializer gets executed as soon as the class is
loaded, even before the main method is called!!!.

So if we create a static block and give some command inside it. It will execute. The JVM finds and loads the class into memory when you run this code, the static initializer is executed during the loading and initialization of the class.
But my suggestion does not use this feature while developing your application. And even if you use this feature please make sure to incorporate
System.exit(0); After your code
System.exit(0) is called at the end of the static block to terminates the program. If not, then the JVM would have next used reflection on that class to find the main() method. If it does not find the main method, it throws an exception. if we don’t write main() in the program then the compiler doesn’t know
where to start the program…

public class WithoutMain {
static {
System.out.println( "Hello World" );
System.exit(0);
}
}
Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

I am the founder and owner of the blog - TechTravelHub.com, always love to share knowledge on test automation,tools,techniques and tips.I am a passionate coder of Java and VBScript.I also publish articles on Travel ideas and great honeymoon destinations.Apart from these, I am a gear-head,love to drive across India. I have shared lots of articles here on How to travel several parts of India.Customization of cars aka car modification is my another hobby.Get in touch with me on [email protected]

Write A Comment