Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object life cycle in java and memory management?

For the below statement in a program, how many objects will be created in heap memory and in the string constant pool?

I need clarity in object creation. Many sources I've read are not elaborating. I am confused when the object gets destroyed.

String a="MAM"+"BCD"+"EFG"+"GFE";

How many objects will be created?

I am looking for good material about the life cycle of objects, methods and classes and how the JVM handles them when they are dynamically changed and modified.

like image 563
saikiran Avatar asked Aug 07 '13 07:08

saikiran


People also ask

What is the life cycle of an object in Java?

We can break the life of an object into three phases: creation and initialization, use, and destruction. Object lifecycle routines allow the creation and destruction of object references; lifecycle methods associated with an object allow you to control what happens when an object is created or destroyed.

What is memory management in Java?

Memory management is the process of allocating new objects and removing unused objects to make space for those new object allocations. This section presents some basic memory management concepts and explains the basics about object allocation and garbage collection in the Oracle JRockit JVM.

What is object life cycle?

An object's life cycle—that is, its runtime life from its creation to its destruction—is marked or determined by various messages it receives. An object comes into being when a program explicitly allocates and initializes it or when it makes a copy of another object.

How long will an object take up memory Java?

Memory usage of some typical Java objects Theoretically, a long requires 4 more bytes compared to an int. But because object sizes will typically be aligned to 8 bytes, a boxed Long will generally take up 24 bytes compared to 16 bytes for an Integer.


1 Answers

"MAM"+"BCD"+"EFG"+"GFE" is a compile-time constant expression and it compiles into "MAMBCDEFGGFE" string literal. JVM will create an instance of String from this literal when loading the class containing the above code and will put this String into the string pool. Thus String a = "MAM"+"BCD"+"EFG"+"GFE"; does not create any object, see JLS 15.18.1. String Concatenation Operator +

The String object is newly created (§12.5) unless the expression is a compile-time constant expression (§15.28).

It simply assigns a reference to String object in pool to local var a.

like image 172
Evgeniy Dorofeev Avatar answered Oct 21 '22 22:10

Evgeniy Dorofeev