一.基本数据类型的占位及取值范围 1,整数类型的 1).byte(8位);取值<0x7f(127) 0x80(-128)> 2).short(16位);取值<0x7fff(32767) 0x8000(-32768)> 3).int(32位);取值<0x7fffffff(2G-1)2^31-1或21亿 0x80000000(-2G)> 4).long(64位);取值<2^63-1 -2^63-1> 2,浮点类型 1).float(4个字节);<-3.403E38~3.403E38> 2).double(6个字节);<-1.798E308~1.798E308> 3,字符型(文本型) 1).char(unicode字符16位);<0,65535> 4.布尔型 1).boolean(8位):true/false
二.类型的书写规则及类型之间的转换 1.书写规则 1).byte b=0; 2).short s=1; 3).int i=2; 4).long l=100000000L;或者long l=10000000l; 5).float f=0.314f;(单精度,一般后面加f) 6).double d=0.314(双精度) 7).char c ='A'或者 char c2=98;
还可以使用转义字符’/’来将其后的字符转变为其他的含义: char c2=’/n’;//’/n’代表换行符 8).boolean a=true ;boolean b=false; 2.类型转换 demo:
public static void main (String[]args){ //强制转换
byte b1=5;byte b2=6;byte b3=(byte)(b1+b2);short s1 = 1; s1 += 1 long d=10000000000L;long e=1000000000*2*10L;long f=1000000000*3*10L;long g=1000000000L*3*10;long h=System.currentTimeMillis();double h=56.98;int i =(int)h;double j=6.0,k=4.9;double z=j-k;char k='/'';System.out.PRintln(k);} 三.基本类型的包装类别 1.基本数据类型和包装类的对应表 byte:Byte short:Short int:Integer long:Long float;Float double:Double char:Character boolean:Boolean
Demo
public static void main(String[]args){ int I=1234; Integer i=new Integer(i) System out println(i); double D=1234.0; Double d=new Double(D) System.out.println(d); ......}除了int 和char之外,其他数据类型只要首字母大写即可编程他们的对应的包装类。
2.包装类的自动装箱和自动拆箱
public static void main(String[]args){ //自动装箱(基本数据直接转化为包装类) Integer intg =1234; //自动拆箱(包装类直接转化为基本数据类型) int in =intg; System.out.println(in); //基本数据类型 int i=2; //自动装箱 Object obj=2; //自动拆箱 int ii=(Integer)obj; System.out.println(ii);}3.引用数据类型String和包装类的转换
(1)每个包装类都有一个静态的valueOf方法,用于将字符串转换成相应包装类的对象(包装类.valueOf)
public class Demo{ public static void main (String[]args){ //转换异常,抛出NumberFormatException String str="456"; //.valueOf(str)返回的是对应的包装类的对象。自动拆箱为对应的基 //本类型 int i=Integer.valueOf(str); System.out.println(i); double j=Double.valueOf(str); System.out.println(j); .... //String 转换为基本类型,直接用包装类.valueOf(str);}2)String转换为基本类型还有2个方法 (1)parseXXX(String) (2)利用包装类提供的new xxx(String)构造器 demo:
public class demo{ public static void main (String[]args){ //ParseXXX int i=Integer.patreInt("123"); System.out.println(i); //用构造器 int j=new Integer("123"); System.out.println(i); }}``2)基本类型转换为String(1)int i= 123; Stringstr = i + ""; (2)用str.valueOfint i=2; String str=String.valueOf(i);
(3)将基本数据类型封装为对象,再调用对象的toString方法 String str1=Integer.toString(i);新闻热点
疑难解答