Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:

Class and object initialization

Learn how to prepare classes and objects for use in an executing program

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

Page 2 of 9

Listing 2. ClassInitializationDemo2.java

// ClassInitializationDemo2.java
class ClassInitializationDemo2
{
   static boolean b = true;
   static byte by = 1;
   static char c = 'A';
   static double d = 1.2;
   static float f = 3.4f;
   static int i = 2;
   static long l = 3;
   static short s = 4;
   static String st = "abc";
   public static void main (String [] args)
   {
      System.out.println ("b = " + b);
      System.out.println ("by = " + by);
      System.out.println ("c = " + c);
      System.out.println ("d = " + d);
      System.out.println ("f = " + f);
      System.out.println ("i = " + i);
      System.out.println ("l = " + l);
      System.out.println ("s = " + s);
      System.out.println ("st = " + st);
   }
}


In contrast to ClassInitializationDemo1, in ClassInitializationDemo2 a class field initializer explicitly assigns a nondefault value to each class field. Simply put, a class field initializer consists of the assignment operator (=) and an expression that the JVM evaluates after a class loads and before any of that class's developer-specified methods execute. The assignment operator assigns the expression's value to the associated class field. When run, ClassInitializationDemo2 produces the following output:

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comments (3)
Login
Forgot your account info?

Very helpful article, thanxBy Anonymous on September 28, 2009, 7:56 pmThis question is risen by young curious java students. But there are low chances to describe without the deep concept understanding and seeing the whole picture....

Reply | Read entire comment

I'm always curious about it...By Anonymous on September 3, 2009, 2:59 amI'm always curious about it. You gave me a highway express. Thanks a lot.

Reply | Read entire comment

Very usefulBy Anonymous on May 3, 2009, 11:30 amThank you

Reply | Read entire comment

View all comments

Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources