Chinaunix首页 | 论坛 | 博客
  • 博客访问: 346700
  • 博文数量: 81
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 847
  • 用 户 组: 普通用户
  • 注册时间: 2015-03-25 22:29
个人简介

执一不失,能君万物http://weidian.com/s/284520723?wfr=c

文章分类

全部博文(81)

文章存档

2016年(11)

2015年(70)

我的朋友

分类: Java

2015-06-18 15:19:35

Java中变量的自动类型转换与强制类型转换

点击(此处)折叠或打开

  1. /*
  2. 变量的自动类型转换与强制类型转换
  3. 自动类型转换-数据类型按容量大小排序为:char,byte
  4. */
  5. class TestVariable1{
  6.     public static void main(String[] args){
  7.         short s1 = 1;
  8.         int i1 = 2;
  9.         int i2 = s1 + i1;
  10.         float f1 = 12.2f;
  11.         float f2= f1 + i1;
  12.         //float f3 = f1 + 12.22;
  13.         //TestVariable1.java:14: 错误: 不兼容的类型: 从double转换到float可能会有损失
  14.         char c1 = 'a';
  15.         //a = 97
  16.         c1 = 'A';
  17.         //A = 65
  18.         int i3 = c1 + s1;
  19.         System.out.println(f2);
  20.         //System.out.println(f3);
  21.         System.out.println(i3);
  22.         short ss1 = 12;
  23.         byte bb1 = 1;
  24.         char cc1 = 'a';
  25.         int ii1 = ss1 + bb1;
  26.         System.out.println(ii1);
  27.         int ii2 = cc1 + bb1;
  28.         System.out.println(ii2);    
  29.         //强制类型转换
  30.         long l1 = 12345L;
  31.         int m1 = (int)l1;
  32.         System.out.println(m1);
  33.         byte by1 = (byte)m1;
  34.         System.out.println(by1);    
  35.         //平时常用的字符串,也是一种数据类型
  36.         String nation = "中国人";
  37.         System.out.println(nation);
  38. //当把任何基本类型的值和字符串值进行连接运算时(+),基本类型的值将自动转化为字符串类型。
  39.         String st1 = "hello";
  40.         String str1 = st1 + m1;
  41.         System.out.println(str1);
  42.         //举例
  43.         String str2 = "hello";
  44.         int myInt1 = 12;
  45.         char cha1 = 'a';
  46.         System.out.println(str2+myInt1+cha1);//hello12a
  47.         System.out.println(myInt1+cha1);//12+97=109
  48.         System.out.println(myInt1+cha1+myInt1);//12+97+12=121
  49.         System.out.println(cha1+str2+myInt1);//ahello12
  50.         System.out.println(myInt1);//12
  51.         System.out.println(cha1);//a
  52.     }
  53.     
  54. }


阅读(1662) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~