File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Code and  Data segment. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Code and  Data segment." Watch "Code and  Data segment." New topic

Code and Data segment.

Varun Khanna
Ranch Hand

Joined: May 30, 2002
Posts: 1400
Can anyone help me knowing what role exactly code segment and data segment plays in general in Java.
I just have an understanding that while creating 2 objects of same type,they contains there own class variable copy and shares same methos code in code that right? when actually is code loded in code segment ? How long it stays there?Does it comes into picture during compilation also?

- Varun
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
I am not exactly sure what you mean by "code segment" etc.
When a class is used in any manner, it is automatically "loaded" the first time by the JVM. This causes a Classfile to be created for it, all the code is loaded into the Method Area, and any static initializers are executed.
Methods, constructors and initializing code (both static and non-static) are kept in the Method Area of the Classfile. There is no "per instance" implementation of code. The classfile and it's methods stay until the class is unloaded. Most of the classes that you will use as a beginner are loaded by the bootstrap classloader and stay put until the JVM comes down.
Data that is related to a particular object of the class (fields) are kept in the object itself on the heap. So each object has a field that relates to each variable that defines it's current state. If it inherits variable from a Super class, the object has a place for that also (even if it is hidden by a variable with the same name in the subclass).
Static variables are kept in a central location related to the Classfile. These variables are "shared" by all instances of the class. Of course those variables may hold references to objects which are themselves on the heap.
[ July 17, 2002: Message edited by: Cindy Glass ]

"JavaRanch, where the deer and the Certified play" - David O'Meara
I agree. Here's the link:
subject: Code and Data segment.
It's not a secret anymore!