When is it better to use static variable? [duplicate] - java

This question already has answers here:
Difference between Static and final?
(11 answers)
Closed 5 years ago.
I am wondering why sometimes I see code with static variable? When is it better to use static variable instead of "normal" variable? If its value do not change from an istance to another, is it not better to use final variable?

The point in using static variables is not the same as final ones.
Final-declared variables (static or not) cannot be modified. They are often used as "reference values" or constants.
Static-variables (and methods) are therefore needed as "shared content". For instance, say each person in the office likes to drink coffee. Are we better of with everyone bringing his own coffee machine ? Or are we better sharing one such machine for the entire office ?
Obviously you want to chose the shared option. In a programming idiom, this would translate to having a static variable in the Office class representing the unique CoffeeMachine.
Off-topic but surely you wouldn't want to make this coffee machine final. What if someone breaks it ? You would need to replace it, and thus change the variable.

static means, that the variable is in all instances of this Object the same.
The Main example is a Object-Counter.
class foo{
private static int count = 0;
public foo()
{
count ++;
}
public static getCountOfObj()
{
return count;
}
}
So you can edit it on all foo-Objects.

static variables are used when only one copy of the variable is required. so if you declare variable inside the method there is no use of such variable it's become local to function only..
Variables declared static are commonly shared across all instances of a class.

I assume you mean static fields.
static fields are associated with the class, whereas instance fields are associated to an object (aka class instance).
If a field is marked as final (works for both instance and static fields), then it cannot be reassigned.
So each has its own different role to play.

Related

Why there's no error in this code? j is final and static but still accessible using object of class how? [duplicate]

This question already has an answer here:
How static fields are referenced through objects? [duplicate]
(1 answer)
Closed 2 years ago.
interface TempInterface {
static final int j = 30;
}
class TempClass implements TempInterface {
}
public class Try {
public static void main(String args[]) {
TempClass obj = new TempClass();
System.out.println(obj.j);
}
}
In Java, the static keyword means that the variable can be accessed by every object of a class. Java forces every variable in an interface to be both static and final, so every object of a class that implements it will be able to access that variable, but not change it.
A static variable is nothing more than a fixed memory location shared by all instances of the class (since it belongs to the class itself). This means that all of the instances can access it since they know its location. Note however that it is usually frowned upon if you access a static field from an instance instead of a class reference.
For further information I suggest you read up on Oracle's tutorial regarding class variables. To quote a section:
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
Regarding interfaces, you can think of them as special types of classes, so by implementing an interface you inherit all of its data as well (i.e. static variables).
Static means that you have access without need to create new instance, final means - you can'not change but you may get this.
And I can note what interface variable may be accesed from another package too because it's also implicitly public (as static and final).

Java - Is it ok to instantiate class objects inside class? [duplicate]

Why can we access a static variable via an object reference in Java, like the code below?
public class Static {
private static String x = "Static variable";
public String getX() {
return this.x; // Case #1
}
public static void main(String[] args) {
Static member = new Static();
System.out.println(member.x); // Case #2
}
}
Generally, public variables can be accessed by everybody, and private variables can only be accessed from within the current instance of the class. In your example you're allowed to access the x variable from the main method, because that method is within the Static class.
If you're wondering why you're allowed to access it from another instance of Static class than the one you're currently in (which generally isn't allowed for private variables), it's simply because static variables don't exist on a per-instance basis, but on a per class basis. This means that the same static variable of A can be accessed from all instances of A.
If this wasn't the case, nobody would be able to access the private static variable at all, since it doesn't belong to one instance, but them all.
The reason that it is allowed is that the JLS says it is. The specific sections that allows this are JLS 6.5.6.2 (for the member.x cases) and JLS 15.11.1 (in both cases). The latter says:
If the field is static:
If the field is a non-blank final field, then the result is the value of the specified class variable in the class or interface that is the type of the Primary expression.
If the field is not final, or is a blank final and the field access occurs in a class variable initializer (§8.3.2) or static initializer (§8.7), then the result is a variable, namely, the specified class variable in the class that is the type of the Primary expression.
Why are these allowed by the JLS?
Frankly, I don't know. I can't think of any good reasons to allow them.
Either way, using a reference or this to access a static variable is a bad idea because most programmers are likely to be mislead into thinking that you are using an instance field. That is a strong reason to not use this feature of Java.
In your first and second cases you should reference the variable as x or Static.x rather than member.x. (I prefer Static.x.)
It is not best practice to reference a static variable in that way.
However your question was why is it allowed? I would guess the answer is to that a developer can change an instance member (field or variable) to a static member without having to change all the references to that member.
This is especially true in multi-developer environments. Otherwise your code may fail to compile just because your partner changed some instance variables to static variables.
static variables are otherwise called as class variables, because they are available to each object of that class.
As member is an object of the class Static, so you can access all static as wll as non static variables of Static class through member object.
The non-static member is instance member. The static member(class wide) could not access instance members because, there are no way to determine which instance owns any specific non-static members.
The instance object could always refers to static members as it belongs to class which global(shared) to its instances.
This logically makes sense although it is not interesting practice. Static variable is usually for enforcing single declaration of variable during instantiation. Object is a new copy of Class with other name. Even though object is new copy of class it is still with characteristics of the (uninstantiated) Class (first invisible instance). Therefore new object also has that static members pointing to the original copy. Thing to note is: New instance of StackOverflow is also StackOverflow.

What is this variable public final static [duplicate]

This question already has answers here:
when exactly are we supposed to use "public static final String"?
(13 answers)
Closed 9 years ago.
I am a beginner in Java Programmer and do not understand what is this variable: public final static int ID = 8; please tell me a definition or example code. Thanks.
public - Any object can see it, even objects that use your code as a library.
final - its value will never change.
static - however many objects of this class you create, there will be only one.
int - it is a 32-bit integer.
ID - it can be referred to by this name.
= - it is immediately assigned the value.
8 - it will have the value 8 (decimal).
This form is commonly used for constant values. The compiler will often replace every access to it with its constant value instead.
public means that it can be accessed from other classes
final means it cannot be reinitialized i.e its value can't be changed after initialization.
static means that all instances of the class use the same exact field (unlike non-static fields where each instance has their own version of the field). static fields are described as being 'class variables' Similarly, non-static fields are called 'instance variables'
public means it accessible by any other class outside of that one.
final means once the variable is declared it cannot be changed.
static means the variable can be accessed from any method within the class.
int is a primitive data type declaration.
These are all basic concepts of Java OOP, so I'd recommend reading about it a little.
Declaring Variables: http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html

Java Static vs Instance

So my coder friend hates using the static coding. Yet my Java program is full of it to link between classes, and I have a lot of them!
Is it worth rewriting the whole code to remove the static method?
Is there any advantage of using one over the other?
1. An instance variable is one per Object, every object has its own copy of instance variable.
Eg:
public class Test{
int x = 5;
}
Test t1 = new Test();
Test t2 = new Test();
Both t1 and t2 will have its own copy of x.
2. A static variable is one per Class, every object of that class shares the same Static variable.
Eg:
public class Test{
public static int x = 5;
}
Test t1 = new Test();
Test t2 = new Test();
Both t1 and t2 will have the exactly one x to share between them.
3. A static variable is initialized when the JVM loads the class.
4. A static method cannot access Non-static variable or method.
5. Static methods along with Static variables can mimic a Singleton Pattern, but IT'S NOT THE RIGHT WAY, as in when there are lots of classes, then we can't be sure about the class loading order of JVM, and this may create a problem.
static is for the cases where you don't want to have copy for each instance
instance variables are for the cases where you want separate copy for each instance of object.
Based on business cases, which one to use may change.
If you have too many static functions and variables it can lead to a more functional approach rather than true OO. Also if you have public static variable then you replicate global variable which are not good. Keeping track of them is a nightmare.
Generally my rule is to use instance variables if you can and only have static variables and functions if it really is generic over a class rather than an object
This is quite a good answer to a similar questions
Java: when to use static methods
Rather than just linking to methods consider using the new operation to create a new object and access the method from that in a non static way.
before
public void myMethod(){
Time.setTime(Time.getTime() + 20);
System.out.println(Time.getTime());
}
after
public void myMethod(){
Time t = new Time();
t.setTime(t.getTime() + 20);
System.out.println(t.getTime());
}
Any state that is held in these methods will now be the to instance of time you have created. You could also share the variable t accross other methods if you needed to.
Garbage Collection - static fields live much longer then instance fields.
From a logic point of view, static fields are ONLy suppose to be shared among every single instance - if it is truly your case then no problem of course.
Are you talking about static methods or static properties?
As far as static methods are concerned, there is only one way to abuse them, and that is when you define methods that take an object instance as a parameter. You should never need to do that and in my view doing so is poor coding practice. Here is an example:
static int add(ThisClass a, ThisClass b) {
return a.value + b.value;
}
If you are talking about static variables in the class, you are basically into the subject of "singletons" which is where there is intended to be only one instance of a particular class. Singletons are subject to a lot of abuse. They are used by many class libraries (think JDNI and the logging classes) but if an application makes extensive use of them it can be a sign of a poorly structured program. That is probably what your friend is bitching about.
Instance and Static variable:
Answer to your Question: I would say it is worth to use static variable to save memory allocation.
Memory allocation:
For static variable only one memory location is allocated irespective to no of object created and for Instance variable each object one memory location allocated
Now consider this example, consider you are working on companies internal project where you have to create 1M object to Employee class and some property to the Employee class are eid, ename, ecompany now Important thing is that all employees are working in XYZ company so value to the property ecompany is gonna be "XYZ" irrespective of Employee.
Now you know the situation, value to the property ecompany is gonna be XYZ for 1 Million Object.
Now you decide you want to declare ecomapny property as static or instance considering memory allocation
if you declare it as a static then minimum memory allocated to ecompany will be only 48 bytes which very less compare to memory needed to store 1 Million instance variable. 100000 * 48 bytes = 48 Million bytes.
When you use static objects (except for the case of singleton) you're actually implementing functional programming combined with global variables. If you do that a lot - you should reconsider either your design or using Java (maybe you should use a functional programing language such as list, scheme etc).
Pro Static
Once a static member is called from the inside or the outside of the class, then the static constructor of the class is called. The "static object" will live through the whole session, hence you will win in performance.
Con Static
Static members cannot have states, hence they cannot talk to non-static members of the class.
Example
If we consider the BigInteger class, this class would gain if some of the parts were made into static members.
An instance of the class represent (as expected) a big integer.
However, the main methods add and multiply are not static (which they should be in a better world), which is bad for performance.
Hence, in practice one should not be afraid of mixes between static and non-static.
I don't like using static variables or methods because they have no real inheritance. This makes it more difficult to mock for testing. Using instances gives you the flexibility of full polymorphism. On the other hand, sometimes static variables are necessary, for example with a global cache. Static methods can be a benefit if they provide helper methods for classes/objects/primitives which you cannot access or extend. These helper methods are so simple they don't need inheritance. For example java.util.Arrays class or java.util.Collections.

Difference between a static and a final static variable in Java

Generally, final static members especially, variables (or static final of course, they can be used in either order without overlapping the meaning) are extensively used with interfaces in Java to define a protocol behavior for the implementing class which implies that the class that implements (inherits) an interface must incorporate all of the members of that interface.
I'm unable to differentiate between a final and a final static member. The final static member is the one which is a static member declared as final or something else? In which particular situations should they be used specifically?
A static variable or a final static variable can never be declared inside a method neither inside a static method nor inside an instance method. Why?
The following segment of code accordingly, will not be compiled and an compile-time error will be issued by the compiler, if an attempt is made to compile it.
public static void main(String args[])
{
final int a=0; //ok
int b=1; //ok
static int c=2; //wrong
final static int x=0; //wrong
}
You are making a huge mix of many different concepts. Even the question in the title does not correspond to the question in the body.
Anyways, these are the concepts you are mixing up:
variables
final variables
fields
final fields
static fields
final static fields
The keyword static makes sense only for fields, but in the code you show you are trying to use it inside a function, where you cannot declare fields (fields are members of classes; variables are declared in methods).
Let's try to rapidly describe them.
variables are declared in methods, and used as some kind of mutable local storage (int x; x = 5; x++)
final variables are also declared in methods, and are used as an immutable local storage (final int y; y = 0; y++; // won't compile). They are useful to catch bugs where someone would try to modify something that should not be modified. I personally make most of my local variables and methods parameters final. Also, they are necessary when you reference them from inner, anonymous classes. In some programming languages, the only kind of variable is an immutable variable (in other languages, the "default" kind of variable is the immutable variable) -- as an exercise, try to figure out how to write a loop that would run an specified number of times when you are not allowed to change anything after initialization! (try, for example, to solve fizzbuzz with only final variables!).
fields define the mutable state of objects, and are declared in classes (class x { int myField; }).
final fields define the immutable state of objects, are declared in classes and must be initialized before the constructor finishes (class x { final int myField = 5; }). They cannot be modified. They are very useful when doing multithreading, since they have special properties related to sharing objects among threads (you are guaranteed that every thread will see the correctly initialized value of an object's final fields, if the object is shared after the constructor has finished, and even if it is shared with data races). If you want another exercise, try to solve fizzbuzz again using only final fields, and no other fields, not any variables nor method parameters (obviously, you are allowed to declare parameters in constructors, but thats all!).
static fields are shared among all instances of any class. You can think of them as some kind of global mutable storage (class x { static int globalField = 5; }). The most trivial (and usually useless) example would be to count instances of an object (ie, class x { static int count = 0; x() { count++; } }, here the constructor increments the count each time it is called, ie, each time you create an instance of x with new x()). Beware that, unlike final fields, they are not inherently thread-safe; in other words, you will most certainly get a wrong count of instances of x with the code above if you are instantiating from different threads; to make it correct, you'd have to add some synchronization mechanism or use some specialized class for this purpose, but that is another question (actually, it might be the subject of a whole book).
final static fields are global constants (class MyConstants { public static final double PI = 3.1415926535897932384626433; }).
There are many other subtle characteristics (like: compilers are free to replace references to a final static field to their values directly, which makes reflection useless on such fields; final fields might actually be modified with reflection, but this is very error prone; and so on), but I'd say you have a long way to go before digging in further.
Finally, there are also other keywords that might be used with fields, like transient, volatile and the access levels (public, protected, private). But that is another question (actually, in case you want to ask about them, many other questions, I'd say).
Static members are those which can be accessed without creating an object. This means that those are class members and nothing to do with any instances. and hence can not be defined in the method.
Final in other terms, is a constant (as in C). You can have final variable inside the method as well as at class level. If you put final as static it becomes "a class member which is constant".
I'm unable to differentiate between a final and a final static member.
The final static member is the one which is a static member declared
as final or something else? In which particular situations should they
be used specifically?
Use a final static when you want it to be static. Use a final (non-static) when you don't want it to be static.
A static variable or a final static variable can never be declared
inside a method neither inside a static method nor inside an instance
method. Why?
Design decision. There's just no way to answer that without asking James Gosling.
The following segment of code accordingly, will not be compiled and an
compile-time error will be issued by the compiler, if an attempt is
made to compile it.
Because it violates the rule you just described.
final keyword simply means "this cannot be changed".It can be used with both fields and variables in a method.When a variable is declared final an attempt to change the variable will result to a compile-time error.For example if i declare a variable as final int x = 12; trying to increment x that is (++x) will produce an error.In short with primitives final makes a value a constant.
On the other hand static can only be applied with fields but not in methods.A field that is final static has only one piece of storage.final shows that it is a constant(cannot be changed), static shows it is only one.
In Java, a static variable is one that belongs to class rather than the object of a class, different instances of the same class will contain the same static variable value.
A final variable is one that once after initialized ,after the instantiation of a class (creation of an object) cannot be altered in the program. However this differ from objects if a different value is passed post creation of another object of the same class.
final static means that the variable belongs to the class as well as cannot be change once initialized. So it will be accessible to the same value throughout different instances of the same class.
Just to add a minor information to #Bruno Reis 's answer, which I sought to complete the answer, as he spoke about important condition to initialize final fields before constructor ends, final static fields must also be initialized before before static blocks' execution finishes.
You cannot declare static fields in static block, static fields can only belong to a class, hence the compiler error.

Categories

Resources