This question already has answers here:
JAVA cannot make a static reference to non-static field
(4 answers)
Closed 7 years ago.
public class Test1
{
final static int ARR_LENGTH = 3;
public static void main(String[] args)
{
int[] arr = new int[ARR_LENGTH];
for(int x=0;x<ARR_LENGTH;x++)
arr[x]=x+1;
for(int element:arr)
System.out.print(element + ", ");
}
}
Why does ARR_LENGTH have to be a static variable when it is declared outside of main?
static means that it's a variable of a class,
this means that static keyword can be used only in a 'class scope' i.e. it doesn't have any sense inside methods.
Q: Why does ARR_LENGTH have to be a static variable when it is declared outside of main?
Answer: Because main() is an static method.
The reason behind this is because static methods and variables can be called before creating an instance of a class (and this is exactly why we define some methods or variables static); Therefore in static methods of a class you can not access non-static members because they are only visible from instances of class not from static methods which could be called before instantiating of same class.
Related
This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
What is the difference between referencing a field by class and calling a field by object?
(5 answers)
Closed 5 years ago.
I know that static variables are part of class and not part of the Object . How can the following lines of code work without any problem
class M
{
static int i=0;
void Inc()
{
System.out.println("Global "+M.i);
System.out.println("Local "+this.i);
}
}
public class StaticTest
{
public static void main(String args[])
{
M m1=new M();
m1.i=99; //How can the m1 object access i variable of the class
m1.Inc();
}
}
The output i get is
Global 99
Local 99
How can the m1 object access i variable of the class?
It is the very same i variable in both cases.
unfortunately, java allows you to access static fields using non-static syntax.
That is all there is to this, nothing else behind this.
Yes, it is allowed for non-static members to access and update static members.
See this for more information here
This question already has answers here:
non static variable name cannot be referenced from a static context [duplicate]
(5 answers)
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 6 years ago.
I am trying to learn java. currently learning about types of variables.
i have written a small program defining instance,local,static variables and trying to print the same from with in the main method. but i am getting error saying "non static variable i cannot be referenced from static context. Below is my program
public class variable{
int i=5;
static int j=10;
public static void main(String[] args){
int k=15;
System.out.println(i);
System.out.println(j);
System.out.println(k);
}
}
Please let me know whats wrong with the program
You need to create a instance of variable and access i
variable v = new variable();
// then access v.i
BTW use Camelcase for you class name.
int i should be static becasue static context cant refer to the non-static variable
Options:
Make a new instance of your class so you can reach i. In fact it is maybe not the best option, because you should make it private, and add a getter method... :)
OR
You could change int i to static int i, because of the static main method.
+1 : it is better to have classnames camescased... :)
The compiler says illegal modifier for parameter i.
Please tell me what I'm doing wrong. Why can't I use a static variable in a Java constructor?
class Student5{
Student5() {
static int i = 0;
System.out.println(i++);
}
public static void main(String args[]){
Student5 c1 = new Student5();
Student5 c2 = new Student5();
Student5 c3 = new Student5();
}
}
Because of where you are declaring i:
Student5(){
static int i=0;
System.out.println(i++);
}
the compiler treats it as a local variable in the constructor:
Local variables cannot be declared as static. For details on what modifiers are allowed for local variables, see Section 14.4 of the Java Language Specification.
Judging from what the code appears to be trying to do, you probably want i to be a static member of Student5, not a local variable in the constructor:
class Student5{
private static int i = 0;
Student5(){
System.out.println(i++);
}
. . .
}
If you want to declare static variable then declare it outside of the constructor, at class level like this -
public class Student5{
private static int i;
}
You declaration of static occurred at your constructor which is a local variable and local variable can not be static. And that's why you are getting - illegal modifier for parameter i. And finally for initializing static variable you may use a static initialization block (though it's not mandatory) -
public class Student5{
private static int i;
static {
i = 5;
}
}
This is how the language was designed.. What if you wanted to have another int field named i in the constructor?, then which i should be considered?. Also, static fields are initialized before the constructor is called i.e, during class initilization phase. A constructor gets called only when a new instance is created.
Imagine what would happen (supposed to happen) if you load and initialize a class but not create a new instance.
Static variables are variables that can be referenced without having an instance of the class. By defining one instead of a constructor, which is called when you create an instance of the class, you are contradicting yourself. Either make it defined without having an instance (outside of the constructor and static) or make it specific to an instance (inside the constructor and not static).
You might want to rethink what you are actually trying to do and if you really need a static variable.
This question already has an answer here:
Are there any guarantees in JLS about order of execution static initialization blocks?
(1 answer)
Closed 8 years ago.
Is there a reason where static final variable will not be instantiated before the static block?
So in the example I provided will print:
someVar value= null
Instead of:
someVar value=SomeValue
I saw this behavior today, In my application,
I am trying to reproduce - unsuccessfully - I do see the value of the static member...
class SomeClass{
static final String someVar ="SomeValue";
static{
System.out.println("someVar value=" + someVar );
}
public static void main(String[] args){
new SomeClass();
}
}
The order of initialization is given in JSL #12.4.2:
For static initialization:
Execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
For construction:
Evaluate the arguments and process that superclass constructor invocation recursively
Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class.
Execute the rest of the body of this constructor.
Note that initializer blocks and variable initializers are considered together, not separately.
I would to say, it depend on your code sequence. Run following code in your local, it will tell you the answer.
public class SomeClass{
static final String someVar ="SomeValue";
static final StaticMember staticMem = new StaticMember(1);
static{
System.out.println("someVar value=" + someVar );
}
static final StaticMember staticMem2 = new StaticMember(2);
public static void main(String[] args){
new SomeClass();
}
}
class StaticMember {
StaticMember(int num) {
System.out.println("StaticMember constructor " + num);
}
}
There is an order the jvm will excecute and instanciate always in this priority:
Static Blocks
Static Members
Instance Blocks
Instance Members
Constructor
If you have inheritance the instanciation order will be a little bit different:
Parent Static Block
Parent Static Members
Child Static Block
Child Static Members
Parent Non-Static Members
Child Non-Static Members
Parent Constructor
Child Constructor
I hope this clarifies a little your issue.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why can’t enum’s constructor access static fields?
enum Test {
e1,e2;
int i=0;
static int j=5;
Test(){
System.out.println(i+" "+j);
}
}
In the above code the constructor can access the instance variable but not the static variable J.
I have read the answer relate to other author all are saying the e1 and e2 initialized before the initialization of J( static field), But according java spec all the static field
initialized when ever the class loaded to memory, that is before running of the constructor.
So before running of Test() constructor the static variable j must be initialized. I'm not able understand the restriction, can any body make me understand.I have already read the answer of the questions Why can't enum's constructor access static fields? But I am not happy with answer like :-The constructor is called before the static fields have all been initialized.
Suppose if take another example with a simple class like enum
class Test{
public static final Test t=new Test();
static int a=5;
Test(){
System.out.println(a);
}
public static void main(String[] args) {
}
}
Here according to there argument the constructor will run before the initialization of static field and it's running also as it's print 0(As JVM did the initilization). But no compilation error or no run time problem. Then why the same thing not happen with enum.
If you imagine how your enum would actually look as a class, it makes sense:
public class Test {
// Imagine you cannot move these two statements:
public static final Test e1 = new Test();
public static final Test e2 = new Test();
int i=0;
static int j=5;
private Test(){
System.out.println(i+ " " + j);
}
static int getJ() {
return j;
}
public static void main(String[] args) {
System.out.println(Test.getJ());
}
}
This prints:
0 0
0 0
5
If you can share a concrete example (rather than a theoretical one), we could suggest how to redesign the code to achieve the desired result, despite the static field limitations.
Problem is, that instances of enum are created during inicialization of static fields. And they created before initialization of your static fields.
They must be in static array values and statically accessible, so it makes sense. And as stated in anser to "Why can't enum's constructor access static fields?", its unfortunate that this happens before all user defined static field inicialization.
But if it was swapped, you could not acces enum instances in static initialization, so it would need allowing static block both before and after creation of enum values.
I don't know whether problem is because inicialization of enum values is concern of Enum class (and handled specialy by JVM (this logic is not in Enum class itself), or because you cannot put static fields before enum values.
WHY it is that way can answer only few people (eg. Josh Bloch and Neal Gafter who are stated as authors of Enum in javadoc, and maybe some unknown others)