表达式的类型转换

一段小程序来解释表达式中的各个数据类型的转换机制。

package com.liaojianya.chapter1;
/**
 * This program demonstrates the convertion of data type.
 * @author LIAO JIANYA
 *
 */
public class TypeConvert6_17
{
	public static void main(String[] args)
	{
		char ch = 'a';
		short a = -2;
		int b = 3;
		float f = 5.3f;
		double d = 6.28;

		System.out.println("ch / a = " + ch / a);
		System.out.println("the type of (ch / a) is :  " + getType((ch / a)));
		
		System.out.println("d / f = " + d / f);
		System.out.println("the type of (d / f) is :  " + getType((d / f)));
		
		System.out.println("a + b = " + (a + b));
		System.out.println("the type of (a + b) is :  " + getType((a + b)));
		
		System.out.println("(ch / a) - (d / f) - (a + b) = " + ((ch / a) - (d / f) - (a + b)));		
		System.out.println("the type of ((ch / a) - (d / f) - (a + b)) is :  " 
		+ getType(((ch / a) - (d / f) - (a + b))));
	}
		public static String getType(Object o)
		{
			return o.getClass().toString();
		}
		public static String getType(int o)
		{
			return "int";
		}
		public static String getType(char o)
		{
			return "char";
		}
		public static String getType(short o)
		{
			return "short";
		}
		public static String getType(float o)
		{
			return "short";
		}
		public static String getType(double o)
		{
			return "double";
		}

}

  运行结果:

ch / a = -48
the type of (ch / a) is :  int
d / f = 1.1849056177353188
the type of (d / f) is :  double
a + b = 1
the type of (a + b) is :  int
(ch / a) - (d / f) - (a + b) = -50.18490561773532
the type of ((ch / a) - (d / f) - (a + b)) is :  double

 分析:

 1)占用字节较少的数据类型转换成占用字节较多的数据类型。

 2)字符类型会转换成int类型。

 3)int类型会转换成float类型。

 4)表达式中出现double,则其他操作数也会转换成double类型。

 5)总结:大鱼吃小鱼:占字节多的替换占字节少的;精度高的优先;优先级排序:byte,short,int,long,float,double。

转载于:https://www.cnblogs.com/Andya/p/5680044.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值