System class (I)
27 December 2007The System class is a very useful which contains static fields and methods. It cannot be instantiated. In this post, I will briefly write about System class and will explore few interesting methods.
System class belongs to java.lang package, so it can be used in any Java class without importing any package. System class provides static methods that are very useful. For example to get current time in milliseconds:
static long currentTimeMillis()
This static method is very useful when you want to calculate the time taken by a piece of code. Review the code below:
long start = System.currentTimeMillis(); for(int i=0;i<100;i++) { calculateSalaries(); } long end = System.currentTimeMillis(); System.out.println("calculateSalaries executed 100 times and took " + (end - start) + " milli seconds.");
We called method 100 times and want to calculate the time it takes. We store the time in milliseconds before the execution and after the execution. Difference between the two long values gave us the execution time.
Garbage collection is called automatically but you can also call it using gc() method of System class.
System.gc();
System class has exit() method which is used to terminate the JVM.
System.exit(0);
You can load libraries (dll) and call legacy code in Java using loadLibrary(..) method.
static void loadLibrary(String libname)
System class has a method to copy array.
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Example:
String array1[] = new String[5]; array1[0] = "abc"; array1[1] = "def"; array1[2] = "ghi"; array1[3] = "jkl"; array1[4] = "mno"; String array2[] = new String[3]; System.arraycopy(array1, 2, array2, 0, 3);
Happy coding.
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: System class (I)