zoukankan      html  css  js  c++  java
  • java中变量运算细节 (2)

    /*
    目的:测试变量的运算方式
    结果:byte a, b, c;
           a = b+c;
           或者 a = b+10
           形如这种形式的算式, 等式的右边的运算结果默认的都是int型的!因为等式右边有变量, 编译器无法确定变量的内容
           ,因为它是变量!所以相加之后得到的int再默认强制转换成byte可能会损失精度.
           而形如 a=4+5;这种常量的赋值,虽然 4 和 5 都默认的是int, 但都是常量,它们的值是确定的!所以如果 4+5的值超过了
           byte的最大值的范围, 那就会编译出错!(也就是等式右边都是常量运算,编译器是可以判断的!)
    	   
    	形如 byte a = 9, b=12;
    	或者 a+=b; a+=10; 这样的赋值运算编译器底层都是做了强制转换运算的!
    	也就是说 a+=b 等价于 a = (byte)(a+b); 而不是 a = a+b;
    */
    
    public class VarDemo{
       public static void main(String args[]){
               StringBuffer str =  new StringBuffer("a");
    	   String newStr = new String(str.append(1123));
    	   System.out.println(str.append(new myClass()));
    	   
    	   //这样写编译就是对的了!why?
    	   int a, b, c;
    	   b = 10;
    	   c = 14;
    	   a = b+c;
    	   
           int a1;
    	   byte b1, c1;
    	   b1 = Byte.MAX_VALUE;
    	   c1 = 34;
    	   a1 = b1+c1; 
    	   System.out.println(b1 + " " + a1);
    	  
    	   /*
             这样写是编译错的!why?
    	     byte a3;
    	     byte b3;
    	     b3 = 12;
    	     a3 = b3 + 6; 
    	     System.out.println(b3 + " " + a3);
           */	
    
           /*
             这样写是编译却是对的!why?
    	     byte a3=4;
    	     byte b3;
    	     b3 = 12;
    	     a3 += b3; 
    	     System.out.println(b3 + " " + a3);
           */		   
    	  
    	   /*
               这样写编译是错的!why?
       	       byte av=100+200;
    	   */
    	  
    	   /*
    	       这样写编译就是对的了!why?
    	       byte a1;
    	       a1=4+5;
    	   */
    
       	   /*
              这样写编译是错的!why? 	   
    	      byte a1;
    	      byte b1, c1;
    	      b1=Byte.MAX_VALUE;
    	      c1=34;
    	      a1=b1+c1;
    	   */
    	   
    	   
    	   
    	   /*
    	   这样写是编译错的!why?
    	   short a2, b2, c2;
    	   b2=10;
    	   c2=34;
    	   a2=b2+c2;
           */
       }
    }
    
    class myClass{
        int x;
    	String str;
    	public myClass(){
    	    x=4234;
    		str = new String("hujunzheng");
    	}
    	
    	public String  toString(){
    	   return " " + x + " " + str;
    	}
    }
    

      

  • 相关阅读:
    mybatis-generator自动生成代码时,只生成insert方法
    elasticsearch-head-master下运行npm install报npm WARN elasticsearch-head@0.0.0 license should be a valid SPDX license expression
    fs.default.name和fs.defaultFS
    zookeeper集群为什么要是单数
    Quorom机制
    把数据库放入Docker是一个好主意吗?
    JVM GC算法CMS详解
    JVM之——CMS
    对于TCP/IP协议的三次握手和四次挥手的理解
    JVM G1和CMS
  • 原文地址:https://www.cnblogs.com/hujunzheng/p/3871945.html
Copyright © 2011-2022 走看看