This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initializers in program.

 
Prasad Ballari
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Can anybody help me, What is the difference between class variable initializer and instance variable initilizer.And how can i write each one of them.
(The basic concept what i know is that, class initializers are used to initialize class variables and instance initializers are used to initialize instance varibales.).
Can anybody help me.( with example).
Thanks in advance
Ragards
Prasad.


[This message has been edited by Prasad Ballari (edited November 16, 2000).]
 
Suresh Selvaraj
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Static Initializer is initialised when the class is loaded and even before the main() method is executed. Static variables are also known as class variables.
Instance members (variables/methods) belong to every instance of a class.
Example:
class A
{
static // 1 ==> Static Initializer
{
System.out.println("Static Initializer Executed");
}
static int x=9; // 2 ==> class variable
int y; // 3 ==> Instance variable
boolean answer; // 4 ==> Instance variable
String s; // 5 ==> Instance variable
public static void main(String [] args)
{
A a = new A();
System.out.println(" x = " + A.x );
System.out.println(" y = " + a.y );
System.out.println(" answer = " + a.answer );
System.out.println(" String s = " + a.s );
}
}
Output:
Static Initializer Executed
9
0
false
null
From the above output,it is clear that static initializers are executed even before the main() method is executed.
The instance variables are initialised with the default values, i.e "0" for int, "false" for boolean, "null" for String/any Object.
The static variable "x=9" is accessed by its class name "A".
- Suresh Selvaraj
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic