码迷,mamicode.com
首页 > 编程语言 > 详细

java中变量运算细节 (2)

时间:2014-07-27 23:25:19      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:blog   java   os   div   ar   new   app   log   

/*
目的:测试变量的运算方式
结果: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;
	}
}

  

java中变量运算细节 (2),布布扣,bubuko.com

java中变量运算细节 (2)

标签:blog   java   os   div   ar   new   app   log   

原文地址:http://www.cnblogs.com/hujunzheng/p/3871945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!