关于默认初始化

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.关于默认值说明

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值