Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could we add structs to Java?

I've got asked this question at an interview and was unable to answer. Hope you can help me.

The question was: Why didn't Java guys add support for structs? Why is it impossible to add value types allocated on the stack to Java?

I suppose there should be some backwards compatibility issues with previous java versions? I am, however, unable to come up with any.

like image 374
user1096294 Avatar asked Jan 27 '26 13:01

user1096294


1 Answers

While Java doesn't allow Stack allocation, it does use something call Escape Analysis.

Found a link that touches on this: http://www.ibm.com/developerworks/java/library/j-jtp09275/index.html

The Java language does not offer any way to explicitly allocate an object on the stack, but this fact doesn't prevent JVMs from still using stack allocation where appropriate. JVMs can use a technique called escape analysis, by which they can tell that certain objects remain confined to a single thread for their entire lifetime, and that lifetime is bounded by the lifetime of a given stack frame. Such objects can be safely allocated on the stack instead of the heap. Even better, for small objects, the JVM can optimize away the allocation entirely and simply hoist the object's fields into registers.

like image 181
BlackHatSamurai Avatar answered Jan 29 '26 02:01

BlackHatSamurai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!