Java.lang.System class in Java

Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array. It extends class Object.
Fields:

  1. public static final InputStream in: The “standard” input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.
  2. public static final PrintStream out: The “standard” output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
  3. public static final PrintStream err: The “standard” error output stream. This stream is already open and ready to accept output data.
    Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out, has been redirected to a file or other destination that is typically not continuously monitored.

Methods:

  1. static void arraycopy(Object source, int sourceStart, Object Target, int targetStart, int size): Copies an array. The array to be copied is passed in source, and the index at which point the copy will begin within source is passed in sourceStart. The array that will receive the copy is passed in target, and the index which point the copy will begin within the target is passed in targetStart. Size is the number of elements that are copied.

    Syntax: public static void arraycopy(Object source, 
    int sourceStart, Object Target, int targetStart, int size)
    Returns: NA.
    Exception: 
    IndexOutOfBoundsException - if copying would cause access of data 
    outside array bounds.
    ArrayStoreException - if an element in the source array could not 
    be stored into the target array because of a type mismatch.
    NullPointerException - if either source or target is null.
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating arraycopy() method
    import java.lang.*;
    import java.util.Arrays;
    class SystemDemo
    {
        public static void main(String args[])
        {
            int[] a = {1, 2, 3, 4, 5};
            int[] b = {6, 7, 8, 9, 10};
              
            System.arraycopy(a, 0, b, 2, 2);
              
            // array b after arraycopy operation
            System.out.println(Arrays.toString(b));
              
        }
    }

    chevron_right

    
    

    Output:

    [6, 7, 1, 2, 10]
    
  2. static String clearProperty(String key): Removes the system property indicated by the specified key.

    Syntax: public static String clearProperty(String key)
    Returns: the previous string value 
    of the system property, or null if there was no property 
    with that key.
    Exception: 
    SecurityException - if a security manager exists and its 
    checkPropertyAccess method doesn't allow 
    access to the specified system property.
    NullPointerException - if key is null.
    IllegalArgumentException - if key is empty.
    
  3. static String getProperty(String key): Gets the system property indicated by the specified key.

    Syntax: public static String getProperty(String key)
    Returns: the string value of the system 
    property, or null if there is no property with that key.
    Exception: 
    SecurityException - if a security manager exists and its 
    checkPropertyAccess method doesn't allow access to the 
    specified system property.
    NullPointerException - if key is null.
    IllegalArgumentException - if key is empty.
    
  4. static String getProperty(String key, String def): Gets the system property indicated by the specified key.

    Syntax: public static String getProperty(String key, String def)
    Returns: the string value of the system property,
     or the default value if there is no property with that key.
    Exception: 
    SecurityException - if a security manager exists and its 
    checkPropertyAccess method doesn't allow access to the 
    specified system property.
    NullPointerException - if key is null.
    IllegalArgumentException - if key is empty.
    
  5. static String setProperty(String key, String value): Sets the system property indicated by the specified key.

    Syntax: public static String setProperty(String key, String value)
    Returns: the previous value of the system 
    property, or null if it did not have one.
    Exception: 
    SecurityException - if a security manager exists and its checkPermission 
    method doesn't allow setting of the specified property.
    NullPointerException - if key or value is null.
    IllegalArgumentException - if key is empty.
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating clearProperty(), getProperty()
    // and setProperty() methods
    import java.lang.*;
    import static java.lang.System.clearProperty;
    import static java.lang.System.setProperty;
    import java.util.Arrays;
    class SystemDemo
    {
        public static void main(String args[])
        {
            // checking specific property
            System.out.println(System.getProperty("user.home"));
              
            // claering this property
            clearProperty("user.home");
              
            System.out.println(System.getProperty("user.home"));
              
            // setting specific property
            setProperty("user.country", "US");
              
            // checking property
            System.out.println(System.getProperty("user.country"));
              
            // checking property other than system property
            // illustrating getProperty(String key, String def)
            System.out.println(System.getProperty("user.password",
                  "none of your business"));
        }
    }

    chevron_right

    
    

    Output:

    /Users/abhishekverma
    null
    US
    none of your business
    
  6. static Console console(): Returns the unique Console object associated with the current Java virtual machine, if any.

    Syntax: public static Console console()
    Returns: The system console, if any, otherwise null.
    Exception: NA
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating console() method
    import java.io.Console;
    import java.lang.*;
    import java.util.Currency;
    import java.util.Locale;
    class SystemDemo
    {
        public static void main(String args[]) throws NullPointerException
        {
              
            Console c = System.console();
            if(c != null)
            {
               Currency currency = Currency.getInstance(Locale.ITALY);
               c.printf(currency.getSymbol());
                c.flush();
            }
            else
                System.out.println("No console attached");
        }
    }

    chevron_right

    
    

    Output:

    No console attached
    
  7. static long currentTimeMillis(): Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

    Syntax: public static long currentTimeMillis()
    Returns: the difference, measured in milliseconds,
     between the current time and midnight, January 1, 1970 UTC.
    Exception: NA.
    
  8. static long nanoTime(): Returns the current value of the running Java Virtual Machine’s high-resolution time source, in nanoseconds.

    Syntax: public static long nanoTime()
    Returns: the current value of the running Java
     Virtual Machine's high-resolution time source, in nanoseconds
    Exception: NA
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating currentTimeMillis() method
    import java.lang.*;
    class SystemDemo
    {
        public static void main(String args[]) throws NullPointerException
        {
            System.out.println("difference between the "
                    + "current time and midnight,"
                    + " January 1, 1970 UTC is: "
                    System.currentTimeMillis());
            System.out.println("cuurent time in "
                    + "nano sec: "
                    System.nanoTime());
        }
    }

    chevron_right

    
    

    Output:

    difference between the current time 
    and midnight, January 1, 1970 UTC is: 
    1499520649545
    cuurent time in nano sec: 29976939759226
    
  9. static void exit(int status): Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
    This method calls the exit method in class Runtime. This method never returns normally.
    The call System.exit(n) is effectively equivalent to the call:
    Runtime.getRuntime().exit(n)

    Syntax: public static void exit(int status)
    Returns: NA
    Exception: 
    SecurityException - if a security manager exists and its 
    checkExit method doesn't allow exit with the specified status.
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating exit() method 
    import java.lang.*;
    class SystemDemo
    {
        public static void main(String args[]) throws NullPointerException
        {
            System.gc();
            System.out.println("Garbage collector executed ");
              
            System.out.println(System.getProperty("os.name"));
              
            System.exit(1);
              
            // this line will not execute as JVM terminated
            System.out.println("JVM terminated");
        }
    }

    chevron_right

    
    

    Output:

    Garbage collector executed 
    Mac OS X
    
  10. static void gc(): Runs the garbage collector. Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

    Syntax: public static void gc()
    Returns: NA
    Exception: NA
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating gc() method
    import java.lang.*;
    class SystemDemo
    {
        public static void main(String args[]) 
        {
            Runtime gfg = Runtime.getRuntime();
            long memory1, memory2;
            Integer integer[] = new Integer[1000];
       
            // checking the total memeory
            System.out.println("Total memory is: "
                               + gfg.totalMemory());
       
            // checking free memory
            memory1 = gfg.freeMemory();
            System.out.println("Initial free memory: "
                                          + memory1);
       
            // calling the garbage collector on demand
            System.gc();
       
            memory1 = gfg.freeMemory();
       
            System.out.println("Free memory after garbage "
                               + "collection: " + memory1);
       
            // allocating integers
            for (int i = 0; i < 1000; i++)
                integer[i] = new Integer(i);
       
            memory2 = gfg.freeMemory();
            System.out.println("Free memory after allocation: "
                               + memory2);
       
            System.out.println("Memeory used by allocation: " +
                                        (memory1 - memory2));
       
            // discard integers
            for (int i = 0; i < 1000; i++)
                integer[i] = null;
       
            System.gc();
       
            memory2 = gfg.freeMemory();
            System.out.println("Free memeory after  "
                + "collecting discarded Integers: " + memory2);
        }
    }

    chevron_right

    
    

    Output:

    Total memory is: 128974848
    Initial free memory: 126929976
    Free memory after garbage collection: 128632160
    Free memory after allocation: 127950520
    Memeory used by allocation: 681640
    Free memeory after  collecting discarded Integers: 128643472
    
  11. static Map getenv(): Returns an unmodifiable string map view of the current system environment. The environment is a system-dependent mapping from names to values which is passed from parent to child processes.
    If the system does not support environment variables, an empty map is returned.

    Syntax: public static Map getenv()
    Returns: the environment as a map of variable names to values.
    Exception: 
    SecurityException - if a security manager exists and its 
    checkPermission method doesn't allow access to the process 
    environment
    
  12. static String getenv(String name): Gets the value of the specified environment variable. An environment variable is a system-dependent external named value.
    System properties and environment variables are both conceptually mappings between names and values. Both mechanisms can be used to pass user-defined information to a Java process. Environment variables have a more global effect, because they are visible to all descendants of the process which defines them, not just the immediate Java subprocess. They can have subtly different semantics, such as case insensitivity, on different operating systems. For these reasons, environment variables are more likely to have unintended side effects. It is best to use system properties where possible. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as PATH).

    Syntax: public static String getenv(String name)
    Returns: the string value of the variable,
     or null if the variable is not defined in the system environment.
    Exception: 
    NullPointerException - if name is null
    SecurityException - if a security manager exists and 
    its checkPermission method doesn't allow access to the
     environment variable name.
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating getenv() method
    import java.lang.*;
    import java.util.Map;
    import java.util.Set;
    class SystemDemo
    {
        public static void main(String args[]) 
        {
            Map<String, String> gfg = System.getenv();
            Set<String> keySet = gfg.keySet();
            for(String key : keySet)
            {
                System.out.println("key= " + key);
            }
              
            // checking specific environment variable
            System.out.println(System.getenv("PATH"));
        }
    }

    chevron_right

    
    

    Output:

    key= JAVA_MAIN_CLASS_5396
    key= PATH
    key= J2D_PIXMAPS
    key= SHELL
    key= USER
    key= TMPDIR
    key= SSH_AUTH_SOCK
    key= XPC_FLAGS
    key= LD_LIBRARY_PATH
    key= __CF_USER_TEXT_ENCODING
    key= Apple_PubSub_Socket_Render
    key= LOGNAME
    key= LC_CTYPE
    key= XPC_SERVICE_NAME
    key= PWD
    key= JAVA_MAIN_CLASS_2336
    key= SHLVL
    key= HOME
    key= _
    /usr/bin:/bin:/usr/sbin:/sbin
    
  13. static Properties getProperties(): Determines the current system properties.

    Syntax: public static Properties getProperties()
    Returns: the system properties.
    Exception: 
    SecurityException - if a security manager exists and 
    its checkPropertiesAccess method doesn't allow access 
    to the system properties.
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating getProperties() method
    import java.lang.*;
    import java.util.Properties;
    import java.util.Set;
    class SystemDemo
    {
        public static void main(String args[]) 
        {
            Properties gfg = System.getProperties();
            Set<Object> keySet = gfg.keySet();
            for(Object key : keySet)
            {
                System.out.println("key= " + key);
            }
        }
    }

    chevron_right

    
    

    Output:

    key= java.runtime.name
    key= sun.boot.library.path
    key= java.vm.version
    key= user.country.format
    key= gopherProxySet
    key= java.vm.vendor
    key= java.vendor.url
    key= path.separator
    key= java.vm.name
    key= file.encoding.pkg
    key= user.country
    key= sun.java.launcher
    key= sun.os.patch.level
    key= java.vm.specification.name
    key= user.dir
    key= java.runtime.version
    key= java.awt.graphicsenv
    key= java.endorsed.dirs
    key= os.arch
    key= java.io.tmpdir
    key= line.separator
    key= java.vm.specification.vendor
    key= os.name
    key= sun.jnu.encoding
    key= java.library.path
    key= java.specification.name
    key= java.class.version
    key= sun.management.compiler
    key= os.version
    key= http.nonProxyHosts
    key= user.home
    key= user.timezone
    key= java.awt.printerjob
    key= file.encoding
    key= java.specification.version
    key= java.class.path
    key= user.name
    key= java.vm.specification.version
    key= sun.java.command
    key= java.home
    key= sun.arch.data.model
    key= user.language
    key= java.specification.vendor
    key= awt.toolkit
    key= java.vm.info
    key= java.version
    key= java.ext.dirs
    key= sun.boot.class.path
    key= java.vendor
    key= file.separator
    key= java.vendor.url.bug
    key= sun.io.unicode.encoding
    key= sun.cpu.endian
    key= socksNonProxyHosts
    key= ftp.nonProxyHosts
    key= sun.cpu.isalist
    
  14. static SecurityManager getSecurityManager(): Gets the system security interface.

    Syntax: static SecurityManager getSecurityManager()
    Returns: if a security manager has 
    already been established for the current application,
     then that security manager is returned; otherwise, 
    null is returned.
    Exception: NA
    
  15. static void setSecurityManager(SecurityManager s): Sets the System security.

    Syntax: public static void setSecurityManager(SecurityManager s)
    Returns: NA.
    Exception: 
    SecurityException - if the security manager has 
    already been set and its checkPermission method 
    doesn't allow it to be replaced.
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating setSecurityManager() 
    // and getSecurityManager() method
    import java.lang.*;
    class SystemDemo
    {
        public static void main(String args[]) 
        {
            SecurityManager gfg = new SecurityManager();
              
            // setting the security manager
            System.setSecurityManager(gfg);
              
            gfg = System.getSecurityManager();
            if(gfg != null)
                System.out.println("Security manager is configured");
        }
    }

    chevron_right

    
    

    Output:

    Security manager is configured
    
  16. static void setErr(PrintStream err): Reassigns the “standard” error output stream.

    Syntax: public static void setErr(PrintStream err)
    Returns: NA
    Exception: 
    SecurityException - if a security manager exists and its
     checkPermission method doesn't allow reassigning of the
     standard error output stream.
    
  17. static void setIn(InputStream in): Reassigns the “standard” input stream.

    Syntax: public static void setIn(InputStream in)
    Returns: NA.
    Exception: 
    SecurityException - if a security manager exists and its
     checkPermission method doesn't allow reassigning of the
     standard input stream.
    
  18. static void setOut(PrintStream out): Reassigns the “standard” output stream.

    Syntax: public void setOut(PrintStream out)
    Returns: NA
    Exception: 
    SecurityException - if a security manager exists and its
     checkPermission method doesn't allow reassigning of the
     standard output stream.
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating setOut(), setIn() and setErr() method
    import java.lang.*;
    import java.util.Properties;
    import java.io.*;
    class SystemDemo
    {
        public static void main(String args[])  throws IOException  
        {
            FileInputStream IN = new FileInputStream("input.txt");
            FileOutputStream OUT = new FileOutputStream("system.txt");
              
            // set input stream
            System.setIn(IN);
            char c = (char) System.in.read();
            System.out.print(c);
              
            // set output stream
            System.setOut(new PrintStream(OUT));
            System.out.write("Hi Abhishek\n".getBytes());
              
            // set error stream
            System.setErr(new PrintStream(OUT));
            System.err.write("Exception message\n".getBytes());
        }
    }

    chevron_right

    
    

    Output: Output of above java code depends on content in “input.txt” file.
    Create your own “input.txt” then run the code and check the output.

  19. static void load(String filename): Loads a code file with the specified filename from the local file system as a dynamic library. The filename argument must be a complete path name.

    Syntax: public static void load(String filename)
    Returns: NA
    Exception: 
    SecurityException - if a security manager exists and
     its checkLink method doesn't allow loading of the specified
     dynamic library
    UnsatisfiedLinkError - if the file does not exist.
    NullPointerException - if filename is null
    
  20. static void loadLibrary(String libname): Loads the system library specified by the libname argument. The manner in which a library name is mapped to the actual system library is system dependent.

    Syntax: public static void loadLibrary(String libname)
    Returns: NA
    Exception: 
    SecurityException - if a security manager exists and its 
    checkLink method doesn't allow loading of the specified dynamic
     library
    UnsatisfiedLinkError - if the library does not exist.
    NullPointerException - if libname is null
    
  21. static String mapLibraryName(String libname): Maps a library name into a platform-specific string representing a native library.

    Syntax: public static String mapLibraryName(String libname)
    Returns: a platform-dependent native library name.
    Exception: NullPointerException - if libname is null
    
  22. static void runFinalization(): Runs the finalization methods of any objects pending finalization. Calling this method suggests that the Java Virtual Machine expend effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run. When control returns from the method call, the Java Virtual Machine has made a best effort to complete all outstanding finalizations.

    Syntax: public static void runFinalization()
    Returns: NA
    Exception: NA.
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating runFinalization(), load()
    // loadLibrary() and mapLibraryName() method
    import java.lang.*;
    class SystemDemo
    {
        public static void main(String args[]) throws NullPointerException
        {
       
            // map library name
            String libName = System.mapLibraryName("os.name");
            System.out.println("os.name library= " + libName);
       
            //load external libraries
            System.load("lixXYZ.so");
            System.loadLibrary("libos.name.dylib");
       
            //run finalization
            System.runFinalization();
       
      
        }
    }

    chevron_right

    
    

    Output:

    os.name library= libos.name.dylib
    
  23. static int identityHashCode(Object x): Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object’s class overrides hashCode(). The hash code for the null reference is zero.

    Syntax: public static int identityHashCode(Object x)
    Returns: the hashCode.
    Exception: NA.
    
  24. static Channel inheritedChannel(): Returns the channel inherited from the entity that created this Java virtual machine.

    Syntax: public static Channel inheritedChannel().
    Returns:  inherited channel, if any, otherwise null.
    Exception: 
    IOException - If an I/O error occurs
    SecurityException - If a security manager is present and
     it does not permit access to the channel.
    
  25. static String lineSeparator(): Returns the system-dependent line separator string. It always returns the same value – the initial value of the system property line.separator.

    Syntax: public static String lineSeparator()
    Returns: On UNIX systems, it returns "\n";
     on Microsoft Windows systems it returns "\r\n".
    Exception: NA
    
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java code illustrating lineSeparator(), inherentChannel()
    // and identityHashCode() method
    import java.io.IOException;
    import java.lang.*;
    import java.nio.channels.Channel;
    class SystemDemo
    {
        public static void main(String args[]) 
                throws NullPointerException,
                IOException
        {
       
            Integer x = 400;
            System.out.println(System.identityHashCode(x));
              
            Channel ch = System.inheritedChannel();
            System.out.println(ch);
              
            System.out.println(System.lineSeparator());
              
        }
    }

    chevron_right

    
    

    Output:

    1735600054
    null
    "\r\n"
    

This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.