class SomeClass{
final static int temp;
//temp=30;
SomeClass(int a){
System.out.println("here");
temp=a;
}
}
public class HelloWorld{
public static void main(String args[]){
SomeClass t1 = new SomeClass(10);
SomeClass t2 = new SomeClass(20);
System.out.println("t1:"+t1.temp);
System.out.println("t2:"+t2.temp);
}
}
When I create object t2 of SomeClass I can't assign value 20 to it. What could be the reason here? I cannot understand the final static int type.
You have to understand the two modifiers of the temp variable:
static means makes this a class variable so when you make the assignment in the object constructor, this is not a member of the object, but of the class. On the creation of t2 you make a second assignment to the one and only class variable (not a member variable of the object).
final means that the variable can be assigned a value only once, and therefore the assignment in the construction of t2 fails.
Do you intend for temp to be a member field of the object? Then remove static.
If you intend for temp to be a class variable that is reassigned? Then remove final.
static means belonging at class level. And, final means you only can instantiate it once. So, when you use final static, you are instantiating it once when you create t1. Then, that cannot be reinitialized. See this article.
If you want to have a variable that cannot be changed at object level, remove static.
when you define a variable final static, it means that you define it as a CONSTANT. Only one copy of variable exists which can’t be reinitialize.
Related
I'm learning Java and write the simple code below:
public class Test {
private int a = b;
private final static int b = 10;
public int getA() {
return a;
}
}
public class Hello {
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.getA());
}
}
The result: 10. Well done! It run successfully and have no error.
Can anyone please explain why I can assign a static variable before declaring it?
The assignment
private int a = b;
takes place when you create a new instance of Test (just before the constructor is called).
The declaration and initialization of the static variable b, takes place before the instance is created, when the class is loaded.
The order of the statements doesn't matter, since static variables are always initialized first.
Javavariables are initialised this order:
Static variables of the superclasses if any
static variables of the current class.
Static variables, and static blocks in the order that they are
declared
Instance variables of the superclasses
All instance variables of the current class.
Instance variables, and instance level initialisation blocks, in
declaration order
Therefore "b" is intialized before the "a".
Hope this helps.
Static variables are bound to a class - which of course always exists before instances of the class. Thus, you can freely assign it to instance fields.
The order of declaring variables doesn't really matter in your code as in reality the static variable is going to be initialized before non-static ones.
The code you wrote works well because
private final static int b = 10;
is a class variable (static field). Those type of variables are initialised for first.
Then is executed the line
private int a = b;
which initialise the instance variable (field) a.
In short, it doesn't matter the order in which those variables are declared in your code. Class variables are always declared before instance variables.
What is the difference between a static and instance variable. The following sentence is what I cant get:
In certain cases, only one copy of a particular variable should be shared by all objects of a class- here a static variable is used.
A static variable represents class wide info.All objects of a class share the same data.
I thought that instance vars were used class wide whereas static variables only had scope within their own methods?
In the context of class attributes, static has a different meaning. If you have a field like:
private static int sharedAttribute;
then, each and every instance of the class will share the same variable, so that if you change it in one instance, the change will reflect in all instances, created either before or after the change.
Thus said, you might understand that this is bad in many cases, because it can easiy turn into an undesired side-effect: changing object a also affects b and you might end up wondering why b changed with no apparent reasons. Anyway, there are cases where this behaviour is absolutely desirable:
class constants: since they are const, having all the classes access the same value will do no harm, because no one can change that. They can save memory too, if you have a lot of instances of that class. Not sure about concurrent access, though.
variables that are intended to be shared, such as reference counters &co.
static vars are instantiated before your program starts, so if you have too many of them, you could slow down startup.
A static method can only access static attributes, but think twice before trying this.
Rule of thumb: don't use static, unless it is necessary and you know what you are doing or you are declaring a class constant.
Say there is a test class:
class Test{
public static int a = 5;
public int b = 10;
}
// here t1 and t2 will have a separate copy of b
// while they will have same copy of a.
Test t1 = new test();
Test t2 = new test();
You can access a static variable with it's class Name like this
Test.a = 1//some value But you can not access instance variable like this
System.out.println(t1.a);
System.out.println(t2.a);
In both cases output will be 1 as a is share by all instances of the test class.
while the instance variable will each have separate copy of b (instance variable)
So
t1.b = 15 // will not be reflected in t2.
System.out.println(t1.b); // this will print 15
System.out.println(t2.b); / this will still print 10;
Hope that explains your query.
Suppose we create a static variable K and in the main function we create three objects:
ob1
ob2
ob3;
All these objects can have the same value for variable K. In contrast if the variable K was an instance variable then it could have different values as:
ob1.k
ob2.k
ob3.k
I think you are thinking about the C/C++ definition of the static keyword. There, the static keyword has many uses. In Java, the static keyword's functionality is described in your post. Anyhow, you can try it for yourself:
public class Test_Static{
static int x;
public static void main(String[] argv){
Test_Static a = new Test_Static();
Test_Static b = new Test_Static();
a.x = 1; // This will give an error, but still compile.
b.x = 2;
System.out.println(a.x); // Should print 2
}
}
and similarly for non static variables:
public class Test_NonStatic{
int x;
public static void main(String [] argv){
Test_NonStatic a = new Test_NonStatic();
Test_NonStatic b = new Test_NonStatic();
a.x = 1;
b.x = 2;
System.out.println(a.x); // Should print 1.
}
}
Consider a class MyClass, having one static and one non-static member:
public class MyClass {
public static int STATICVARIABLE = 0;
public int nonStaticVariable = 0;
}
Now, let's create a main() to create a couple of instances:
public class AnotherClass{
public static void main(String[] args) {
// Create two instances of MyClass
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.nonStaticVariable = 30; // Setting value for nonstatic varibale
obj1.STATICVARIABLE = 40; //Setting value for static variable
obj2.nonStaticVariable = 50;
obj2.STATICVARIABLE = 60;
// Print the values actually set for static and non-static variables.
System.out.println(obj1.STATICVARIABLE);
System.out.println(obj1.nonStaticVariable);
System.out.println(obj2.STATICVARIABLE);
System.out.println(obj2.nonStaticVariable);
}
}
Result:
60
30
60
50
Now you can see value of the static variable printed 60 both the times, as both obj1 and obj2 were referring to the same variable. With the non-static variable, the outputs differ, as each object when created keeps its own copy of non-static variable; changes made to them do not impact on the other copy of the variable created by another object.
Instance Variables
Any variable that is defined in class body and outside bodies of
methods; and it should not be declared static, abstract, stricftp,
synchronized, and native modifier.
An instance variable cannot live without its object, and it is a part of
the object.
Every object has their own copies of instance variables.
Static Variables (class variables)
Use static modifier
Belong to the class (not to an object of the class)
One copy of a static variable
Initialize only once at the start of the execution.
Enjoy the program’s lifetime
I'm always confused between static and final keywords in java.
How are they different ?
The static keyword can be used in 4 scenarios
static variables
static methods
static blocks of code
static nested class
Let's look at static variables and static methods first.
Static variable
It is a variable which belongs to the class and not to object (instance).
Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
A single copy to be shared by all instances of the class.
A static variable can be accessed directly by the class name and doesn’t need any object.
Syntax: Class.variable
Static method
It is a method which belongs to the class and not to the object (instance).
A static method can access only static data. It can not access non-static data (instance variables) unless it has/creates an instance of the class.
A static method can call only other static methods and can not call a non-static method from it unless it has/creates an instance of the class.
A static method can be accessed directly by the class name and doesn’t need any object.
Syntax: Class.methodName()
A static method cannot refer to this or super keywords in anyway.
Static class
Java also has "static nested classes". A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class.
Static nested classes can have instance methods and static methods.
There's no such thing as a top-level static class in Java.
Side note:
main method is static since it must be be accessible for an application to run before any instantiation takes place.
final keyword is used in several different contexts to define an entity which cannot later be changed.
A final class cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes are final, for example java.lang.System and java.lang.String. All methods in a final class are implicitly final.
A final method can't be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.
A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a blank final variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases.
Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.
When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the final variable cannot change.
static means it belongs to the class not an instance, this means that there is only one copy of that variable/method shared between all instances of a particular Class.
public class MyClass {
public static int myVariable = 0;
}
//Now in some other code creating two instances of MyClass
//and altering the variable will affect all instances
MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();
MyClass.myVariable = 5; //This change is reflected in both instances
final is entirely unrelated, it is a way of defining a once only initialization. You can either initialize when defining the variable or within the constructor, nowhere else.
note A note on final methods and final classes, this is a way of explicitly stating that the method or class can not be overridden / extended respectively.
Extra Reading
So on the topic of static, we were talking about the other uses it may have, it is sometimes used in static blocks. When using static variables it is sometimes necessary to set these variables up before using the class, but unfortunately you do not get a constructor. This is where the static keyword comes in.
public class MyClass {
public static List<String> cars = new ArrayList<String>();
static {
cars.add("Ferrari");
cars.add("Scoda");
}
}
public class TestClass {
public static void main(String args[]) {
System.out.println(MyClass.cars.get(0)); //This will print Ferrari
}
}
You must not get this confused with instance initializer blocks which are called before the constructor per instance.
The two really aren't similar. static fields are fields that do not belong to any particular instance of a class.
class C {
public static int n = 42;
}
Here, the static field n isn't associated with any particular instance of C but with the entire class in general (which is why C.n can be used to access it). Can you still use an instance of C to access n? Yes - but it isn't considered particularly good practice.
final on the other hand indicates that a particular variable cannot change after it is initialized.
class C {
public final int n = 42;
}
Here, n cannot be re-assigned because it is final. One other difference is that any variable can be declared final, while not every variable can be declared static.
Also, classes can be declared final which indicates that they cannot be extended:
final class C {}
class B extends C {} // error!
Similarly, methods can be declared final to indicate that they cannot be overriden by an extending class:
class C {
public final void foo() {}
}
class B extends C {
public void foo() {} // error!
}
static means there is only one copy of the variable in memory shared by all instances of the class.
The final keyword just means the value can't be changed. Without final, any object can change the value of the variable.
final -
1)When we apply "final" keyword to a variable,the value of that variable remains constant.
(or)
Once we declare a variable as final.the value of that variable cannot be changed.
2)It is useful when a variable value does not change during the life time of a program
static -
1)when we apply "static" keyword to a variable ,it means it belongs to class.
2)When we apply "static" keyword to a method,it means the method can be accessed without creating any instance of the class
Think of an object like a Speaker. If Speaker is a class, It will have different variables such as volume, treble, bass, color etc. You define all these fields while defining the Speaker class. For example, you declared the color field with a static modifier, that means you're telling the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.
Declaring
static final String color = "Black";
will make sure that whenever this class is instantiated, the value of color field will be "Black" unless it is not changed.
public class Speaker {
static String color = "Black";
}
public class Sample {
public static void main(String args[]) {
System.out.println(Speaker.color); //will provide output as "Black"
Speaker.color = "white";
System.out.println(Speaker.color); //will provide output as "White"
}}
Note : Now once you change the color of the speaker as final this code wont execute, because final keyword makes sure that the value of the field never changes.
public class Speaker {
static final String color = "Black";
}
public class Sample {
public static void main(String args[]) {
System.out.println(Speaker.color); //should provide output as "Black"
Speaker.color = "white"; //Error because the value of color is fixed.
System.out.println(Speaker.color); //Code won't execute.
}}
You may copy/paste this code directly into your emulator and try.
Easy Difference,
Final : means that the Value of the variable is Final and it will not change anywhere. If you say that final x = 5 it means x can not be changed its value is final for everyone.
Static : means that it has only one object. lets suppose you have x = 5, in memory there is x = 5 and its present inside a class. if you create an object or instance of the class which means there a specific box that represents that class and its variables and methods. and if you create an other object or instance of that class it means there are two boxes of that same class which has different x inside them in the memory. and if you call both x in different positions and change their value then their value will be different. box 1 has x which has x =5 and box 2 has x = 6. but if you make the x static it means it can not be created again.
you can create object of class but that object will not have different x in them.
if x is static then box 1 and box 2 both will have the same x which has the value of 5. Yes i can change the value of static any where as its not final. so if i say box 1 has x and i change its value to x =5 and after that i make another box which is box2 and i change the value of box2 x to x=6. then as X is static both boxes has the same x. and both boxes will give the value of box as 6 because box2 overwrites the value of 5 to 6.
Both final and static are totally different. Final which is final can not be changed. static which will remain as one but can be changed.
"This is an example. remember static variable are always called by their class name. because they are only one for all of the objects of that class. so
Class A has x =5, i can call and change it by A.x=6; "
Static and final have some big differences:
Static variables or classes will always be available from (pretty much) anywhere. Final is just a keyword that means a variable cannot be changed. So if had:
public class Test{
public final int first = 10;
public static int second = 20;
public Test(){
second = second + 1
first = first + 1;
}
}
The program would run until it tried to change the "first" integer, which would cause an error. Outside of this class, you would only have access to the "first" variable if you had instantiated the class. This is in contrast to "second", which is available all the time.
Static is something that any object in a class can call, that inherently belongs to an object type.
A variable can be final for an entire class, and that simply means it cannot be changed anymore. It can only be set once, and trying to set it again will result in an error being thrown. It is useful for a number of reasons, perhaps you want to declare a constant, that can't be changed.
Some example code:
class someClass
{
public static int count=0;
public final String mName;
someClass(String name)
{
mname=name;
count=count+1;
}
public static void main(String args[])
{
someClass obj1=new someClass("obj1");
System.out.println("count="+count+" name="+obj1.mName);
someClass obj2=new someClass("obj2");
System.out.println("count="+count+" name="+obj2.mName);
}
}
Wikipedia contains the complete list of java keywords.
I won't try to give a complete answer here. My recommendation would be to focus on understanding what each one of them does and then it should be cleare to see that their effects are completely different and why sometimes they are used together.
static is for members of a class (attributes and methods) and it has to be understood in contrast to instance (non static) members. I'd recommend reading "Understanding Instance and Class Members" in The Java Tutorials. I can also be used in static blocks but I would not worry about it for a start.
final has different meanings according if its applied to variables, methods, classes or some other cases. Here I like Wikipedia explanations better.
Static variable values can get changed although one copy of the variable traverse through the application, whereas Final Variable values can be initialized once and cannot be changed throughout the application.
what i basicly want is this:
public class Test
{
private static final Integer a;
public Test(Integer a)
{
this.a = a;
}
}
This obviously doesn't work, cause the 2nd created instance would try to override the final variable.
So is there a way to give all the instances the same immutable value via the constructor?
Static final values should be initialized in a static context, not by instances.
One options is to set the value in the declaration:
private static final Integer a=FileConfig.getInstance().getA();
Each class can have a static {} block where code is called to initialize the static parts of the class.
static {
a = FileConfig.getInstance().getA();
}
Finally, you can set the value from a static method
private static int getA() {
return FileConfig.getInstance().getA();
}
private static final Integer a=getA();
In closure, static instance initialization does not belong in instance constructors.
If the configuration values change sometimes, there is simply no reason to store the value a in a static final variable. If you want to create each instance with the constant a in the constructor, what is the purpose of a static field in the first place? Somehow, when you call the constructor for the first time, you are passing in a value from somewhere. If the value deserves to be static and final, you can acquire it from within the static initializer. If the configuration is not a singleton, but every instance always produces the same value of a, you could easily do a = new FileConfig().getA();.
Other than that, you could make the value non-final, and rest assured that since you always put in the same value of a, the static variable will not change.
Still, you could make a a final instance variable of the class, set in the constructor.
So is there a way to give all the instances the same immutable value via the constructor?
I assume you want a value to be assigned to a the first time an object of type Test is created but not when any subsequent instance is created. In that case you cannot declare it final. a will be null initially, the constructor has to check if it is null and assign it a value in that case.
But I urge you to look at the design, especially why the caller have to provide the value. Isn't it counter-intuitive that after the second Test object is created Test.a does not change in the following case?
// assume this is the first `Test` object created:
Test t = new Test(5); // Test.a is 5
Test t = new Test(6); // Test.a is *still* 5
This might be a dumb question but I had this question hover around me. Is there any difference between class variables and member variables in java or they both one and the same.
class Example {
protected String str;
public static String str1 = "xyz";
}
I know that str1 is a class variable, is str also a class variable?
Yes, the difference is, there is only one per class when we talk about class attributes and there is one per object when we talk about instance attribute.
In your code protected String str declares an instance attribute ( or member variable as you call it ) and public static String str1 = "xyz" declares a class attribute.
There is a big difference.
Member variables are tied to an instance object of the class. So the variable's value can be different for different instance objects.
The static variable is one for the whole class - you don't need to instantiate an object to access it.
class A {
public int memberVar;
public static int staticVar;
}
void Test() {
A obj = new A();
int var = obj.memberVar;
//var = A.memberVar -- wrong!
//vs
var = A.staticVar;
}
They are not the same, and str isn't a class variable - the "static" indicates a class variable.
The fundamental difference is that class (static) variables can be thought of as shared between all instance of the class, whereas there is an independent copy of each member (instance) variable for each instance of the class.
str is not a class variable. str is an instance variable.
Class variable
a class variable is a variable defined
in a class (i.e. a member variable) of
which a single copy exists, regardless
of how many instances of the class
exist
Instance variable
a variable defined in a class (i.e. a
member variable), for which each
object of the class has a separate
copy
By these definitions, str1 is a class variable, and str is not.
There is a difference. str1 is a class variable that has 1 value for all instances of the class. The str variable is an instance variable, and each instance of Example (aka, new Example()) can have a different value of str, but all instances of Example will share the same value of str1.
If you try to implement a counter inside your class that counts how many instances have been created, you will see immediately why class variables can do the work, while instance variables can not.
public class MyClass {
private static int count;
public MyClass() {
count++;
...
}
public static int getCount() {
return count;
}
...
}
You can call MyClass.getCount(); even before having created a single MyClass instance.
str1 is a class variable as static is the modifier to it. static means variable belongs to a class not to the instance.
str variable does not have static modifier which makes it member or instance variable.
each instance of a class will have its own copy of member variable