Why can't i use static variable in java constructor? - java

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.

Related

Consider the code given below, Is there any way to acces the variable "iry" from the innerClassMethod() if the variable name "iry" is changed to "i"? [duplicate]

i'm new in java and i confused for below example
public class Test {
int testOne(){ //member method
int x=5;
class inTest // local class in member method
{
void inTestOne(int x){
System.out.print("x is "+x);
// System.out.print("this.x is "+this.x);
}
}
inTest ins=new inTest(); // create an instance of inTest local class (inner class)
ins.inTestOne(10);
return 0;
}
public static void main(String[] args) {
Test obj = new Test();
obj.testOne();
}
}
why i can't access to shadowed variable in inTestOne() method with "this" keyword in line 8
why i can't access to shadowed variable in inTestOne() method with "this" keyword in line 8
Because x is not a member variable of the class; it is a local variable. The keyword this can be used to access a member fields of the class, not local variables.
Once a variable is shadowed, you have no access to it. This is OK, because both the variable and the local inner class are yours to change; if you want to access the shadowed variable, all you need to do is renaming it (or renaming the variable that shadows it, whatever makes more sense to you).
Note: don't forget to mark the local variable final, otherwise you wouldn't be able to access it even when it is not shadowed.
this. is used to access members - a local variable is not a member, so it cannot be accessed this way when it's shadowed.

Can i initialize static variable after the initialization?

What is the problem with below code?
class test {
static int a;
a=10;
}
If I'm writing like this (as above), I'm getting a compile time error.
class test {
static int a=10;
a=4;
}
For the second one, I'm not getting any error.
Neither of your examples should compile.
a=10;
is a statement, which is not valid directly inside a class declaration. You can only put the following directly inside a class:
Member declarations (member/static variable declarations (like static int a;), methods, nested classes and interfaces);
Static and instance initializers;
Constructors.
You need to put a statement inside a block, for example a static initializer:
static int a;
static {
a = 10;
}
which is equivalent to:
static int a = 10;
You need to use a static block of statement to do an assignment on an other line (outside a method)
class test {
static int a;
static { a=10; }
}
a=4; must be done in a valid scope
either a method or a constructor...
this line is valid instead
static int a=10;
because java allows youto declare and initialize in one statement!
If you want to initialize a after defining it as a null int, you can only do that in a function, because it is static.
must be initialized inside static block or init block or in constructor.
you can only initialized your member variable after declaration inside a function or block because it is static you should use static block
What you are currently doing is declaring a variable in a class decleration, which is not valid. Looking at this neither of your examples should give you any good result.
In a class declaration you can however initialize a variable:
static int a;
Then if you want to work with it you would have to create a method first (if you are not aware of this I would strongly advise to watch some youtube tutorials or read books about this topic) :
public void foo(int a){
a = 6; //Here you can play with your variables and change them
}
In class declararions you can: declarations methods, initializers and constructors. (there is a bit more you can do, however I would have a look at these points before diving in too deep).
Furthermore it seems that you are not aware what a static variable or a static method does, I think the following posts will help you with that:
difference between 'static int' and 'int' in java
What are static method and variables?
I hope I could help and have fun learning Java
Because for static memory allocated at the time of class loading
so we need do like this
class test {static int a =10;
public static void main(String args[]) { a=12 output(test.a (or) a);}}
A Java class body is should contain declarations and declaration with an initializer, not the standalone statements. Let's unwrap your requirement of initializing a static variable.
Static variables should not be initialized inside methods as these variables belong to the class. But they can be initiated inside the constructor.
public class Example {
static String name;
static int age;
Example() {
name = "James";
age = 34;
}
public static void main(String args[]) {
new Example();
System.out.println(Example.name);
System.out.println(Example.age);
}
}
Now the output will be :
James
34
If new Example(); is not called then the output will be :
null
0
This is because the static variables are initialized with an object creation and for each Example object name and age will be overwritten with the same value. But at least one object needs to be created for name and age to be initialized.
But if you declare a static and final instance variable, we cannot initialize that in the constructor, it is mandatory to initialize static and final variables at the class level. We can initialize while declaring the variable or using a static initialization block. This runs before the main() method in Java. Hence when the main() method is loaded this static variable will be initialized and the compiler will not throw any errors.
static final int name = "STRING";
static final int age;
static {
age = 10;
}
Putting all these things together,
A static variable can be initialized,
When declaring.
Inside a constructor.
Inside a static block.
A static final variable can be initialized,
When declaring.
Inside a static block.
A final variable can be initialized,
When declaring.
Inside a constructor (If you have more than one constructor in your class then it must be initialized in all of them).

Can a Variable be initialized inside a Class in Java? What about Static Variable? If yes, then what's the use for Static Block?

In C++(prior to C-11), we needed to initialize the variables outside the Class either through constructors or some methods. What's happens in Java?
Can a Variable be initialized inside a Class in Java?
Yes, like this:
public class MyClass {
private int myVariable = 10;
}
What about Static Variable? If yes, then what's the use for Static Block?
Yes, static variables can be initialized in the class as well:
public class MyClass {
private static int myVariable = 10;
}
Static blocks are used when you want to initialize a static variable, but one line is insufficient. For example:
public class MyClass {
private static HashMap<Integer, Integer> myMap;
static {
myMap = new HashMap<>();
myMap.put(10, 20);
myMap.put(20, 40);
}
}
c++ v/s Java:
Common- both OOP language
difference- c++ is not purely object oriented language, but Java is purely oop language.
Classes are blueprint(like a general map) which defines some attributes/properties(Member variables) and behavior(member functions) of a object of that class.
Class is just a imagination before creation of a object.
Object is real time entity that has physical existence in real world or in simply it's a implementation of class.
Classes in java:
class class_name
{
member variables;
member functions;
};
Ex.
class A
{
int a;
void funct()
{
//body
}
}; //defination is closed with semicolon
but,
classes in java:
ANSWER to ur quesion:
class class_name
{
member variables; //still we define the attributes in class that may be static or non-static
member functions;
};
Significance of static variable:
static variable is alloacated the common memory in ram for all the objects of that class and operation perform by any object on static member is reflected to all other object's static member because of common(same) memory.
significance of static method(functions are called methods in java): static method of a class is a method which is called without creating the object of that class.
In java, main() method is declared as static because after execution of program main() method is called without creating the object of class.
kernal of OS calls the main() method.
Can a Variable be initialized inside a Class in Java?
Yes.
class TestClass {
int abc = 0;
static int def = 1;
}
What about Static Variable?
Yes, you can. Same Example as above.
But this won't be initialized every time an object of the class is created.
TestClass ob1 = new TestClass();
ob1.def = 2; // Always use the class name to access static variables. This is just an example.
TestClass ob2 = new TestClass();
System.out.println(ob2.def); // Output : 2
PS : Always use the class name to access static variables. This is just an example.
What's the use for Static Block?
If the initialization of static variables is complex, then you can create a static block and initialize those variables there. Here is a good reference for the same.
class TestClass {
int abc = 0;
static int def = 1;
static {
int x = 100;
int y = 20;
def = x - y + 10;
}
}
If you wat to initialize the variable you can create something like
public class Animal
{
int age = 21;
static int roll = 23;
}
But remember the difference between instance variables and static variables,
int age - this variable is created for each object you create
static int roll - this variable is created only once and is one for every other object.

About declaring and initializing primitive variable in different line outside a method

new to the community, and new to the whole programming world.
While I was studying java, I stumbled on a simple question.
In a main method (or any method), I can declare and initialize a primitive variable on different line just fine. Say,
public static void main (Strin[]args){
int age;
age = 42;
}
will complile just fine.
But if I tried this outside a method, as a class variable or instance variable,
public class test {
int age;
age = 42;
}
the code won't compile. It will only work if the variable is declared and initialized in one line. I was wondering why java doesn't allow this outside a method.
A class body can contain variable declarations and method declarations, but no single statements. When would you expect such a statement to be executed? So your initialization has to be either inline with the declaration (as a shortcut) or in some method, e.g. in the constructor, if you want to initialize the variable when creating a new object.
It is a syntax error! Your code does not comply with the Java syntactic and semantics rules as described in Java Language Specification.
You have to initialise it's value inside the constructor (that's the whole point of a constructor), like
public test() {
age = 42;
}
For static variables it's possible to give them a value:
static int age = 42;
Or use a static block:
static {
age = 43;
}

Reasons for restrictions on assignment of final variables

Why aren't final variables default initialized? Shouldn't the default constructor initialize them to default values if you are happy with the constant be the default value.
Why must you initialized them in the constructor at all? Why can you can't you just initialize them before using them like other variables?
ex.
public class Untitled {
public final int zero;
public static void main(String[] args)
{
final int a; // this works
a = 4; // this works, but using a field doesn't
new Untitled();
}
}
Untitled.java:2: variable a might not have been initialized
Why must you initialize static final variables when they are declared? Why can't you just initialize them before using them in any other method?
ex.
public class Untitled
{
public final static int zero;
public static void main(String[] args)
{
zero = 0;
}
}
Untitled.java:8: cannot assign a value to final variable zero
I'm asking these question because I'm trying to find a logical/conceptual reason why this won't work, why it isn't allowed. Not just because it isn't.
The idea behind a final variable is that it is set once and only once.
For instance final variables, that means they can only be set during initialization, whether at declaration, in a constructor, or an instance initialization block. For the variable to be set anywhere else, that would have to take place in a non-constructor method, which could be called multiple times - that's why this is off limits.
Similarly for static final variables, they can only be set at declaration or in a static initialization block. Anywhere else would, again, have to be in a method which could be called more that once:
public static void main(String[] args)
{
zero = 0;
main(null);
}
As for your first question, I'm assuming it's an error not to explicitly set a final variable in order to avoid mistakes by the programmer.
The Java Language Specification section 8.3.1.2 spells out the rules for final member variables:
A field can be declared final (§4.12.4). Both class and instance variables (static and non-static fields) may be declared final.
It is a compile-time error if a blank final (§4.12.4) class variable is not definitely assigned (§16.8) by a static initializer (§8.7) of the class in which it is declared.
A blank final instance variable must be definitely assigned (§16.9) at the end of every constructor (§8.8) of the class in which it is declared; otherwise a compile-time error occurs.
The JLS doesn't give reasons why the rules are they way they are. However, it might have come from experience in writing Java code, and the above rules are a way to avoid some common coding errors.
The concept of being final means that the variable value cannot change. If you could do as in your second example, then this variable would have been like any other one (i.e. not final)
I don't ave a good rational regarding your first question.
Because, when looking at your code, the Java compiler has no idea whether a given statement will be executed before an other statement. The only exceptions to this rule are code in constructors and implicit constructors, and that's why they're the only place that final fields can be assigned to.

Categories