Printing static variable without class name leads to an error - java

public class ClearingDoubtsAboutStatic {
static
{
System.out.println("Static Block1 Output: "+ClearingDoubtsAboutStatic.statVar); //------Line 5
statVar=20; //-----Line 6
System.out.println("Static Block1 Output: "+ClearingDoubtsAboutStatic.statVar); //------Line 7
System.out.println("Static Block1 Output: "+statVar); //---Line 8
}
static int statVar=30;
public static void main(String[] args) {
}
}
What in my mind was that the line 7 and 8 will give the same output, but it is not the case.
My Question
what I don't understand is when we are able to initialize the static variable without the class name at line 6 but why we are not able to print it without the class name at line 8?

The 2 rules you copy/paste are wrong, you should only consider:
Static declaration and static block initialization are considered in
the order they appear in the source file
Thus, you can fix your issue, changing the order of the declaration, and your static initialization block:
static int statVar=30;
static
{
System.out.println("Static Block1 Output: "+ statVar); //------Line 5
statVar=20; //-----Line 6
System.out.println("Static Block1 Output: "+ statVar); //------Line 7
System.out.println("Static Block1 Output: "+statVar); //---Line 8
}

I not quite sure about your case but in my IntelliJ when I try your code, I got this:
Error:(9, 55) java: illegal forward reference

Hmmm i'm not sure about that but i will share with you my guess. Initialization starts first for everything that is static in Class (in defined order). So your static{...} is will be initialized at first, then statVar will receive its value. First printing should show 0 as this is default int value. It works because your are referencing it by Class name and that is how static variables should be referenced. There is one static variable for Class, not for object. When you are trying to reference it without class name, your are treating it like just some field in your class and you shouldn't try to reference those before they are defined. So compiler is not allowing to do so.

Related

Static Variable with null reference

When I run this code it print twice 0 but i don't undrestand why after affect the object k to null the value of count still printed 0 but when i delete static before count and execute this program it print first 0 and then i print an exception
Exception in thread "main" java.lang.NullPointerException.
Please Can you resolve this problem.
public class Test{
public static int count=0;
public static void main(String[] args){
Test t = new Test();
System.out.println(t.count); // 0
t=null;
System.out.println(t.count); // 0
}
}
static variables in Java are defined at class level and you do not need an object of that class to reference static variable.
And even if you write t.count JVM will instead do conventional Test.count instead (it will replace name of variable with name of its class).
And below extract from JLS: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.11.1
Example 15.11.1-2. Receiver Variable Is Irrelevant For static Field
Access
The following program demonstrates that a null reference may be used
to access a class (static) variable without causing an exception:
class Test3 {
static String mountain = "Chocorua";
static Test3 favorite(){
System.out.print("Mount ");
return null;
}
public static void main(String[] args) {
System.out.println(favorite().mountain);
} } It compiles, executes, and prints:
Mount Chocorua Even though the result of favorite() is null, a
NullPointerException is not thrown. That "Mount " is printed
demonstrates that the Primary expression is indeed fully evaluated at
run time, despite the fact that only its type, not its value, is used
to determine which field to access (because the field mountain is
static).
I assume, you meant t=null; instead of k=null;.
The static variables are there always only once in whole program, they aren't bent to the objects. All instances of Test have the same count, always. If you set it to anything else, it will change for all instances. Therefore, you can read the value from null as well. Alternativelly, you can use System.out.println(Test::count), which will also print 0, without the need of any object of class Test.

How is this Java program executed?

class Welcome{
public static void main(String args[]){
System.out.println(Hello.a);
}
}
class Hello{
static int a=10;
static Hello h=new Hello();
{
System.out.println("IB");
}
static{
System.out.println("SB");
}
}
Output:
IB
SB
10
I really don't understand the logic behind this execution. According to me, the static variables are initialized and static block gets executed. Then, the instance variable is initialized and instance block is executed.
However, this seems to be a bit confusing. It would be a great help if a step-by-step order of actual execution is given.
What is the meaning of static Hello h=new Hello();?
How will this be treated?
I fixed the class keyword and ran it through. The execution is quite straight forward when you see it running.
Static variables are initialised. That means a and h are set.
Initialiser blocks are ran. So "IB" is printed. They run because the value of h is a new Hello object.
NOTE: This only happens because h is defined before the static initializer block in the class. If you change the order they appear in the code, then the order of execution will change.
Static initialiser blocks are ran. So "SB" is printed.
main method is invoked, which prints out Hello.a. So 10 is printed.
IDEOne Link: http://ideone.com/KfdS6n

Java Compilation error 12 : error: <identifier> expected : Initializing and declaring of variable in separate statement . [duplicate]

This question already has answers here:
Java: Identifier expected
(5 answers)
Closed 5 years ago.
While compiling below piece of code, getting error as "error: expected" :
class Test {
public static void main(String[] args) {
Hello h=new Hello();
System.out.println(h.a);
}
}
class Hello {
int a;
a=10;
/*{
a=10
}
}*/ //Putting the reference variable inside the Instance block .
However if declare and initialize variable "a" in the same statement(int a=10;)inside class Hello then not getting error .
The problem is you have a floating initializer statement, you need to have something like the following:
class Test {
public static void main(String[] args) {
Hello h=new Hello();
System.out.println(h.a);
}
}
class Hello {
int a = 10; //changed this line
}
When a variable is simply named, such as below, it is declared. Declaring a variable creates a memory allocation, defines the variable type (e.g. int, char etc) and gives the variable a name (in your case a).
When you initialize a variable, it all the above information is already known, you simply change the variable from its default value to a new one.
The reason you can't initialize the variable from within the class Test is rules set by the creators (and maintainers) of Java. Interestingly when you try the following Eclipse prevents you from compiling:
public class Test {
int i;
i = 10;
}
So I thought it may be a safety feature of the IDE, so I ran from command line:
And that flagged up as an identifier expected error. Simply put, Java was created in mind that when you create a class level variable it must be declared and initialized in the same line, or just declared, and the software which translates from Java code -> Bytecode -> Machine code (the JVM, Java Virtual Machine), has not been made to cope with multi-line initializations at that scope level.

How the output of program came?

The output of following program is:
superstatic block
static blockn0
inmain
super constructor
constructor
Here is the code:
class StaticSuper{
static {
System.out.println("superstatic block");
}
StaticSuper(){
System.out.println("super constructor");
}
}
public class StaticClassExample extends StaticSuper{
static int rand;
static {
rand =(int) (Math.random() * 6);
System.out.println("static blockn" + rand);
}
StaticClassExample(){
System.out.println("constructor");
}
public static void main(String[] args) {
System.out.println("inmain");
StaticClassExample st= new StaticClassExample();
}
}
Why "inmain" is printed third though it is first in the main()? Please explain me the meaning of:
static {
// some lines
}
in the class.
The static block you're seeing is what we call a static initializer and its job is usually to initialize something in the class (perhaps a class-wide state or some kind of resource).
It is invoked when the class is loaded by the runtime and that's why it may be run before main is run.
1 : when you create an instance by using new == > it calls the constructor
2 : just when you constructor is called , the parent constructor is called
3 : and also whenever a class is loaded , even for a constructor , the static blocks are executed first ,
thus you get the order you are getting
since you are executing you class , the complete files is checked first for any static block , and static blocks are executed even before the main method gets called
Static blocks are called at the time classes are loaded. Thats why print outs of static are printed first.
Static variable means that there won't be separate copies of that variable for different instances of that class.
Static block of code is simply if you want to execute something at the time of class loading.
Please explain me the meaning of static { // some lines } in the
class.
It's called a static initializer. It's executed when the class is loaded (or initialized, to be exact). The static blocks will be executed before your main()method.
Why "inmain" is printed third though it is first in the main()?
Since static blocks are executed before your main(), it appears third in the print list and when you create the instance of StaticClassExample class, first its parent constructor is called and then its own constructor is called.
Hence, the output.

Why is this Java code in curly braces ({}) outside of a method?

I am getting ready for a java certification exam and I have seen code LIKE this in one of the practice tests:
class Foo {
int x = 1;
public static void main(String [] args) {
int x = 2;
Foo f = new Foo();
f.whatever();
}
{ x += x; } // <-- what's up with this?
void whatever() {
++x;
System.out.println(x);
}
}
My question is ... Is it valid to write code in curly braces outside a method? What are the effects of these (if any)?
Borrowed from here -
Normally, you would put code to initialize an instance variable in a
constructor. There are two alternatives to using a constructor to
initialize instance variables: initializer blocks and final methods.
Initializer blocks for instance variables look just like static
initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
You may also wanna look at the discussions here.
This is an initializer block that is executed while the instance of the class is being loaded/created and that is used to initialize member properties of a class (See Java http://download.oracle.com/javase/tutorial/java/javaOO/initial.html). You can have as many blocks as you want and they will be instantiated from top to bottom.
In addition to the instance block, you can have as many static blocks as you want as well to initialize static members. They would be declared as follows:
public class Initialization {
static int b = 10;
int a = 5;
static {
b = -9;
}
{
a += 2;
}
public static void main(String[] args) throws Exception {
System.out.println(ClientVoting.b);
System.out.println(new ClientVoting().a);
System.out.println(ClientVoting.b);
System.out.println(new ClientVoting().a);
}
static {
b = 1;
}
{
a++;
}
}
While the class is being initialized, the static member "b" is initialized as 10, then the first static scope changes its value to -9, and later to 1. This is only executed once while the class is loaded. This executes before the initialization of the first line of the main method.
On the other hand, the similar example to your class is the instance reference "a". A is initialized as 5, then the instance block updates it to 7, and the last block to 8. As expected, the static members are only initialized once in this code, while the instance blocks are executed EVERY time you create a new instance.
The output to this example is 1 8 1 8
It's an initializer block. It's used to set instance variables. The motivation to use initializer blocks over constructors is to prevent writing redundant code. The Java compiler copies the contents of the block into each constructor.

Categories