public class DataType
{
public static void main(String[] a)
{
float salary=20f;//单精度浮点数为20.0
double money=30d;//双精度浮点数为30.0 其中d可以省略
money=salary;//float型自动转换为double型,低向高自动转换。
/*java是向上兼容,基本类型高到低为:double - float - long - int |-char
|-short - byte */
salary=(float)money;//需要强制转换,否则提示:“编译错误:不兼容的类型: 从double转换到float可能会有损失”
byte b=25;
char c='a';
int i=23;
double d=.3;//表示0.3 反编译之后:double d1 = 0.29999999999999999D;
float result=(float)(b+c+i*d);//128.9 先计算i*d,值为(double)6.9;再计算b+c,值为(int)122;然后计算122+6.9=(double)128.9
//反汇编后为:float f1 = (float)((double)(byte0 + c) + (double)i * d1);
result=(float)(b+c);
System.out.println(result);
/*
short sho=10;
sho=sho+b;//提示错误:从int转换为short可能会丢失。意味着右侧的byte型和short型计算式,自动上转为int型
System.out.println(sho);
*/
System.out.println(++c);//输出:b
System.out.println(c+1);//输出:99
char ch='天';
System.out.println(++ch);//输出:太 unicode码位置中的下一个
System.out.println(ch+1);//输出:22827 unicode码的值 + (int)1
short sh=1;
// sh=sh+1;//1是整形,与sh相加后转型为int型,再赋值给sh时出错,需要强制转换。错误: 不兼容的类型: 从int转换到short可能会有损失。
sh+=1;//编译正确,输出:2 由于+=是一个运算符,可以近似理解成赋值语句,不涉及到上一句那样运算时转型为int的情况。
System.out.println(sh);
long lo=100;
switch((int)lo)//需要在此处强制转换为(int),否则报错:“不兼容的类型: 从long转换到int可能会有损失”
{ //可以向上转型为int型的变量都可以switch,比int型高的都不可以switch,需要强制转换类型。
case 100:System.out.println("**********");
}
String st="Hello";
switch(st)//一开始我以为switch重载了String类型,反编译后发现是利用了哈希值进行判断,反编译后:switch(st.hashCode())
{
case "Hello":System.out.println("@@@@@@@@@@");
}
String st1="HelloWorld";
String st2="HelloWorld";
System.out.println(st1==st2);//输出:true 我感觉这个“hello world”在常量池里,我认为反编译为st2=st1更准确。并且是同一片地址空间
String st3="Hello"+"World";//输出:true 赋值前先把右边连接好,所以等同于st2赋值时的“HelloWorld”。反编译后:String st3="HelloWorld";
System.out.println(st2==st3);
String st4=st+"World";//注:String类型不可以用 += ,
//此处是否创建了“World”对象?还是只创建了 StringBuilder()对象和“HelloWorld”这两个对象
System.out.println(st1==st4);//输出:false
/*反编译前我是这样想的:
创建了新的对象“World”(如果常量池里没有),又创建了新的对象“HelloWorld”。
反编译后:String s4 = (new StringBuilder()).append(s).append("World").toString();
*/
String st5=st+"World";//输出:false ,在变量参与运算时,会重新开辟字符串,而不会像st2那样直接指向st1那片地址。
System.out.println(st4==st5);
int iValue=129;
byte bValue=(byte)iValue;//强制把一个int类型的值转换为byte类型的值
System.out.println(bValue);//输出:-127,127+1后溢出,溢出后为-128,再+1,变为-127
double dValue=3.98;
int tol=(int)dValue;//强制把一个double类型的值转换为int
System.out.println(tol);//输出:3,强制转换,失去小数部分。
short shh=-1000;//反编译时发现,用char代替了short,用(char)32767以上的数来表示short类型的负数。
char chh=1000;
int abc=chh+shh;//计算时右侧上转为int
System.out.println(abc);
System.out.println("\u000a");//\u000a \u000d都在编译时错误。“错误: 未结束的字符串文字”
//System.out.println("浮点数最大值是:"+Float.MAX_VALUE);
int wat=15;
wat+=wat*=wat;
System.out.println(wat);//输出 240,在GNU c++里输出450
}
}
Java数据类型
最新推荐文章于 2024-05-20 20:48:34 发布