Reputation: 257
1)Why java is stored in RAM and not stored in hard disk. 2)And what is the benefit of static variable over normal variable. Whether normal variable occupy more memory space since objects of classes have it's own copy.
Upvotes: 0
Views: 1845
Reputation: 61526
All running programs are stored in memory regardless of programming language. I'll assume you mean why use .class files instead of .exes. That is for portability, the runtime basically translates the .class files into a .exe at runtime so the same binary can be run on any platform rather than having to provide a different file for each platform.
Yes, instance variables use more memory than class variables since each instance has its own copy. Static variables have all instances share the same copy. If you consider a person, each person has their own name (instance variable) while the # of eyes people have is constant for everyone, barring birth defects and accidents (class variable). Class and instance variables serve very different purposes.
Upvotes: 1
Reputation: 55448
Why java is stored in RAM and not stored in hard disk
If you're talking about variables, storing variables in RAM allows for fast read/write access, orders of magnitude faster than disk. Java can access disk as well.
what is the benefit of static variable over normal variable.
Static variables are not tied to a particular instance of a class, so you can access without having to create an object, but that static variable will be shared among every piece of code that has a reference to it.
Whether normal variable occupy more memory space since objects of classes have it's own copy.
Each time you instantiate an object it will take space in memory. Sometimes it's exactly what you need.
Example:
public class Bicycle{
private int cadence;
private int gear;
private int speed;
// add an instance variable for the object ID
private int id;
// add a class variable for the number of Bicycle objects instantiated
private static int numberOfBicycles = 0;
......
}
Each time you do a new Bicycle()
you will be creating a new object (thus using more memory) with all its attributes except for numberOfBicycles
, there will be only one of that attribute for all instances of Bicycle
.
Upvotes: 2
Reputation: 98469
Upvotes: 4