The use of static in java - java

I want to know if it is possible to use a static variable inside a non static methode ?
also
can I use a non static variable inside a static methode ?
Thanks

A static variable can be accessed from anywhere you like.
A non static variable can only be accessed from a non static method or from a specific object (instance of a class).
The reason for this can get quite complicated, but in brief:
Anything that is non static in your class is duplicated whenever an object is instantiated from that class. Anything static is common to all instances of the class (and not duplicated for new objects), meaning it is unaffected by changes in the state of individual objects.
Now obviously until an instance of the class has been created, anything non static cant exist - there's no object for them to belong to. Since static members dont require an instance of a class to exist, it wouldnt be safe for them to access members that do require an instance of an object (non static).

Both are possible, but to access an instance (non-static) variable you need an instance.
This can be given implicitly in a non-static context like in an instance method, and must be provided explicitly in a static context.
class StaticOrNot {
static int staticVar = 1;
int instVar = 2;
static void staticMethod() {
staticVar += 1;
StaticOrNot someInstance = new StaticOrNot();
someInstance.instVar += 2;
}
void nonStatic() {
staticVar += 1;
instVar += 2; // using this as instance
}
}

I want to know if it is possible to use a static variable inside a non static methode ?
Yes.
can I use a non static variable inside a static methode ?
No.

Think about what it means to use a non-static variable in a static context. A static method is not executing on any instance - therefore, what would it mean to operate on a member field defined on the class? What instance does that field belong to? None!
The opposite scenario, namely, using a static variable in a non-static context makes perfect sense. You're on an instance, and you want to read some static reference that is defined for all instances of a given class.

I want to know if it is possible to use a static variable inside a non static methode ?
Yes.
can I use a non static variable inside a static methode ?
Only if you have an instance of the class available inside that static method.

Related

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.

the concept of STATIC variables, and methods in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have been searching for clear answers desperately and I think I kinda get it but at the same time I don't quite get the broad concept of that keyword, static.
Here's the scenario I've made:
package oops;
public class Math {
boolean notNumber = false;
static boolean notString = false;
public static void main(String[] args) {
int num1 = 1;
static int num2 = 1; //doesn't work
Math math = new Math();
math.notNumber = true;
notNumber = true; //doesn't work
notString = true;
}
public void whatever() {
notNumber = true;
}
}
Why can't you declare a variable as static inside the static method (or any method)? What does "scope" mean? I know that static variables are not associated with a particular instance of a class, it's more like a "global" variable. But why can't you create a static variable inside the method (num2), but can USE the static variable (notString)?
When you make static variables, do you HAVE TO make them in the class? Not possible in the methods?
Since I declared notNumber as non-static, I know I have to create an object to access that variable. But why does it work in whatever() without any creation of objects, but not in the static method main()?
But why can't you create a static variable inside the method (num2),
but can USE the static variable (notString)?
When you make static variables, do you HAVE TO make them in the class?
Not possible in the methods?
static is scoped to the class context. So declaring a static variable in a method scope makes no sense.
It is like if you declared an instance field in a method.
Declaring a variable and using it are two distinct things that don't obey to the same rules.
As a rule of thumb, you declare a variable with a specific modifier in a place that fits to this modifier. For example :
instance and static fields at the class top level
local variables at the method level
And you use a variable with a specific modifier in any context that is compatible with this modifier :
instance variables in an instance context
static variables both in instance and static contexts.
Since I declared notNumber as non-static, I know I have to create an
object to access that variable. But why does it work in whatever()
without any creation of objects, but not in the static method main()?
This is an instance method :
public void whatever() {
notNumber = true;
}
So it is valid to access to instance members of the class.
While this other is a static method. So it can refer static fields but not instance fields :
public class Math {
boolean notNumber = false; // instance
static boolean notString = false; // static
public static void main(String[] args) {
...
notNumber = true; //doesn't work as refers an instance field
notString = true; // work as refers a static field
}
...
}
Because there is absolutly no need to declare static viriables in methods.static variables are members shared by all instances of this class. Suppose it is allowed to declare it in main method, and you have another static method foo, then how can you access this variable in foo?
You seem to understand that static members don't belong to any instance. They belong to the class itself. They are not really "global" like you have said. You still need to write the class name first when you want to access them from another class. Because static members belongs to the class, the only sensible place for them to exist is at the class-level. You can't declare them in methods because it would make them seem like they belong to methods (as in, their scope is the method body), which they don't. You can use them in methods of the same class without qualifying the class name though, because the method is in scope of the class.
They have to be in the class, as mentioned above.
This is a good question. If you look carefully, whatever is not static either! That means you have to have an instance first, before whatever can be executed. This instance, in whatever, is referred to as "this". Your use of notNumber is short for this.notNumber. You are using the notNumber field of the instance on which whatever is called.
Let us answer it one by one. But before that let us understand what is static variable and what is non-static variable. The static variable is a variable that belongs to a Class and not to any specific instance of the class whereas on the other hand a non static variable belongs to a class instance.
So consider below example
class A{
static Object someStaticValue;
Object someNonStaticValue;
}
A.someStaticValue = new Object(); //allowed
A.someNonStaticValue = new Object() //not allowed as someNonStaticValue belongs to instance of A and will be different for each instance of A
A objectA = new A();
objectA.someNonStaticValue = new Object(); //allowed as this will update someNonStaticValue which is in scope of objectA
objectA.someStaticValue = new Object(); //allowed as it will simply update the value of variable in Class scope.
A objectB = new A();
objectB.someNonStaticValue = new Object(); //allowed
objectB.someStaticValue = new Object(); //allowed as it will simply update the value of variable in Class scope.
objectA.someNonStaticValue is not equal to objectB.someNonStaticValue
as they belong to two different scope
whereas A.someStaticValue, objectA.someStaticValue,
objectB.someStaticValue -> All are equal as they are updating the
variable in class scope.
Now coming to your questions:
Why can't you declare a static variable in a static or non-static method?
Any variable declared inside a method will have scope inside a method and hence can never belong to a class. Every time you will call that method a new instance will be used and hence will be different for each call and hence no purpose of making a variable static inside a method
When you make static variables, do you HAVE TO make them in the class?
Not possible in the methods?
Yes, because creating in methods will solve no purpose and will not be able to keep the definition of static as the values will change in different calls to that method.
Since I declared notNumber as non-static, I know I have to create an
object to access that variable. But why does it work in whatever()
without any creation of objects, but not in the static method main()?
Because in whatever() function, it is sure that you have created a new instance of the class using which you have called this function, calling a non-static variable inside a non-static variable is allowed. Also, in this case, its clear to JVM which instance scope to use for this variable. However, when it comes to static method, there is no guarantee that the instance of the class has been created or not and also of which class instance scope to be used for that non-static variable. Hence, calling non-static variable from a static method is not allowed.
Why can't you declare a variable as static inside the static method (or any method)? What does "scope" mean? I know that static variables are not associated with a particular instance of a class, it's more like a "global" variable. But why can't you create a static variable inside the method (num2), but can USE the static variable (notString)?
ANSWER: You can not declare varibale as static inside a method.
Inside method all variables are local variables that has no existance outside this method thats why they cann't be static.
But why does it work in whatever()?
ANSWER: because
boolean notNumber is declared on class level, and whatsoever method is non static that's why. you cannot reference non static in static
WHY YOU CANNOT REFERENCE NON STATIC IN STATIC?
Why non-static variable cannot be reference from a static context - reg
When you make static variables, do you HAVE TO make them in the class? Not possible in the methods?
ANSWER you cannot make static variables inside static method. SEE FIRST ANSWER

What does ObjectReference.VariableName mean?

I didn't understand this part:
Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.
Can you give an example please ?
Static methods are methods that are called without a reference to an instance of that object. So instance variables cannot be called statically, as each instance will have its own values. So in a static method, you need a specific instance of an object in order to know which value of the instance variable you are trying to use.
The difference is how you access these variables:
class myClass {
public static int staticVar;
public int nonStaticVar;
//Constructor initialises both
}
Static approach:
int otherVariable = MyClass.staticVar;
As you can see, for the static variable you do not need to make an object to access it. Note that you can imagine a static variable to have the trait "once per class", which means, that you can not have 2 versions of staticVar.
Non Static (instance variable):
MyClass instanceOfMyClass = new myClass();
int otherVariable2 = instanceOfMyClass.nonStaticVar;
To have 2 versions of nonStaticVar you can simply make 2 objects and give this variable different values in the 2 objects. Note that in this case you have to make an object.

When to choose variables to declare as final static

I have used final and static variables as well. what i found about these variables is,
final variable
A final variable can only be initialized once, either via an initializer or an assignment statement.
Unlike the value of a constant, the value of a final variable is not necessarily known at compile time.
what variables should i declare as final-
Most often i use those variables whose value is constant universally and can never changed, such as the value of PI.
public static final double PI = 3.141592653589793;
static variables
These are those variables which belongs to the class and not to object(instance).
Static variables are initialized only once , at the start of the execution .
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.
what variables should i declare as final-
Most of the time, i use those variables which i want to initialize only once and use them in the enitre class.
When to use final static variable
Now, i came across a term final static in one of my database project. I found that some of the database objects or even database version were declared as statci final.
static final String DATA_BASE = "BackUpDatabase.db";
static final int DATA_BASE_VERSION = 1;
Now, my question is what variables should we declare as final or static or final static, as using either of them could have solved the issue, then wyh to use both together.
static - Only use when a variable which is used globally
final - Only use when you need to declare a value as constant
static final - Only use when a value is globally used and it is a constant.
: - Here global means across all the instances of a java class
Variables declared as static final (or vice versa) are understood to be meaningful constants, and are named in all upper-case with underscores for spaces.
An example of a commonly encountered constant is Integer.MAX_VALUE, or Math.PI.
final only says that value once initialized can't be changed; static says that the attribute belongs to Class and NOT objects.
So when you say final static; this means there is just one copy of variable and it can't be changed.
- static in java means Class's member. Its shared by all the instances of the class.
- final keyword in java means, constant, but has different interpretation depending on what its being applied.
- When we use static final on a field, consider it as a Global variable.
- PI is static variable of Math Class and its directly accessed using the class name, as Math.PI.
- Use all letters in caps to define a static final variable.
final's interpretation:
final variable : Its value canNot be changed
final method : It canNot be overridden
final class : It canNot be extended
final Parameter : Its value canNot be changed which it receives from caller's argument
final Object Reference Variable : It canNot refer to any other object, other than the one its currently referring to
Declaring variables only as static can lead to change in their values by one or more instances of a class in which it is declared.
Declaring them as static final will help you to create a CONSTANT as #Vulcan told. Only one copy exists which can be accessed anywhere.
Static Variable
You can change the static variable value by calling static method
present in same class .
Static variable value will be same for all object created from this
class . if we change the value then all object of that class will get
new value ,old value will be lost.
Value can be changed multiple times.
Final variable
This variable value can be initialized by two way:
At the time of declaring the variable.
At the time of creating object of that class where class constructor will have this.finalvariable = newfinalvariablevalue;
Once initialized it can't be changed by any method (Static or non-static).
static methods or classes are implicitly final .
Because there is only one copy of this method existing for all the objects which means that subclasses dont have access to modify the copy.
lets say you have a method in the parent and you dont want subclasses to change this method.. just declare the parent method as a final. Here you go.
class Parent {
final void myMethod() {
//No one can change this method from subclassess
//compiler works efficiently because it knows that this method will not change
}
}
class Child extends Parent{
//from this class I can use myMethod but I cannot override.
}

SubClass variables do not get initialized again

I have my main class from which i call my sub class.
My sub class contains some public static variables like
public class SubClass2 extends Main {
public static long a = 0;
public static long b = 0;
public static long c= 0;
public void Analyze(int number)
{
b=2;
//some code
}
}
Where as in main i call the object of the SubClass2.I want everytime when i make the new object of the subclass2 in main then it initializes
all the variables =0 but when i take the print statement of the variable b.It prints out like 4.It adds up the previous value with the new value.
Your fields should not be declared as static in that case. This is why they're not being initialised each time. A static field is initialised once only, then shared by every instance of the class, and depending on accessibility, also outside of the class.
The logic that led to the value 4 must be in the code you've replaced with //some code, but this ins't really relevant here.
If for whatever reason these really should be static fields that are initialised each time an instance is instantiated, then you would have to initialise them manually in the class's constructor. But I'd seriously question the design that leads to this situation...
You are using static variables. These have no connection to any objects you create. They are just global, unique variables. You must erase static. By the way, it is redundant to initialize a field to 0. It is already initialized to zero.
If you use the word static there will only ever be one instance of the variable that is shared between everything created that uses it. Remove static and there will be a new, but more importantly, individual variable for each time its initialised in a method.
Perhaps better wording is that instance methods can and will access shared/static variables!
Your question embodies a contradiction in terms. Static variables are initialized once, when the class is loaded. If you want variables initialized per-instance, use per-instance (non-static) variables.

Categories

Resources