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).
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java static class initialization
Why is the string variable updated in the initialization block and not the integer(even though the block is written first)
class NewClass
{
static
{
System.out.println(NewClass.string+" "+NewClass.integer);
}
final static String string="static";
final static Integer integer=1;
public static void main(String [] args)//throws Exception
{
}
}
My output is
static null
P.S:Also noticed that string variable initialization happens before the block only when i insert the final modifier. why is that?why not for integer as well?I have declared it as final static too
From section 12.4.2 of the JLS, snipped appropriately:
The procedure for initializing C is then as follows:
Then, initialize the final class variables and fields of interfaces whose values are compile-time constant expressions (§8.3.2.1, §9.3.1, §13.4.9, §15.28).
Next, 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.
So for non-compile-time-constants, it's not a case of "all variables" and then "all static initializers" or vice versa - it's all of them together, in textual order. So if you had:
static int x = method("x");
static {
System.out.println("init 1");
}
static int y = method("y");
static {
System.out.println("init 2");
}
static int method(String name) {
System.out.println(name);
return 0;
}
Then the output would be:
x
init 1
y
init 2
Even making x or y final wouldn't affect this here, as they still wouldn't be compile-time constants.
P.S:Also noticed that string variable initialization happens before the block only when i insert the final modifier.
At that point, it's a compile-time constant, and any uses of it basically inlined. Additionally, the variable value is assigned before the rest of the initializers, as above.
Section 15.28 of the JLS defines compile-time constants - it includes all primitive values and String, but not the wrapper types such as Integer.
Here is a short and straight forward answer to you question....
static Variable :
static Variables are executed when the JVM loads the Class, and the Class gets loaded when either its been instantiated or its static method is being called.
static Block or static Initializer Block :
static static Initializer Block gets Initialized before the Class gets instantiated or before its static method is called, and Even before its static variable is used.
///////// Edited Part /////////
class NewClass {
final static String string = "static";
final static Integer integer = 1;
static {
System.out.println(NewClas.string + " " + NewClas.integer);
}
public static void main(String [] args) { // throws Exception
new NewClas();
}
}
The above will print static 1.
The reason is that the JVM will do the optimization process known as Constant folding, doing an pre-calculation of the constant variables.
Moreover in your case the result was static null cause Constant folding is applied to Primitive type and not Wrapper Object, in your case its Integer...
They are initialized in the given order (fields and static blocks), that's why printed value is null, nothing was assigned to static fields that are defined after the 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.
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.
Here is example code:
class A {
static {
int a;
class B {
}
}
public static void main(String[] args){
// cannot access class B and in a;
}
}
I don't know what the static keyword in this context means. I declare an int variable and a class inside it. But I cannot use it inside class A or in the main method. I compile and it doesn't produce any errors. So, I think this type of declaration has some purpose.
This is a static initialization block. You can use this to collect initialization for static/class members.
Similarly you can have a non-static initialization block to initialize instance members for each new object:
class A
{
static int a;
private int b;
// static/class initialization:
static
{
// initialize class members
a = 5;
}
// instance initialization:
{
// initialize instance members
b = 5;
}
}
This example is trivial, you could instead just initialize the variables in their declaration: static int a = 5, and in fact generally that would be clearer. But use an initialization block when the initialization is multi-step, or generally more complicated, for example, setting up a database connection.
For more examples, see: Initializing Fields from the java tutorials.
The code inside the static {} block will be executed when the class (not an object of this class) is loaded for the first time.
See this
It is referred as static block in Java. This is usually used for initialization purposes that your Class A might require
static blocks are executed when JVM loads this class. There can be many such blocks and they would be executed in the order of appearance
This is a static initialization block. Here is Oracle Java SE documentation static initialization blocks.
In your example, int a is a local variable to the static initialization block. Here is another Stackoverflow post regarding local variables in static initialization blocks: What is the scope of variables declared inside a static block in java?. That is why you cannot access it in your main method.
That definition is a static initializer block. It allows extra logic for initialization, in this case applied to static members.
You will be able to access whatever you initialize in the block if you call the class A constructor, because "the Java complier copies initializer blocks into every constructor". Check docs
This is the static initializer block.
The reason that int a and class B cannot be accessed outside of the block is due to scoping. Similar to constructors and methods, variables declared within the scope of the initializer block are not accessible outside of the block.
Static variables: Are the class variables and they are not created separately for each object of the class.
Instance variables: Are also the class variables but are created for each object separately.
The above definitions are just for references.
Please explain why i am getting error in this class declaration.I know it is just because i have not of initialised x.
class non_static{
public static void main(String args[])
{
int x;
System.out.println(x);
}
}
But this class declaration is totally fine.
class static_example{
static int x;
public static void main(String args[])
{
System.out.println(x);
}
}
And output of this program is 0.
Please do explain me why static member is initialized with the default value while local variables are not.
It has nothing to do with static declaration vs instance declaration. It is local declaration, which does not have a default and will cause an error when it is used uninitialized.
public class Example {
private static int stattic;
private int instancee;
public void someMethod() {
System.out.println("I am static and 0: " + stattic);
System.out.println("I am not static and 0: " + instancee);
int locall;
System.out.println("I am causing an error because I have not been initialized: " + locall);
}
}
If you want to know the background on why Java specifies it like that, it has to do wih the limits of static code analysis. Memory allocated from the stack (and this is where the local vars are) can be confirmed positively by the compiler to be initialized before use. Not so with heap-allocated storage (static vars, instance vars). This is why the JLS requires the implementations to always zero out any heap storage before exposing a pointer to it.
Local variables must always be initialized with a value. For non-local variables (i.e. instance or static variables) the default is defined as the corresponding type's null values (null, zero or false).
In java the Instance Variables (ie class variables) are initialized to their default values.
But the Local Variables (ie Method variables) CAN NOT be used without initializing...
class static_example{
static int x;
public static void main(String args[])
{
System.out.println(x);
}
}
In the above example of yours, x is declared at Class scope... So it is already initialized to its default value 0, so its NOT GIVING any error..