File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Static Variable V/S Static Block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply locked New topic
Author

Static Variable V/S Static Block

Ramesh Sahu
Ranch Hand

Joined: Jul 14, 2008
Posts: 32
When I run the following code :


class cache
{
static{
initializeIfNecessary();
}


static int sum;

public static int getSum() {
initializeIfNecessary();
return sum;
}

static boolean initialized = false;

private static void initializeIfNecessary()
{
System.out.println("Initialized Called->"+initialized);
if(!initialized) {

sum+=1;
initialized = true;

}
}
}

class client {
public static void main(String args[])
{
System.out.println("Inside Main->"+cache.initialized +" "+ cache.sum);
System.out.println(cache.getSum());
}
}




I get the following output:
Initialized Called->false
Inside Main->false 1
Initialized Called->false
2

Can anyone explain me the output???
Thanks in advance!!
Tom Johnson
Ranch Hand

Joined: May 11, 2005
Posts: 142
my eyes

Please format the code so its readable!!


<a href="http://faq.javaranch.com/java/UseCodeTags" target="_blank" rel="nofollow">Use Code Tags!!</a>
amitabh mehra
Ranch Hand

Joined: Dec 05, 2006
Posts: 98
This is because of the order of initialization of static members - blocks, variables etc.
The cache class gets loaded and all of its static code is executed at that time. Static initializers are executed at the same time that static variables are initialized. The initializations occur in lexical order.

So this gives your first output line:
Initialized Called->false


Over here, the first thing is the static block that calls the static method initializeIfNecessary() which has reference to the 2 variables, declared static. So default values are taken here and code is executed. In the second step it goes for next static member -> sum, for which the values has already been calculated.
Then comes the boolean member and its value is rewritten to false.
If you omit out this assignment of false, you will see that value - true set during initializeIfNecessary() is retained.

Hence your other 2 outputs.


Ramesh Sahu
Ranch Hand

Joined: Jul 14, 2008
Posts: 32
Thanks for your reply.

But I really want to know what happens when the static block calls any static function with assignments within it &

when main method calls up the static method ......

I actually what to know what happens to assignments??

I am a bit confused!!!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19693
    
  20

Duplicate. Continuing here.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static Variable V/S Static Block