System Class in Java – Properties, System.out.println()

Filed Under: Java

System class in java is one of the core classes and I have never seen any java developer who doesn’t use it. One of the easiest way to log information for debugging is System.out.print() function. System class is final and all of it’s members and methods are static so that we can’t subclass and override it’s behavior through inheritance.

System Class in Java

System class in java doesn’t provide any public constructors. So we can’t instantiate this class (for argument sake, we can instantiate it using Java Reflection) and that’s why all of it’s methods are static.

Here we will look into the different features provided by java.lang.System class.

  1. Java System Array Copy
  2. Java System Properties
  3. Reading and Writing to Console
  4. Java System Get Current Time
  5. Java System Environment Variables
  6. Security Manager
  7. File IO Operations
  8. Miscellaneous Tasks

  1. Java System Array Copy

    Java System class provides a native method for copying data from one array to another. This is a native implementation and supposed to be faster than other ways to copy array data.

    System array copy method throws IndexOutOfBoundsException if copying would cause access of data outside array bounds. It also throws ArrayStoreException if an element in the source array could not be stored into the destination array because of a type mismatch and NullPointerException if either source or destination array is null.

    Below example program shows how to use this method.

    
    int [] array1 = {1,2,3,4,5};
    int[] array2 = {10,20,30,40,50};
    		
    //copying first two elements from array1 to array2 starting from index 2 of array2
    System.arraycopy(array1, 0, array2, 2, 2);
    		
    System.out.println(Arrays.toString(array2)); //prints "[10, 20, 1, 2, 50]"
    

    System class in java, java system array copy

  2. Java System Properties

    System class contains useful method to get the list of System properties, get specific property, set system property and clear any existing property. The sample program below shows different methods and it’s usage.

    
    //Get System Defined Properties
    Properties systemProps = System.getProperties();
    Set<Object> keySet = systemProps.keySet();
    for(Object obj : keySet){
    	String key = (String) obj;
    	System.out.println("{"+obj+"="+systemProps.getProperty(key)+"}");
    }
    
    //Get Specific Property
    System.out.println(System.getProperty("user.country"));
    
    //Clear property example
    System.clearProperty("user.country");
    System.out.println(System.getProperty("user.country")); //print null
    
    //Set System property
    System.setProperty("user.country", "IN");
    System.out.println(System.getProperty("user.country")); //prints "IN"
    

    If we run above code in a java program, we get following output. Notice that output will vary based on your system configurations.

    
    {java.runtime.name=Java(TM) SE Runtime Environment}
    {sun.boot.library.path=/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib}
    {java.vm.version=23.5-b02}
    {gopherProxySet=false}
    {java.vm.vendor=Oracle Corporation}
    {java.vendor.url=http://java.oracle.com/}
    {path.separator=:}
    {java.vm.name=Java HotSpot(TM) 64-Bit Server VM}
    {file.encoding.pkg=sun.io}
    {user.country=US}
    {sun.java.launcher=SUN_STANDARD}
    {sun.os.patch.level=unknown}
    {java.vm.specification.name=Java Virtual Machine Specification}
    {user.dir=/Users/pankaj/CODE/MyProject}
    {java.runtime.version=1.7.0_09-b05}
    {java.awt.graphicsenv=sun.awt.CGraphicsEnvironment}
    {java.endorsed.dirs=/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/endorsed}
    {os.arch=x86_64}
    {java.io.tmpdir=/var/folders/f1/25ry1vy5675_30mkwqp7p46r0000gn/T/}
    {line.separator=
    }
    {java.vm.specification.vendor=Oracle Corporation}
    {os.name=Mac OS X}
    {sun.jnu.encoding=US-ASCII}
    {java.library.path=/Users/pankaj/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.}
    {java.specification.name=Java Platform API Specification}
    {java.class.version=51.0}
    {sun.management.compiler=HotSpot 64-Bit Tiered Compilers}
    {os.version=10.8.3}
    {http.nonProxyHosts=local|*.local|169.254/16|*.169.254/16}
    {user.home=/Users/pankaj}
    {user.timezone=}
    {java.awt.printerjob=sun.lwawt.macosx.CPrinterJob}
    {file.encoding=MacRoman}
    {java.specification.version=1.7}
    {java.class.path=/Users/pankaj/CODE/bin:/Users/pankaj/}
    {user.name=pankaj}
    {java.vm.specification.version=1.7}
    {sun.java.command=com.journaldev.util.SystemClassExamples}
    {java.home=/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre}
    {sun.arch.data.model=64}
    {user.language=en}
    {java.specification.vendor=Oracle Corporation}
    {awt.toolkit=sun.lwawt.macosx.LWCToolkit}
    {java.vm.info=mixed mode}
    {java.version=1.7.0_09}
    {java.ext.dirs=/Users/pankaj/Library/Java/Extensions:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/ext:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java}
    {sun.boot.class.path=/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/sunrsasign.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/JObjC.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/classes}
    {java.vendor=Oracle Corporation}
    {file.separator=/}
    {java.vendor.url.bug=http://bugreport.sun.com/bugreport/}
    {sun.io.unicode.encoding=UnicodeBig}
    {sun.cpu.endian=little}
    {socksNonProxyHosts=local|*.local|169.254/16|*.169.254/16}
    {ftp.nonProxyHosts=local|*.local|169.254/16|*.169.254/16}
    {sun.cpu.isalist=}
    US
    null
    IN
    

    java system properties

    Check out Java Properties example tutorial.

  3. Reading and Writing to Console

    Java System Class provide a method to get the unique Console object associated with the running JVM.

    Console class was introduced in Java IO in 1.6 and provides useful method to print formatted data and read password securely.

    If no console is associated with the current JVM, for example running through Eclipse or running as background program, then it returns null.

    Below sample program show get Console object from System class and use it.

    
    Console console = System.console();
    
    if(console != null){
        Calendar c = new GregorianCalendar();
        console.printf("Welcome %1$s%n", "Pankaj"); //prints "Welcome Pankaj"
        console.printf("Current time is: %1$tm %1$te,%1$tY%n", c); //prints "Current time is: 08 5,2013"
        console.flush();
    } else{
    	//No console is attached when run through Eclipse, background process
    	System.out.println("No Console attached");
    }
    

    java system console printf eclipse

    java system console

  4. java System Get Current Time

    System class in java provide two methods to get the current time in milliseconds and nano time.

    We can use time in milliseconds to create Date object, nano time is used mostly in scientific experiments or in benchmark testing.

    Below code snippet show the usage of System class methods to get time related information.

    
    long currentTimeMillis = System.currentTimeMillis();
    Date date = new Date(currentTimeMillis);
    System.out.println("Current time in millis="+currentTimeMillis);
    System.out.println(date); //prints 2013-08-05
    
    long nanoTime = System.nanoTime();
    System.out.println("Current nano time="+nanoTime);
    

    java system class get current time

  5. Java System Environment Variables

    Java System class provides a method to get the environment variables data in Map form, the returned Map is unmodifiable and it contains key-value pairs in String object.

    
    //get unmodifiable environment variables map
    Map<String, String> envMap = System.getenv();
    Set<String> keySet = envMap.keySet();
    for(String key : keySet){
    	System.out.println("Key="+key+",value="+envMap.get(key));
    }
    
    //Get Specific environment variable
    String pathValue = System.getenv("PATH");
    System.out.println("$PATH="+pathValue);
    

    java system environment variables, system in java

  6. Security Manager

    SecurityManager class is used to implement security policy for applications, System class provide useful methods to get SecurityManager for the currently running JVM and to set the SecurityManager for the application.

    
    SecurityManager secManager = System.getSecurityManager();
    if(secManager == null){
    	System.out.println("SecurityManager is not configured");
    }
    SecurityManager mySecManager = new SecurityManager();
    System.setSecurityManager(mySecManager);
    secManager = System.getSecurityManager();
    if(secManager != null){
    	System.out.println("SecurityManager is configured");
    }
    

    java system security manager

  7. File IO Operations

    System class contains three fields – in, out and err. They are used to read data from InputStream and to write data to OutputStream.

    System class provide methods to set different types of InputStream and OutputStream to be used for logging purposes.

    For example, we can set FileOutputStream to out and err fields so that console output is written to file.

    Below code snippet shows the usage of these fields and how can we set them using setter methods.

    
    try(FileInputStream fis = new FileInputStream("input.txt");
    	FileOutputStream fos = new FileOutputStream("server.log");) {
    
    //set input stream
    System.setIn(fis);
    char c = (char) System.in.read();
    System.out.print(c); //prints the first character from input stream
    
    //set output stream
    System.setOut(new PrintStream(fos));
    System.out.write("Hi Pankaj\n".getBytes());
    
    //set error stream
    System.setErr(new PrintStream(fos));
    System.err.write("Exception message\n".getBytes());
    } catch (IOException e) {
    	e.printStackTrace();
    }
    

    Notice the use of Java 7 try with resources feature in above try-block.

  8. Miscellaneous Tasks

    System class provides some other methods for miscellaneous tasks. For example, to run Garbage Collector, load external libraries, map the library name to OS specific String, run the finalize method for any object waiting for finalization and to terminate the JVM.

    
    //run the garbage collector
    System.gc();
    System.out.println("Garbage collector executed.");
    
    //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();
    
    //terminates the currently running JVM
    System.exit(1);
    // this line will never print because JVM is terminated
    System.out.println("JVM is terminated"); 
    

That’s all about System class in java, I hope it will help you in getting most out of java System class.

Reference: API Doc

Comments

  1. Abdus Salam says:

    Thanks for publishing important topic about just System Class.

  2. Deepak says:

    Good article to understand the System class.

    I think their is a Typo (in 3rd line).. System class is final but not static.

  3. Sumit Kumar says:

    Hi Pankaj,

    Thanks for the explanation..
    I have a doubt.. why dont we ever import System and Wrapper classes???

    1. Pankaj says:

      Because java.lang package is implicitly imported and we don’t need to import them in our code, something like every java class parent is java.lang.Object but we don’t need to extend it in our code.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages