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.
Related
If I modify a static variable of a class does it get shared by previous instance of the class or only the new instance of the class.
I was just doing RMI and I have a class with static variables which I register to RMI registry. If I update the static variable by calling the RMI object it gets updated but if I update it by classname then check the value of the variable from the RMI object it gives me the old value.
If class A has a static variable s, then all instances of A in a given JVM will share that static variable. The JLS guarantees this.
Possible explanations for what you are seeing include:
You have managed to load class A multiple times in the JVM, using different classloaders. That will give you different A classes, as far as the type system is concerned, and each one will have different static variables.
You are actually talking to instances of A in a different JVM in the "by RMI" and "by classname". cases. The classes A in the different JVMs do not share static variables.
Various problems with your edit / build / deploy / run cycle.
Static variables or static method can be called without creating its class instance. Which means its values are same for all objects or any reference to that class. Does it mean we can get static values from class anywhere in our project.
In my case when user login I get all of the profile information and assign it to static variables in UserProfile.java class. Can these values be accessed anywhere in my project.
I don't want to use Shared-preferences or SQlite for storing this data.
Yes, static variables can be accessed directly from the class' name (MyClass.myVariable), as long as their access policy permits it.
Static variables are accessible directly from class without creating an object of class.
Variables you want to access must be public
you can simply access them like
YourClass.yourVariable
If those static values are public then you can access them from wherever you can access your class.
However, you cannot access classes across different modules, so to make that happen , you have to add compile project(':project_name') in your dependencies inside your gradle file.
This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Closed 8 years ago.
I'm quite new to Java and I'm trying to understand static variables and methods. Could someone give me a brief explanation of why I'd use the static method over the instance method and also what would be the ideal situation to use static variables? I know that static variables and methods are part of the class and not an instance of said class but I'm having trouble understanding when I'd use it.
Thanks!
These are the main differences
1.Static variables take memory only 1 time during the lifetime of program.
2.You can call static variables or methods. without creating the object of that class by classname only.
3.Static variables can be called in static and non-static context.
Mainly static variables are used to save memory because every object takes memory .
Static members relate to a type not a concrete instance. So instance methods and variables concern the identity of the instance, e.g. an instance method can alter the state of the object.
To some extend this is a religious question. Some people prefer to create static methods in a class when they do not access any instance variable. Other people do not like this approach. Another usual usage is creating factory methods, able to create an instance of an object while itself being called statically.
Often there are utility classes that contain static methods to serve clients with some functionality that is not bound to any type context. But all too often these utility classes get abused by using them as a trash bin for all sorts of methods a programmer did not find a fitting class for. This may be a result of poor design.
A popular use of static variables is the definition of an logger instance (e.g. SLF4J) for a class because loggers are thread safe and can be used by all instances and static methods alike. One advantage is (see a comparison) that only one instance has to be created for all instances of the containing class.
For static variable or method, you can think of that there is only one copy of the variable or method during the whole life time of the program.
So if you there is variable whose value should be shared across all the processes or thread, you can declare a static variable. For example, when you want to use a singleton pattern, you will need a static variable to indicate if there is instance of the class already.
For static methods, I would use them when state of the class is not important. I think the best example is java.lang.Math, they are all static methods, and returns the expected values to you no matter what you called before.
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 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.