关于static变量对于内存分配的实际验证...

关于static变量对于内存分配的实际验证...

public   class  Num
{
    
static  Integer i  =   new  Integer( 520 );
};
public   class  Demo
{
        
public   static   void  main(String[] args)
        {
            Num demo1 
=   new  Num();
            Num demo2 
=   new  Num();
            
if  (demo1.i  ==  demo2.i)
            {
                System.out.println(
" ture " );
            }
            
else
            {
                System.out.println(
" false " );
            }

        }
    
}

输出为: true!表明demo1.i和demo2.i只有一分存储空间.虽然new了两个对象.但只有一份存储空间!
public   class  Num
{
    Integer i 
=   new  Integer( 520 );
};

public   class  Demo
{
        
public   static   void  main(String[] args)
        {
            Num demo1 
=   new  Num();
            Num demo2 
=   new  Num();
            
if  (demo1.i  ==  demo2.i)
            {
                System.out.println(
" ture " );
            }
            
else
            {
                System.out.println(
" false " );
            }

        }
    
}

输出为false
关于static变量或方法..只会创建一份空间..无论是否有对象去引用..
下面是更深入的说明!!!
public   class  Num
{
 
static  Integer i  =   new  Integer( 520 );
 Integer j 
=   new  Integer( 520 );
}

public   class  Demo
{
        
public   static   void  main(String[] args)
        {
            Num demo1 
=   new  Num();
            Num demo2 
=   new  Num();
            
if  (demo1.i  ==  demo2.i)
            {
                System.out.println(
" ture " );
            }
            
else
            {
                System.out.println(
" false " );
            }
            
if  (demo1.j  ==  demo2.j)
            {
                System.out.println(
" ture " );
            }
            
else
            {
                System.out.println(
" false " );
            }
            System.out.println(Num.i);

        }
    
}

下面一个例子:
public   class  F1
{
    
public   static   void  main(String[] args)
    {
        Integer i 
=   new  Integer( 10 );
        Integer j 
=   new  Integer( 10 );
        
int  k  =   20 ;
        
int  l  =   20 ;
        System.out.println(k 
== l);
        System.out.println(i 
==  j);
    }
};
上面的例 子表明:对于通过new创建的两个对象的引用i&j,他们所引用的值都相同为10.但是,两个10存储在不同的两个地方,两个引用不同哦.....
上面例 子的结果为:
ture
false


 

芳儿宝贝.我爱你

你可能感兴趣的:(关于static变量对于内存分配的实际验证...)