Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

jvm
java
communitycreator

How to get the total memory in JVM using Java

abhilash

What is the Runtime class in Java?

The Runtime class has methods that interface and interact with the application’s runtime environment.

The totalMemory() method

The totalMemory() method of the Runtime class is used to retrieve the total memory available in the Java Virtual Machine (JVM). The value returned by this method is in bytes.

Syntax

public native long totalMemory()

Return value

This method returns the total memory available to the JVM.

Example

public class Main {

    public static void main(String[] args){
        Runtime currentRuntime = Runtime.getRuntime();
        System.out.println("Runtime.totalMemory() = " + currentRuntime.totalMemory() + " bytes");
    }
}

Explanation

  • Line 4: We retrieve the current runtime of the application using the getRuntime() method of the Runtime class.
  • Line 5: We obtain the total memory JVM will have by calling the totalMemory() method on the currentRuntime retrieved in line 4.

RELATED TAGS

jvm
java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring