Meaningless Drivel is fun!*
The moose likes Programming Diversions and the fly likes Interesting Java interview question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Other » Programming Diversions
Bookmark "Interesting Java interview question" Watch "Interesting Java interview question" New topic
Author

Interesting Java interview question

Myke Enriq
Ranch Hand

Joined: Feb 13, 2012
Posts: 106
It goes like this : I am at a job interview , I am writing code on paper to create a class , and it hit me:

class A{
int x;
};

........

A a = new A();


When exactly is the memory for object a allocated ? What allocates memory for this object ?

The constructor of A is the default:
A(){
super();
}

At what line memory is allocated for a , and how much ?




Balaji Vankadaru
Ranch Hand

Joined: May 31, 2013
Posts: 47
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory.

The new operator also invokes the object constructor.

fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11152
    
  16

I don't think you can know how much memory is allocated. That isn't specified anywhere in the JLS, as far as I know.

Sure, it says an int can hold a 32bit number....but I believe that as long as my int BEHAVES in this way, I could allocate 256 bits, or 2048 bits, or whatever I want to store it.

It may make more sense to do so for memory alignment...i.e. the CPU is designed to expect 16-byte chunks of memory, so I have to allocate 16-byte chunks.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18505
    
  40

Myke Enriq wrote:
When exactly is the memory for object a allocated ? What allocates memory for this object ?

The constructor of A is the default:
A(){
super();
}

At what line memory is allocated for a , and how much ?


First, constructors, instance initializers, and initialization of instance variables are for initialization -- memory allocation is done before any of that happens.

As for when the memory is allocated -- the JLS isn't really strict. Except it is safe to assume that it is very early as it is not possible for any of the class code to run without the memory for the instance being allocated first.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Myke Enriq
Ranch Hand

Joined: Feb 13, 2012
Posts: 106
First I remember that years ago I was asked how much memory was allocated at the creation of a new object of some class with an int and String members. However I do not remember if it was Java or C++.

Secondly , there is a lot of magic in this line: A a = new A(); I still can not say at what moment in time a instanceOf A becomes true , and at what moment of time space is allocated for a.

For example , each object a has a lock on it , on which you can use synchronize(a) upon. So even if class A{} has no explicit class variables , it has at least that lock object.
Therefore at some point before the new A() instruction is executed , memory is allocated to a.

Where can I find these answers ? I am programming in Java daily yet I can not help feeling that I may have a severe misunderstanding of this issue , that could prove important.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11152
    
  16

Since the JLS doesn't specify how it needs to be done, the answer can vary depending on which exact JVM you are using. If Henry writes one, he may decide to do it HERE, and if I write one, I may decide to do it THERE.

Really, the whole purpose of a high-level language like Java is that you don't know, you don't NEED to know, and you shouldn't care. If knowing the exact instruction set is critical, then you'd be better served by writing your code in assembly or some other low-level language.
Myke Enriq
Ranch Hand

Joined: Feb 13, 2012
Posts: 106
fred rosenberger wrote:Since the JLS doesn't specify how it needs to be done, the answer can vary depending on which exact JVM you are using. If Henry writes one, he may decide to do it HERE, and if I write one, I may decide to do it THERE.

Really, the whole purpose of a high-level language like Java is that you don't know, you don't NEED to know, and you shouldn't care. If knowing the exact instruction set is critical, then you'd be better served by writing your code in assembly or some other low-level language.


I actually can not sleep because of this question.

Anyway , I earn my living by programming in Java , surely you cna understand why I care about this question.


On a more serious note , I have a feeling it makes a big impact on the way I write code if I actually know what creating a java object means , what default functions and members class A{} has , and when and at how memory for new A() is allocated.

Please tell me where I can search for answers.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18505
    
  40

Myke Enriq wrote:First I remember that years ago I was asked how much memory was allocated at the creation of a new object of some class with an int and String members. However I do not remember if it was Java or C++.


In Java, there is no direct way to get the memory requirements (the size) of a class. It doesn't matter anyway -- about the only reason to know the exact memory size is to do pointer arithmetic, which you also can't do in Java.

In C++, you can use the sizeof() operator.

Myke Enriq wrote:
Secondly , there is a lot of magic in this line: A a = new A(); I still can not say at what moment in time a instanceOf A becomes true , and at what moment of time space is allocated for a.


It is not possible for any code, internal or external, to get to an instance before the memory has been allocated. It is possible to get to the instance before initialization has been completed, but not before memory allocation (along with other stuff). Hence, there is no point where is becomes true. If you can take an instanceof operator on the instance, then it is or it isn't -- there is no point where it will change.

Henry
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18505
    
  40

Myke Enriq wrote:
On a more serious note , I have a feeling it makes a big impact on the way I write code if I actually know what creating a java object means , what default functions and members class A{} has , and when and at how memory for new A() is allocated.

Please tell me where I can search for answers.



I don't agree. I think there are tons of stuff that is orders of magnitude more important.... but to each its own. One option is to use the source code -- you can download it from the openjdk open source page.

Henry
Myke Enriq
Ranch Hand

Joined: Feb 13, 2012
Posts: 106
Object[] container;

My task is to permute the container , and today I was talking about this piece of code with my examiner at a job interview:

// swap container[i] with container[j]
aux = container[i]; container[i] = container[j] ; container[j] = aux;

other programmer: would it not have been better to write a swap function ?
me: a swap function adds extra costs
other programmer: but you can easily read this line of code if it had a swap function plus it is a OOP principle
me: surely performance is more important than readability
other programmer: got to lecture me for half an hour how readability is more important than performance , and got a reason not to hire me and he probably went to his bosses and reported I am too stupid to work there.

Anyhow, lets analyze the cost of a poorly written swap function:


// swap container[i] with container[j]
swap(Object[] container , int i , int j){
Object aux;
aux = container[i]; container[i] = container[j] ; container[j] = aux;
}

Costs of swap function:
- creates a new Object each time it is called !
- uses stack
- creates a copy of container reference
- adds an extra function to that class

Bu wait , there is more. I actually do not want to swap Object[] container , but MyClass[] container. As MyClass eventually extends Object , the cost to create a MyClass object is a bit greater than the cost to create an Object object. What is this cost ?

And about readability , as that guy was obsessed by it. You actually need to declare a class member aux so the swap function is like this:
swap(Object[] container , int i , int j){
this.aux = container[i]; container[i] = container[j] ; container[j] = this.aux;
}

So instead o having a line of code in a function , you add a new member and a new function to the class , both having a very remote connection to the purpose of that class. Since with any class you
get to read its members and functions declarations probably ten times more than you actually read the code in a single one of those functions , it may actually decrease readability.


In conclusion , I did not get the job , but I can not help myself feel that if I knew the actual costs and process of creating a new Object object , I would have tipped the balance in my favor.

But I digress. Please tell me where can I find more information of how JVM creates new objects and allocates memory.
I would very much love to see a diagram of this process , if possible.

Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18505
    
  40

Myke Enriq wrote:
But I digress. Please tell me where can I find more information of how JVM creates new objects and allocates memory.
I would very much love to see a diagram of this process , if possible.


Sorry, but as I mentioned, your best option is with the OpenJDK source code. When I had to do something similar to this many years ago, the source code was the only option. The JLS doesn't really define it to this level, and no books seems to go this deep either. If such information exists, I certainly didn't know about it.

Also, I was working with Java 5, so I was working with the Sun source code, and not OpenJDK source code, but it should be similar. And if it is similar, then you will need to bone up on C. You will also need to figure out a set of weird macros (written with the C preprocessor) -- admittedly, I never really completely figured it all out. Most of my work was bug fixing (back then), and I never really got to see how the memory management system work as a whole -- particularly all the stuff related to the garbage collector(s). Regardless, good luck. It is definitely not an easy task that you are considering.

Henry
Anish Nath
Greenhorn

Joined: Sep 21, 2011
Posts: 23
The product compnay Interview pattern's, interview questions and answers on google,amazon,adobe,cisco and other product company tips
[youtube]http://youtube.com/watch?v=OX-r4CjVfYg[/youtube]
Cracking Interview
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Interesting Java interview question
 
Similar Threads
space allocation for class
Memory accocation in case of arrays
difference between exe file and batch file
Memory allocation for objects & variables?
How memory is allocated to objects in heap?