Hi Teo Rajkumar,
First of all, a warm welcome to CodeRanch!
Teo Rajkumar wrote:Is "static int var=value1" not equivalent to "static{ int var2=value2}" ? If so how do they differ?
Definitely
not! In this code snippet
var is a static (or class) variable and
var2 is nothing more but a local variable inside the static initializer block. And because
var2 is a local variable, you can only access it in the static initializer block itself.
But you could use the static initializer block to initialize static (or class) variables (and then it's equivalent to a static initializer), as illustrated in the following code snippet
Output:
static: var1 = 1
static: var2 = 2
static: var3 = 3
main: var1 = 1
main: var2 = 2
And as a final remark, a static (or class) variable can have the same name as a local variable. Illustrated in this code snippet
And the same applies to instance variables as well
What do you think the output will be of both code snippets?
Hope it helps!
Kind regards,
Roel