I am little bit confused that where did static variables and methods are loaded. we say that static variables and methods are loaded in the static memory. bt public static void main() is loaded into stack .Since main() method is also static then how it is possible that main is loaded into stack.
and alse is static methods and variable are stored in different positions because we say that methods are loaded in different place in memory.
The stack is where things go when they are invoked/executed. It doesn't matter if it is static or not. Any running function goes onto the stack where it's local variables and all are held until the stack frame is popped.
For example, I can have main() call main() recursively over and over. Each one would be a new stack frame. The fact that it is a static function does not change that.
Static variables, on the other hand, are different. There will only be one instance of them and you know it explicitly. So, they can go into special storage and be treated differently (as are other global things like the class definitions and all that).
The actual implementation of this is not liable to be very useful, nor easily understandable. However, a model of it might help you understand the use of these things.
First of all, data and code are quite different animals in Java. Variables are going to have values that change at runtime; code never does that. So when you instantiate a class, you are never going to get another copy of the code.
Consider the class Class - instances of it exist, one per fully-qualified class in the program. I think of all code for one class, static or not, as being associated with its Class instance -- 'loaded' with it, if you prefer. Incidentally, and coincidentally, that's also where I think of its static variables being 'loaded'.
But the instance variables need multiple copies -- whenever you instantiate the class, you need another copy of them. So they are associated (or loaded) with the instance of the class when instantiated -- think of the pointer to the class as a pointer to a structure that contains all the instance variables of that class, plus a pointer to jump tables to its methods, etc.
I do not know what you mean by public static void main being "loaded onto the stack". Do you mean the code? Code never goes onto a stack per se. It wouldn't make any sense to have code from a (normal) class put on the stack, lost when the current method returns, and then have to load it again if the method were called.
I think there's part of your question I'm not getting to because I don't understand what you're asking.
Related
I would like to know that if I have the following class.
class Example {
public static void method1() {}
public void method2() {}
public void method3() {}
}
Only 1 method is static and it should be the first thing to be loaded in the memory during runtime. But what about the instance methods? Are they loaded in the memory when an instance of this class is created? Or are they already loaded when the class is loaded initially.
What I am trying to understand is if it is a better approach to have all the functionality in the same class by having separate methods for each functionality or is it better to create a separate class for each functionality with only there respective methods in its class.
So will it help memory wise in the later case because I will only create the instance of the class that I need to use and only that much of methods will be loaded in the memory. Otherwise, in the former case, where I have 100 methods in the same class, but I only need to use just 2 methods out of them, it will be waste of memory because all 100 methods are loaded.
Any suggestions?
Actually memory allocation for class variables and class member functions/methods are done differently. When a class is being instantiated its class variables are being created in the memory which is call as data segment and method codes are created in code segment. IF we create ten objects of a particular class java virtual machine will create ten different code segments but only one code segment will be created for all the object. Java virtual machine will create a code segment only when there is at least one reference to that that class object in the code else it will not.
Code segment captured minimal memory only. It just stores assembly instructions created from code. Hence you no need to worry about it. For object also a programmer no need to worry about managing the memory in Java as there is a garbage collector in java.
Now answer to your question in my comment section:-
But will the methods themselves be stored somewhere in heap etc. ? So a class having 100 methods or 2 methods will behave the same memory wise?
As I said your method's codes will be converted into assembly instruction by your java virtual machine and will be stored in the memory in an instruction pointer for each method. Not necessarily now many method, it will depends on lines of code, recursion, loops, and condition etc. Yes if 100 methods of same size of codes with all the above then it will takes more memory than two methods.
I am fairly new to Java, this particular question has arisen because I am trying to do some Swing programming for the first time but it is a general Java question.
I have a class with some instance variables, I need to create one (and only one) object to hold the variables and methods. Is there a best/approved place to create the object, should it be declared and instantiated in the class' attribute definition :
public class TestClass {
static TestClass tC = new TestClass();
...
or declared in the class' attributes definition and instantiated by a static method (e.g. main later on) :
public class TestClass {
static TestClass tC;
...
public static void main(String[] args) {
tc = new TestClass();
}
Or somewhere else, does it matter?
Or somewhere else, does it matter?
It certainly does matter, if you see it generally enough.
Placing the initialization inside the main method will be relevant only to those uses of your class where this particular main method is executed. If your class has any scope of usage larger than a single program, that particular avenue of initialization will be as good as non-existent.
Placing the initialization inline with declaration ensures that the field is initialized for all users of the class, independent of the code path taken to access it.
Additionally note that in real-world programs, hardcoding singleton initialization like that very often interferes with the full extent of intended usage. The singleton often depends on some kind of initialization data, and that data may not be available at class initialization time. There may be several independent "zones" in a larger program, each needing a differently initialized singleton. Testing concerns usually imply substituting a mock implementation instead of your class, and so on.
So, either of your approaches may work for you currently, but also neither of them may be enough in a more complex scenario.
If you instantiate the variable where you declare it as a field, it will be created as the class is first initialised (that is, when it's first "touched".) If you initialise it in the main method, then it will be initialised, well, whenever that particular line in that method is executed.
If it doesn't make a difference functionally, then one could argue that the inline declaration ensures that it's never null when a method comes to deference it (this could be further strengthened by making the field final if you can.) In the grand scheme of things though, it probably doesn't matter too much.
I've got a Java worker that handles a lot of data. It waits on a Redis queue in main() and then calls different functions to handle the data depending on type.
I've got two questions on optimizing the code:
Would it be better to have private static class variables and use them to send data to methods instead of using function arguments?
Would it speed up execution time if variables used in these often-called methods would be private static on class instead of declared always over again when entering the method?
Thanks
You are talking about speed, but static variables will help you mostly memory-wise.
If you are creating multiple instante variables (non-static fields) and thinking of changing to into a static one:
When multiple instances of a class need access to a particular object in a variable local to those instances (instance variable), it is better to make that variable a static variable rather than have each instance hold a separate reference. This reduces the space taken by each object (one less instance variable) and can also reduce the number of objects created if each instance creates a separate object to populate that instance variable. (Quoted from Java Performance Tuning book.)
If you are not creating instance variables, but just passing a variable along in parameters:
Performance-wise, there should be no difference. As a all method parameters in Java are passed value-by-reference, meaning that the actual variable is not copied over an over: only its address (pointer - a reference to the variable) is copied into the parameter of the called method.
In any case, static fields can compromise your code's readability (it can make them so much harder to maintain). If you really need a static behaviour, please also consider using a Singleton design pattern.
Bottom line is:
Seems to me your scenario is: You are just passing variables along (an not having instance variables).
I advise you to keep it that way. If you change it, there will be near-zero (if any) performance gain by using static fields -- on the other hand, your code will be much harder to maintain/understand/debug.
I just want to see what you guys might think the difference (in terms of usage, efficiency, or even good practice) with regard to android development.
If I use a static variable in one of my base activity (so its single instance and be access everywhere), as opposed to using a non static variable in my application subclass (which is a single application class for all the activities).
Both will achieve the same end results if you try to use a global variable.
I was using the static one then I moved to use the application subclass (in case you guys wonder "what is it I am using for", I wanted to play background music and control it from everywhere and I don't wish to use service for certain reasons).
Any help clarifying the best way to ?
It depends on use also, suppose if you are using
android:process
for some reason in your Activity or anything else in your Manifest file your static value will be reset and you will get the initial value assigned to static variable. In that case you can use SharedPreference or Application class.
Because if you use android:process for any particular Activity then that Activity will run in another process and as we know that in Android every Application runs in its own process.
Other than this I don't see there is much issue using static. But, personally I would prefer Application class as Android has it for global variables.
During the execution of a program, each variable has its own time within which it can be accessed. This is called the lifetime of the variable.
Instance variables:
Instance variables are class members. Every time you create an object from a class, a brand new copy of these instance variables is created for this object. Actually, creating an object from a class means, partially, creating copies of instance variables for that object. So each object has its own copy of instance variables which exist as long as the object they belong to exists. The values of these variables constitute what we call: the state of the object.
Static variables:
Static variables are also members of a class but can't belong to any object created from that class. So created objects from the class don't get their own copies of static variables. Therefore static variables are created only when the class is loaded at runtime. The existence of static variables is dependent only on the class itself. As a result, a static variable exists as long as its class exists.
One of main difference between these two variable is that when you are calling System.gc(); your instance variable is set to null while static variable will never set to null by calling gc.
I have a global boolean variable which I use to disable all trading in my financial trading system.
I disable trading if there is any uncaught exception or a variety of other conditions (e.g. no money in account).
Should this variable be static or an instance variable? If its an instance I will need to add it to constructors of loads of classes...Not sure if its worth the hassle.
Thxs.
If it's an instance, then you probably want it to be a Singleton, and you'll provide a public static getter (or a factory, or DI if you care about testing).
If you access it from multiple threads, then it'd better be an AtomicBoolean in both cases.
Throughout your entire career, the number of times that you will have a valid use for a global variable will be countable in the fingers of one hand. So, any given time you are faced with a "to global or not to global" decision, most chances (by far) are that the correct answer is NOT. As a matter of fact, unless you are writing operating system kernels and the like, the rule of thumb should be "do not, under any circumstances, make any variable whatsoever, anywhere, anytime, global."
Note that wrapping access to a global variable in a global (static) method is just fooling yourself: it is still just a global variable. Global methods are only okay if they are stateless.
The link provided by #HermantMetalia is a good read: Why are static variables considered evil.
In your case, what you need is probably some kind of "Manager" object, a reference to which you pass as a construction time parameter to all of your major logic objects, which, among other things, contains a property called "isTradingAllowed" or something like that, so that anyone interested in this piece of information can query it.
I'd put it in a static field. But prefer to make it an AtomicBoolean to prevent threading issues :-)
public class TradeMaster {
private static final AtomicBoolean TRADING_ALLOWED = new AtomicBoolean(true);
public static void stopTrading() {
TRADING_ALLOWED.set(false);
}
public static boolean isTradingAllowed() {
return TRADING_ALLOWED.get();
}
}
Static Pros:
No need to pass references to instance to every class which will be using this
Static Cons:
May lead to difficult in testing - I think it should be fairly easy to test a static variable if you set the state of the variable before and after the test (assuming the tests are not running concurrently).
Conclusion:
I think the choice here depends on what your view of testing static variables is...For this simple case of one variable managing the state I really cant see the problem with using static. On the otherhand...its not really that hard to pass an instance to the constructors of the dependent classes so you dont really have any downside when using the instance approach.
It should be static since it will be shared by all the instances of
this class.
It should be static since you dont want to have a separate variable for all the objects.
Given that I would suggest that you read some good resources for static variable usage they work like charm unless you mess them..
If you want to make a variable constant for the class irrespective of how many instances are creted then use static method. But if the variable may change depending on the use by different instance of class then use instance variable.
Example
*
Here is an example that might clarify the situation. Imagine that you
are creating a game based on the movie 101 Dalmations. As part of that
project, you create a Dalmation class to handle animating the various
Dalmations. The class would need instance (non-static) variables to
keep track of data that is specific to each Dalmation: what its name
is, how many spots it has, etc..
*
But you also need to be able to keep track of how many Dalmations have
been created so you don't go over 101. That can't be an instance
variable because it has to be independent of specific Dalmations. For
example, if you haven't created any Dalmations, then this variable has
to be able to store zero. Only static variables exist before objects
are created. That is what static variables are for - data that applies
to something that is beyond the scope of a specific instance of the
class.