Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Find Length or Size of an Array in Java?
Next article icon

How to Calculate Size of Object in Java?

Last Updated : 21 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, an object is an instance of a class that encapsulates data and behavior. Calculating the size of an object can be essential for memory management and optimization. This process involves understanding the memory layout of the object, including its fields and the overhead introduced by the JVM.

In this article, we will learn to calculate size of object in Java.

Declaration:

public static long getObjectSize(Object object);

Return Value: Size of the specified object in bytes as a long.

Program to Calculate Size of Object in Java

Below is the implementation to Calculate Size of Object in Java:

Java
// Java program to calculate the size of an object // Importing required classes  import java.lang.instrument.Instrumentation;  // Main Class public class SizeCalculate {     // Volatile variable to hold the global Instrumentation instance     private static volatile Instrumentation globalInstrumentation;      // premain method to initialize the Instrumentation instance     public static void premain(String agentArgs, Instrumentation inst)      {         globalInstrumentation = inst;     }      // Method to get the size of an object     public static long getObjectSize(Object object) {         if (globalInstrumentation == null) {             throw new IllegalStateException("Agent not initialized.");         }         return globalInstrumentation.getObjectSize(object);     }      // Main driver method     public static void main(String[] args) {         String example = "GeeksforGeeks";         System.out.println("Size of the object: " + getObjectSize(example) + " bytes");     } } 

Executing the Program:

Step 1: First compile the Java code using the below command in the IDE terminal:

javac SizeCalculate.java

Step 2: Once the code is compiled, we can run the application by executing the below command in the terminal.

java -javaagent:SizeCalculate.jar SizeCalculate

The console output should display the size of the object:

Note: Output may vary slightly depending on the Java version and implementation you are using.

Output:

Console Output


Explanation of the above Program:

  • The premain method initializes the globalInstrumentation variable with the provided Instrumentation instance.
  • The getObjectSize method uses globalInstrumentation to get the size of an object.
  • The main method demonstrates object size calculation for a sample string "GeeksforGeeks".

Complexity of the Above Method:

Time Complexity: O(1)
Auxiliary Space: O(1), as no extra space is used


Next Article
How to Find Length or Size of an Array in Java?

G

gpancomputer
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

  • How to get the size of a JavaScript object ?
    In this article, we will see the methods to find the size of a JavaScript object. These are the following ways to solve the problem: Table of Content Using Object.keys() methodUsing Object.objsize() methodUsing Object.entries() methodUsing Object.values() methodUsing Object.keys() methodWe can get t
    2 min read
  • How to Get the Size of an Array in JavaScript
    To get the size (or length) of an array in JavaScript, we can use array.length property. The size of array refers to the number of elements present in that array. Syntax const a = [ 10, 20, 30, 40, 50 ] let s = a.length; // s => 5 The JavaScript Array Length returns an unsigned integer value that
    2 min read
  • How to Find Length or Size of an Array in Java?
    Finding the length of an array is a very common and basic task in Java programming. Knowing the size of an array is essential so that we can perform certain operations. In this article, we will discuss multiple ways to find the length or size of an array in Java. In this article, we will learn: How
    3 min read
  • How are Java Objects Stored in Memory?
    In Java, all objects are dynamically stored in the Heap memory while references to those objects are stored in the stack. Objects are created with the help of "new" keyword and are allocated in the heap memory. However, declaring a variable of a class type does not create an object it only creates r
    5 min read
  • Classes and Objects in Java
    In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh
    12 min read
  • Object Class in Java
    Object class in Java is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of the Java Object class and if it extends another class then it is indirectly derived. The Ob
    8 min read
  • Hashtable size() Method in Java
    The java.util.Hashtable.size() method of Hashtable class is used to get the size of the table which refers to the number of the key-value pair or mappings in the Table. Syntax: Hash_Table.size() Parameters: The method does not take any parameters. Return Value: The method returns the size of the tab
    2 min read
  • Files size() method in Java with Examples
    size() method of java.nio.file.Files help us to get the size of a file (in bytes). This method returns the file size, in bytes by taking the path of the file as a parameter. The size may differ from the actual size on the file system due to compression, support for sparse files, or other reasons. Th
    2 min read
  • Set size() method in Java with Example
    The java.util.Set.size() method is used to get the size of the Set or the number of elements present in the Set. Syntax: int size()Parameters: This method does not take any parameter. Return Value: The method returns the size or the number of elements present in the Set. Below program illustrate the
    1 min read
  • AbstractSet size() method in Java with Example
    The size() method of AbstractSet in Java is used to get the size for this instance of the AbstractSet. It returns an integer value which is the size for this instance of the AbstractSet. Syntax: public int size() Parameters: This function has no parameters. Returns: The method returns an integer val
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences