天天看点

关于默认初始化

Exercise 1: (2) Create a class containing an int and a char that are not initialized, and print their values to verify that Java performs default initialization.

练习:创建一个类,他包含一个int域和一个char域,他们没有被初始化,将他们的值打印出来,以验证Java执行力默认初始化。

能运行的程序如下:

public class Ex1 
{
   static int i;
   static char ch;
   public static void main(String[] args)
   {
       System.out.println("The default value for \"int\" is"+i);
       System.out.println("The default value for \"char\" is"+ch);
   }
}
           

错误1:

public class Ex1 
{
   
   public static void main(String[] args)
   {  
       static int i;
       static char ch;
       System.out.println("The default value for \"int\" is"+i);
       System.out.println("The default value for \"char\" is"+ch);
   }
}
           

错误2:

public class Ex1 
{
   
   public static void main(String[] args)
   {  
       int i;
       char ch;
       System.out.println("The default value for \"int\" is"+i);
       System.out.println("The default value for \"char\" is"+ch);
   }
}
           

注意点:

1.错误1说明

The default values are only what Java guarantees when the variable is used as a member of a class. This ensures that member variables of primitive types will always be initialized (something C++ doesn’t do), reducing a source of bugs. However, this initial value may not be correct or even legal for the program you are writing. It’s best to always explicitly initialize your variables.

2.错误2说明

关于Static的关键字的用法,static variable有什么作用,下面就有描述:

One is if you want to have only a single piece of storage for a particular field, regardless of how many objects of that class are created, or even if no objects are created. The other is if you need a method that isn’t associated with any particular object of this class. That is, you need a method that you can call even if no objects are created.

3.关于默认值说明

若某个主数据类型属于一个类成员,那么即使不明确(显式)进行初始化,也可以保证它们获得一个默认值,这种保证却并不适用于“局部”变量——那些变量并非一个类的字段。