digitization, transformation, binary

Class System in Java

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 Name Meaning
file.encoding The character encoding for the default locale
file.encoding.pkg The package that contains converters between local encodings and Unicode
file.separator File separator (‘/’ on UNIX, ‘ \’ on Windows)
java.class.path The classpath
java.class.version Java class version number
java.compiler The just-in-time compiler to use, if any
java.home Java installation directory
java.vendor Java vendor-specific string
java.vendor.url Java vendor URL
java.version Java version number
line.separator Line separator(‘ \n’ on UNIX, ‘ \r\n’ on Windows)
os.arch Operating system architecture
os.name Operating system name
os.version Operating system version
path.separator Path separator (‘:’ on UNIX, ‘,’ on Windows)
user.dir User’s current working directory when the properties were initialized
user.home User’s home directory
user.language The two-letter language code of the default locale
user.name User’s account name
user.region The two-letter country code of the default locale
user.timezone The 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.

READ  Class LineNumberInputStream in Java

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.

READ  Class ServerSocket in Java

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..

READ  File Concept Simplified In Java

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);
}
}

How To Get System Properties In Java?

For each system, system properties information (persistent ) will be maintained in the form of system properties. Mainly we use properties to maintain system configuration. The system class will maintain a Properties object to get all the details.

In short, it is nothing but a key-value pair in the form of string.
The important aspect of System property is “to access any value from it, it requires current security manager’s approval”

More details can be found here:

Lets see an example:

import java.util.Properties;
public class systemTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Properties p=System.getProperties();
p.list(System.out);
}
}

output:
java.vm.specification.vendor=XYZ Corporation
user.variant=
os.name=Windows XP
sun.jnu.encoding=Cp1252
java.library.path=C:Program FilesJavajdk1.7.0_21bin…
java.specification.name=Java Platform API Specification
java.class.version=51.0
sun.management.compiler=HotSpot Client Compiler
os.version=5.1
user.home=C:Documents and Settingsanichatt.AP…
user.timezone=
java.awt.printerjob=sun.awt.windows.WPrinterJob
file.encoding=Cp1252
java.specification.version=1.7
user.name=anichatt
java.class.path=E:myProgram
java.vm.specification.version=1.7
sun.arch.data.model=32
java.home=C:Program FilesJavajdk1.7.0_21jre
sun.java.command=systemTest
java.specification.vendor=xyz Corporation
user.language=en
awt.toolkit=sun.awt.windows.WToolkit
java.vm.info=mixed mode, sharing
java.version=1.7.0_21
java.ext.dirs=C:Program FilesJavajdk1.7.0_21jre…
sun.boot.class.path=C:Program FilesJavajdk1.7.0_21jre…
java.vendor=xyz Corporation
file.separator=
java.vendor.url.bug=http://bugreport.sun.com/bugreport/
sun.cpu.endian=little
sun.io.unicode.encoding=UnicodeLittle
sun.desktop=windows
sun.cpu.isalist=pentium_pro+mmx pentium_pro pentium+m…

Below are the system properties that can be tracked using the system class’s Property Object. Important system properties

Key Meaning
“file.separator” Character that separates components of a file path. This is “/" on UNIX and "" on Windows.
“java.class.path” Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.
“java.home” Installation directory for Java Runtime Environment (JRE)
“java.vendor” JRE vendor name
“java.vendor.url” JRE vendor URL
“java.version” JRE version number
“line.separator” Sequence used by operating system to separate lines in text files
“os.arch” Operating system architecture
“os.name” Operating system name
“os.version” Operating system version
“path.separator” Path separator character used in java.class.path
“user.dir” User working directory
“user.home” User home directory
“user.name” User account name

taken from docs.oracle.com.
How to get single property from the list?? say I want to retrieve OS name and current location of the class file. so the corresponding code:

import java.util.Properties;
public class systemTest {
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Properties p=System.getProperties();
  //p.list(System.out);
  System.out.println(p.getProperty("java.class.path"));
  System.out.println(p.getProperty("os.name"));
  }
}

output:
. (dot -it means current working directory)
Windows XP

How To Check System Configuration Before Proceeding With Our Code In Java?

let’s say I have developed a program in Java-1.6 and used some code which got enhanced in that particular version.
like-

  • Native platform Security (GSS/Kerberos) integration.
  • Java Authentication and Authorization Service (JAAS) login
  • the module that employs LDAP authentication
  • New Smart Card I/O API
  • Native security services technical article

Let’s assume that this program will run on java -1.5. Definitely the compatibility will not be there.

As per stack over flow

The compiler is not backwards compatible because bytecode generated with Java6 JDK won’t run in Java 1.5 jvm (unless compiled with the -target 1.5 flag). But the JVM is backwards compatible, as it can run older bytecodes.

So I guess they chose to consider the compatibility from the point of view of javac (as it is the part specific to the JDK), meaning that the bytecode generated can be run in future releases of the jvm (that is more related to the JRE, but also bundled in the JDK).

In brief, we can say:

JDK’s are (usually) forward compatible.
JRE’s are (usually) backward compatible.

Let us also assume , my program needs the below written…

  • Java version-java 1.7
  • OS-Windows XP
  •  and I have some requirement where the .class file should be in C drive.

if all of the above are matching then our program is good to go else we will simply say with the configuration, this program will not run…

Let’s see how: I have shown how to get system properties previously. From the list of properties, we are only going to choose

  • java version
  • OS
  • class. path

 

import java.util.Properties;
public class systemTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean b=false;
Properties p=System.getProperties();
p.list(System.out);
//get all the list of properties.
String path=p.getProperty("java.class.path");
String os=p.getProperty("os.name");
String javaVersion=p.getProperty("java.specification.version");
System.out.println(path);
System.out.println(os);
System.out.println(javaVersion);
if((path.indexOf("C:\")>=0||path.equals(".")) && os.equals("Windows XP") && javaVersion.equals("1.7"))
b=true;
//checks the path contains C drive,also checks for OS or java version
if(b)
System.out.print("We can proceed");
else
System.out.print("We can not proceed");
}
}

output:
. (dot means present working directory.)
Windows XP
1.7
We can proceed

Now if the java version is 1.4 (running)in the client machine. It should say “We can not proceed”. By this way, we can achieve the precondition cases for running our tests.

Share and Enjoy !

Leave a Comment

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