7 Java primitives & objects memory consumption Q&As

Q1. How much memory space does a primitive type int occupy in Java?
A1. 4 bytes.

Java primitive data types

Java primitive data types

Q2. Java objects get stored in the heap memory space, but how about the primitive variables?
A2. It depends.

Stack vs Heap

Stack vs Heap

1) Primitives defined locally would be on the stack.

2) If a primitive is defined as part of an instance of an object, that primitive would be on the heap

Q3. How much space does java.lang.Integer object occupy?
A3. Java objects need to store 1) object metadata information and then the 2) data .

java.lang.Integer object metadata on a 32bit JVM

1) Class information: 32 bits = 4 bytes.
2) Flags: array or not, hashCode, etc : 32 bits = 4 bytes.
3) Lock information: synchronization 32 bits = 4 bytes.

java.lang.Integer data

int is = 32 bits = 4 bytes.

Total memory occupied on a 32bit JVM is = 128 bits = 16 bytes. This is 4 times the space occupied by a primitive.

java.lang.Integer object metadata on a 64bit JVM

1) Class information: 64 bits = 8 bytes.
2) Flags: array or not, hashCode, etc : 64 bits = 8 bytes.
3) Lock information: synchronization 64 bits = 8 bytes.

java.lang.Integer data

int is 32 bits = 4 bytes.

Total memory occupied on a 64bit JVM is = 224 bits = 28 bytes.

So, if you take an application that was running on a 32 bit JVM and port it to a 64 bit JVM, it is going to require more memory.

Q4. How much space does java.lang.Integer[] array with 1 element occupy on a 32 bit JVM?
A4. Very similar to an Integer object, but requires an extra object data called “size

java.lang.Integer[] object metadata on a 32bit JVM

1) Class information: 32 bits = 4 bytes.
2) Flags: array or not, hashCode, etc: 32 bits = 4 bytes.
3) Lock information: synchronization: 32 bits = 4 bytes.
4) Size of the array 32 bits = 4 bytes.

Then depending on how many elements are in an array: 32 bits or 4 bytes per data.

An array of size 1 will consume = 160 bits = 20 bytes.

Q5. Can you arrange the following Collection data types in terms if their memory overheads in ascending order?

1) ArrayList
2) LinkedList
3) HashSet
4) HashMap

A5. ArrayList –> LinkedList –> HashMap –> HashSet.

1) ArrayList is the least in terms of memory overhead as it is backed by a data structure of type array. A default size of an array list is 10 entries.

2) A HashSet has the highest memory overhead and it takes more memory than a HashMap because internally a HashSet uses a HashMap to store data. So, it needs space for the HashMap + additional meta data space to wrap around a HashMap.

3) A HashMap by default creates a backing data structure (i.e. an array) with a capacity for 16 objects regardless of you add all 16 objects or not. Hence it consumes more memory than a LinkedList as a linked list only occupies space for whatever data that is added.

4) A HashMap uses additional object entries for key, value, next reference (i.e. for iterating), and an int to store hash value whereas a LinkedList uses only next & previous references in addition the data themselves.

So, when using a collection type in Java, it is always a trade off between memory usage & functionality. Some collection types even though consume more memory, but functionally more efficient. For example, a HashMap lookup of elements on average is O(1). This is explained Understanding “Big O” Notation in Java with examples.

Q6. How will you go about evaluating sizeof an object in Java?
A6. Java does not have a sizeof operator like C++ does. Java uses automatic memory management known as the Garbage Collection, hence it is not that important to evaluate size of various objects. But, for the learning purpose, I have used “jvisualvm”, which is a very handy & free profiling tool that gets shipped with the JDK. Step by step instructions are provided: jvisualvm to sample Java heap memory

Q7. What are the best practices with regard to conserving memory when using Java Collections?
A7. 1) Set the initial capacity of the collection appropriately so that the space is not unnecessarily wasted. Most collections double their capacity when the current capacity is reached.

For example, to store 130 elements in a Map, initialize it to say 150, rather than using the default capacity of 16, which has to grow like 16 –> 32 –> 64 –> 128 –> 256, where 256, where 256 is a lot greater than 130.

2) Lazily initialize your collections. This means initialize it just before adding elements.

300+ Core Java Interview Q&As
Module 1 Java Overview+
Unit 1 17 Java Overview Interview Q&As  - Preview
Unit 2 4 Java Compile-time Vs Runtime Interview Q&As  - Preview
Module 2 Java data types-
Unit 1 8 Java data types interview Q&As  - Preview
Unit 2 7 Java primitives & objects memory consumption Q&As  - Preview
Unit 3 4 Java autoboxing & unboxing interview Q&As  - Preview
Unit 4 12 Java String class Interview Q&As  - Preview
Module 3 Java modifiers, annotations, initializers & constructors+
Unit 1 6 Java Modifiers every interviewer seems to like  - Preview
Unit 2 10 Java initializers, constructors, regular methods and static factory methods Q&As
Unit 3 8 Java Annotations interview Q&As
Unit 4 4 Java annotation types & processing interview Q&As
Module 4 Java classes, interfaces & class loaders+
Unit 1 12 Java classes and interfaces interview Q&As
Unit 2 3 Abstract classes Vs interfaces interview Q&As
Unit 3 3 Java class loading interview Q&As to ascertain your depth of Java knowledge
Module 5 Java Objects Interview Q&As+
Unit 1 5 Java Object class methods interview Q&As  - Preview
Unit 2 3 Object wait( ) & notify( ) interview Q&As
Unit 3 7 Object equals Vs == and pass by reference Vs value interview Q&As
Unit 4 10 Java immutable objects interview Q&As
Unit 5 10 Java serialization, cloning, and casting interview Q&As
Module 6 OOP & FP+
Unit 1 10 Java OOP Interview Q&As
Unit 2 5 Inheritance Vs Composition OOP Interview Q&As  - Preview
Unit 3 2 Polymorphism OOP Interview Q&As
Unit 4 8 OOP Design principles interview Q&As
Unit 5 5 OOP Vs FP, FP concepts & where to use FP Q&As  - Preview
Unit 6 19 Java Functional Programming (i.e. FP) interview Q&As
Unit 7 Java FP Lambda expressions by examples
Module 7 Generics & Java Collection Framework(JCF)+
Unit 1 12 Java Generics Interview Q&As  - Preview
Unit 2 5 Java Generics Wildcards Interview Q&As
Unit 3 17 Java Collection Framework (JCF) interview Q&As
Unit 4 9 Java data structures interview Q&As
Unit 5 4 Sorting objects in a Collection interview Q&As
Unit 6 8 Java Map interface & Caching interview Q&As
Unit 7 Lambda expressions to work with Java 8 Collections
Module 8 Java multithreading+
Unit 1 17 Java multi-threading interview Q&As  - Preview
Unit 2 7 Java locks & synchronized keyword interview Q&As
Unit 3 9 blocking, scheduling & daemon threads interview Q&As
Unit 4 7 Java Executor framework Interview Q&As
Unit 5 ExecutorService Vs Fork/Join & Future Vs CompletableFuture Interview Q&As
Unit 6 7 Java ThreadLocal interview Q&As
Unit 7 Java Thread stop, resume, suspend & interrupt interview Q&As
Unit 8 12 Java multi-threading differences between X and Y Q&As
Unit 9 Java multi-threading 15 scenarios interview Q&As
Module 9 What is wrong with this multithread code?+
Unit 1 5 Ways to debug Java thread-safety issues  - Preview
Unit 2 Heap Vs Stack, Thread safety & Synchronization  - Preview
Unit 3 Deep Vs Shallow comparison & multithreading
Unit 4 An excellent written test multithreading question - wait/notify
Unit 5 Multithreading & Locks
Unit 6 Java Collection & ConcurrentModificationException
Unit 7 HashMap & Race condition
Unit 8 ConcurrentHashMap & Atomic operations
Unit 9 JConsole for debugging deadlocks in Java
Unit 10 jvisualvm to debug deadlocks in Java
Module 10 Exceptions Handling+
Unit 1 5 Java exception handling interview Q&As
Module 11 Java I/O & NIO+
Unit 1 15 Java old I/O and NIO (i.e. New I/O) interview Q&As
Unit 2 Java 8 way to reading files
Module 12 JVM+
Unit 1 11 JVM memory model and Atomicity, Visibility, and Ordering interview Q&As
Unit 2 8 Java Garbage Collection interview Q&As to ascertain your depth of Java knowledge
Unit 3 jvisualvm to sample Java heap memory
Unit 4 5 JMX and MBean interview Q&As
Module 13 What is new?+
Unit 1 Java 7 features list
Unit 2 Java 8 features list
Module 14 Java code quality+
Unit 1 How will you go about improving on the following Java code?
Unit 2 How will you go about ensuring code quality in Java apps?
Unit 3 5 Java unit testing interview Q&As
Unit 4 Mocks, stubs, domain, and anemic objects interview Q&As
Unit 5 30+ Java Code Review Checklist Items
Module 15 Debugging Java applications+
Unit 1 7 debugging Java interview questions & answers
Unit 2 Debugging "NoSuchMethodError" in Java
Unit 3 Debugging JAR hell issues in Java
Unit 4 Debugging Java version issues
Unit 5 Remote debugging in Java with Java Debug Wire Protocol (JDWP)
Unit 6 Debugging like a pro with eclipse IDE tutorial for Java developers
Module 16 Performance considerations & memory management+
Unit 1 4 Java application performance considerations interview Q&As
Unit 2 8 Java memory management interview Q&As
Unit 3 jvisualvm to detect memory leak
Module 17 Design Patterns Interview Q&As+
Unit 1 12 Java design patterns interview Q&As
Unit 2 5 Java singleton design pattern interview Q&As
Unit 3 Java Proxy, Decorator, Adapter, Bridge, and Facade design patterns Interview Q&As
Unit 4 3 Flyweight design pattern Interview Q&As to improve memory usage & performance
Learn by categories on the go...
Learn by categories such as FAQs – Core Java, Key Area – Low Latency, Core Java – Java 8, JEE – Microservices, Big Data – NoSQL, Architecture – Distributed, Big Data – Spark, etc. Some posts belong to multiple categories.