The System
class in Java is a final class in java.lang
package that provides useful system-related utilities.
It cannot be instantiated (constructor is private), and all of its members are static.
🔑 Features of System
Class
Here are the main things you can do with it:
1. Standard Input, Output, Error Streams
System.out
→ Standard output (usually console).System.err
→ Standard error output.System.in
→ Standard input (keyboard by default).
Example:
public class SystemExample1 {
public static void main(String[] args) {
System.out.println("Hello from System.out");
System.err.println("This is an error message");
}
}
What is a Stream in Programming?
A stream is a sequence of data elements that can be read (input stream) or written (output stream) over time.
Think of it like a flow of water in a pipe: data flows from a source to a destination
2. Exit JVM
System.exit(statusCode)
→ Terminates the program.0
→ Normal termination.- Non-zero → Abnormal termination.
Example:
public class SystemExample2 {
public static void main(String[] args) {
System.out.println("Before exit");
System.exit(0);
System.out.println("This will not be printed");
}
}
3. Current Time
System.currentTimeMillis()
→ Milliseconds since Jan 1, 1970 UTC.System.nanoTime()
→ High-resolution time (nanoseconds).
Example:
public class SystemExample3 {
public static void main(String[] args) {
long start = System.currentTimeMillis();
// Some task
for (int i = 0; i < 1_000_000; i++) {}
long end = System.currentTimeMillis();
System.out.println("Time taken: " + (end - start) + " ms");
}
}
4. Array Copy
System.arraycopy(src, srcPos, dest, destPos, length)
→ Efficient array copying.
Example:
public class SystemExample4 {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
int[] b = new int[5];
System.arraycopy(a, 0, b, 0, a.length);
for (int n : b) {
System.out.print(n + " ");
}
}
}
✅ Output:
1 2 3 4 5
5. Garbage Collection
System.gc()
→ Suggests JVM to run Garbage Collector. (Not guaranteed).
Example:
public class SystemExample5 {
public static void main(String[] args) {
System.gc(); // Requests GC
System.out.println("Garbage Collection requested");
}
}
6. System Properties & Environment Variables
System.getProperty(String key)
→ Gets JVM/system property.System.getenv(String name)
→ Gets environment variable.
Example:
public class SystemExample6 {
public static void main(String[] args) {
System.out.println("Java Version: " + System.getProperty("java.version"));
System.out.println("User Directory: " + System.getProperty("user.dir"));
System.out.println("PATH: " + System.getenv("PATH"));
}
}
🔎 Summary
System.out
,System.err
,System.in
→ I/OSystem.exit(int)
→ Terminate programSystem.currentTimeMillis()
,System.nanoTime()
→ Time measurementSystem.arraycopy()
→ Fast array copySystem.gc()
→ Suggest garbage collectionSystem.getProperty()
,System.getenv()
→ Properties & environment