why not declare every variables as Static - java

I am new to Java and recently I have studied about static variables. I got to know that for a static variable memory is allocated only once. This means that it will save a lot of memory.My question is that if static variables saves memory, why not declare every variable as static. This will save a lot of memory while creating an application. Pardon me if this seems a silly question, but actually I am just a bit curious.

It's the basics of OOP. Look at an example:
class Person {
public String name = "Foo";
}
Field name is not static, it means that objects of class Person will not share it and each person will have it's own name. And when you change one's person name others will stay unaffected. But if you make it static:
class Person {
public static String name = "Foo";
}
It means, that all persons share the same name which is kind of strange, do you agree?)

The point on creating attributes/variables is that you'll want them as a "feature" for the object. For example, if you have a class "Car", maybe you'll want a variable to reference the color of the car.
The problem is that every instance of "Car" (in real world it'll be each different car) has a value, so each has to be an "independent" variable.
You can use static variables for those ones that are shared by all the objects of this class. For example, a counter to determine how many cars are there. This variable belongs to the class called "Car", but not to any specific instance of that class.

Static variable are created per class level. It is not created when an Object of the class is created. For every instance or object of the class there is only one value of a static member variable. This defeats the purpose of having objects and creating an application around objects.

Yes, it would be allocated memory once in the life cycle and is known as class variable. A class variable can be accessed directly with the class, without the need to create an instance. This would mean that it can be accessed from anywhere and everywhere. Also, memory allocation would mean that even if the variable is not used at many places in the code it would stay in the memory forever as long as the program is running and would take up unnecessary space.

Related

What is the difference between class variables and member variables in Java

There is not much to explain. The title is enough to explain the question. I got this on an interview today.
What are class variables and member variables in Java?
Thank you!
As Zhuinden said they probably meant static variables instead of class variables. For member variables, an instance of the class is needed in order to access the variable. For example if I had a class Foo, and it had a member variable int bar, the only way I could access it is by doing something like
Foo foo = new Foo();
doSomething(foo.bar);
However, if I have bar was a static variable, that means that I can access it even though I don't have an instance of the object. I would access it like this:
doSomething(Foo.bar)
without having to create an instance of Foo.
See here
A member variable is one per object, every object has its own copy of instance variable while a class variable is one per Class, every object of that class shares the same class variable..
A class variable also called as static variable is initialized when the JVM loads the class probably take an example static block if there is no main method in your program while this is not the case with your member variables.
Class variables should be used when you don't want to have copy for each instance while
member variables should be used when you want separate copy for each instance of object.
From point of garbage collection class variables have a long life as class variables are associated with the class and not individual instance.
class variables are cleaned up when the ClassLoader which hold the class unloaded. This is very rare..while in case of member variables they get cleaned up when the instance is cleaned up. Hope this helps.

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.

When will I use a Class Variable in Java v.s an Instance Variable?

Here is a generic class that I have defined, what I would like to know is when I am creating more specific classes for instance a CAR class when would I use a Class Variable? My personal understanding of a class variable is that a single copy of a class variable that has been declared in a class will be declared using the keyword static, and that each object that has been instantiated from the class will contain a single copy of the class variable.
An instance variable allows each instance of a class / object that has been created from the class to have a separate copy of the instance variable per object?
So an instance variable is useful for defining the properties of a class / data-type e.g a House would have a location, but now when would I use a class variable in a House object? or in other words what is the correct use of a class object in designing a class?
public class InstanceVaribale {
public int id; //Instance Variable: each object of this class will have a seperate copy of this variable that will exist during the life cycle of the object.
static int count = 0; //Class Variable: each object of this class will contain a single copy of this variable which has the same value unless mutated during the lifecycle of the objects.
InstanceVaribale() {
count++;
}
public static void main(String[] args) {
InstanceVaribale A = new InstanceVaribale();
System.out.println(A.count);
InstanceVaribale B = new InstanceVaribale();
System.out.println(B.count);
System.out.println(A.id);
System.out.println(A.count);
System.out.println(B.id);
System.out.println(B.count);
InstanceVaribale C = new InstanceVaribale();
System.out.println(C.count);
}
}
My personal understanding of a class variable is that a single copy of a class variable that has been declared in a class will be declared using the keyword static, and that each object that has been instantiated from the class will contain a single copy of the class variable.
No. It's not that "each object will contain a single copy". A static variable is associated with the type rather than each instance of the type. The instances don't have the variable at all.
There's exactly one variable (assuming you're only loading it from one classloader) however many instances of the type there are. No instances? Still one variable. A million instances? Still one variable.
Static variables are mostly useful for constants or constant-alikes - things like loggers, or "the set of valid prices" etc. Things which don't change over the course of the application. They should almost always be final in my experience, and the type should be an immutable type (like String). Where possible, use immutable collections too for static variables - or make sure the variable is private and that you never mutate the collection within the class.
You should avoid using static variables to store global changing state. It makes code much harder to test and reason about.
Static variables are used to store values that are shared between all instances of the class.
If this is not the case, it should be an instance variable.
1. Every object of the class will have its own copy of Instance Variable,its One per Object.
2. But static variable will be shared by all the objects of the class, its One per Class.
3. Now i will give 2 example where these two will have importance.
Instance variable:
Consider a Gaming Program, then each player will have different Name, Scores, Weapons-power, Stage reached, etc.....
Static variable:
Consider a Banking program, where each client will be given an Id, which is greater and unique than the previous one, so static variable will be apt for this.

Java: Memory usage of the final keyword?

When you declare a final variable (constant) in a class, for example:
private static final int MyVar = 255;
How much memory will this require if I have 100,000 instances of the class which declared this?
Will it link the variable to the class and thus have 1*MyVar memory usage (disregarding internal pointers), or will it link to the instance of this variable and create 100,000*MyVar copies of this variable?
Unbelievably fast response! The consensus seems to be that if a variable is both static and final then it will require 1*MyVar. Thanks all!
The final keyword is irrelevant to the amount of memory used, since it only means that you can't change the value of the variable.
However, since the variable is declared static, there will be only one such variable that belongs to the class and not to a specific instance.
Taken from here:
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized . A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
There will be only 1*MyVar memory usage because it is declared as static.
The static declaration means it will only have one instance for that class and it's subclasses (unless they override MyVar).
An int is a 32-bit signed 2's complement integer primitive, so it takes 4 bytes to hold it, if your example wasn't using static you'd just multiply that by the number of instances you have (for your example of 100,000 instances that's 0.38 of a megabyte - for the field alone, extra overhead for actual classes).
The final modifier on a field means it cannot be repointed to another value (whereas final on a class of method means it cannot be overridden).
It's static and thus class scope -> 1.
Edit: actually, it depends on the class loaders. In the general case you have one copy of the class but if you have multiple class loaders/class repositories (might be the case in application servers etc.) you could end up with more.
In addition to the fact that static fields belong to their classes, and thus there is only one instance of static varaible per class (and per classloader), it's important to understand that static final variables initialized by compile-time constant expressions are inlined into classes that use them.
JLS §13.1 The Form of a Binary:
References to fields that are constant variables (§4.12.4) are resolved at compile time to the constant value that is denoted. No reference to such a constant field should be present in the code in a binary file (except in the class or interface containing the constant field, which will have code to initialize it), and such constant fields must always appear to have been initialized; the default initial value for the type of such a field must never be observed.
So, in practice, the instance of static final variable that belong to its class is not the only instance of value of that variable - there are other instances of that value inlined into constant pools (or code) of classes that use the variable in question.
class Foo {
public static final String S = "Hello, world!";
}
class Bar {
public static void main(String[] args) {
// No real access to class Foo here
// String "Hello, world!" is inlined into the constant pool of class Bar
String s = Foo.S;
System.out.println(s);
}
}
In practice it means that if you change the value of Foo.S in class Foo, but don't recompile class Bar, class Bar will print the old value of Foo.S.
static means you will have only one instatnce
final just means, that you can't reassign that value.
The crucial part here is that you declared the variable as static because static variables are shared among all instances of the class, thus requiring only as much space as one instance of the variable. Declaring a variable final makes it immutable outside its declaration or constructor.
final makes is 1*instances memory usage.
However, static makes it simply 1.
The keyword "final" helps you to declare a constant with a specific amount of memory, where as the keyword "static" as its prefix will gives a single instance of this constant, what ever be the amount of memory consumed...!!!
Static means, one instance per class, static variable created once and can be shared between different object.
Final variable, once value is initialized it can't be changed. Final static variable use to create constant (Immutable) and refer directly without using the object.
It's static, so there will be only one instance created, so however many bytes are required to hold one int primitive will be allocated
You will have one instance per class. If you have the class loaded more than once (in different class loaders) it will be loaded once per class loader which loads it.
BTW: Memory is surprising cheap these days. Even if there was a copy per instance, the time it takes you to ask the question is worth more than the memory you save. You should make it static final for clarity rather than performance. Clearer code is easier to maintain and is often more efficient as well.

What is the difference between a static variable and a dynamic variable in java/oops?

please someone tell me the difference between a 'static variable' and a 'normal variable' in oops or in java. Also their usage if possible.
Consider a class having static and dynamic variables.
Dynamic variables : When instance of the class is created, each object has its own copy of dynamic variables. Values of this variables will be different for each object, whatever the value is assigned to it in that object.
Static variable : These are class level variables. The value of these variables will be shared among all the objects of the class. When one of the object changes its value that will be the latest value available for other objects. That means these are the shared variables.
A static variable is usually one associated with a type. Compare this with an instance variable, which is associated with a particular instance of a type, or a local variable, which is associated with one particular call to a method.
I don't know of any standard definition of "dynamic variable" - where have you come across this terminology?
Static variables are those which are at the class or type level. And there will be only one copy of it is available to the all instances of that class type.
And there is no concept of dynamic variables as for as i know. If you came across about this concept at some particular context then mention that, might be helpful to explain you.
EDITED : to answer your question of difference between 'static int' and 'int'.
Say suppose you have a class as
public class StaticInfo{
private static int count;
private int variable;
//.. say setter and getters for variable
//.. static setter and getters for count;
}
So if you create 2 objects of the type StaticInfo then these two will have two different 'variable' member but one common count member which is a class member.
hope it is clear now.
Static variable is instantiated once in life time of the Type.
For a class Age if you have a static variable
static int staticAge;
and another variable as instance variable int instanceAge;
the value assigned to staticAge will be same for all the instance of Age because same variable will shared between all the objects.
the value to instanceAge will be specific to the object of Age.
In java static variable is created by the using of 'static' keyword in front of variable datatype.
static int count
If you are going for concept of static variable then a static variable is not created per object instead of this, it created only one copy for class . here find the example of code in java
class Company{
static String companyName;
String branch;
}
class Car{
static String carName;
String model;
}
public class Server{
public static void main(String ar[]){
Company company1 = new Company();
Company company2 = new Company();
Company company3 = new Company();
Car car1 = new Car();
Car car2 = new Car();
Car car3 = new Car();
}
}
In the above program 'Company' and 'Car' class have 3-3 objects but for static variable only one copy will be create and none static variable have 3 separate memory allocation So in 'Company' class companyName variable will create only once where branch variable will create 3 times for each object same thing applies on Car class.
In short static variables memory is shared among all objects of class and can be modified.
Dynamic variable means you want to create variable of class dynamic which is not possible instead of this you can initialize variable on dynamic using java reflection.
All variables are dynamic unless you make them final. Static is just another beast altogether.
That question doesn't make much sense. Java doesn't have dynamic variables. CommonLisp has them, for example, but Java doesn't.
Static variables (should) remain the same e.g. temperature of a water bath, k constant of a particular spring. Dynamic variables change as the experiment progresses e.g. air temperature and pressure, amount of natural light.

Categories

Resources