This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Initializers in program. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Initializers in program." Watch "Initializers in program." New topic
Author

Initializers in program.

Prasad Ballari
Ranch Hand

Joined: Sep 23, 2000
Posts: 149
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

Joined: Nov 14, 2000
Posts: 104
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


Suresh Selvaraj, (author of JQuiz)<br />SCJP2<br /><a href="http://www.decontconsulting.com" target="_blank" rel="nofollow">www.decontconsulting.com</a>
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Initializers in program.
 
Similar Threads
terminology question
Anonymous class with no constructor.
Constructor
can we accept this code as singleton
Anonymous Classes & Exception Handling