java 中static修饰变量的初始值

public class StaticTest {  
  
    public static byte a1;  
      
    public static short a2;  
      
    public static int a3;  
      
    public static long a4;  
      
    public static char b;  
      
    public static double c;  
      
    public static float d;  
      
    public static boolean e;  
      
    public static String f;  
  
    public static Object g;  
      
    public static int[] a_h;  
      
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
  
        System.out.println("static byte a1------"+a1);  
        System.out.println("static short a2-----"+a2);  
        System.out.println("static int a3-------"+a3);  
        System.out.println("static long a4------"+a4);  
        System.out.println("sstatic char b------"+b);  
        System.out.println("static double c-----"+c);  
        System.out.println("sstatic float d-----"+d);  
        System.out.println("static boolean e----"+e);  
        System.out.println("static String f-----"+f);  
        System.out.println("static Object g-----"+g);  
        System.out.println("static int[] a_h-----"+a_h);  
    }  
  
}  

大家都知道,static修饰的变量在类实例之前就已经分配内存,


结果:

static byte a1------0
static short a2-----0
static int a3-------0
static long a4------0
sstatic char b------

static double c-----0.0
sstatic float d-----0.0
static boolean e----false
static String f-----null
static Object g-----null
static int[] a_h-----null

若变量前无static修饰,并且没有对变量进行初始化,例如:

public class noStaticTest {  
  
    public byte a1=1;  
  
  
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
  
        System.out.println("static byte a1------"+a1);  
          
    }  
  
}  

编译器会编译不通过: Cannot make a static reference to the non-static field a1

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值