java-数据类型

基础数据类型

  • int在64位或者32位jvm中都是32位
  • short、char都是16位

int和Integer

  • int和Integer可以通过自动的拆箱装箱进行转换
      Integer a=1;
      int b=a+1;
    
  • Integer比int占内存,Integer时一个对象,需要存储对象的元数据

String、StringBuilder、StringBuffer

  • string是字符串常量,频繁的使用String进行拼接,会产生占用大量的内存,造成gc
    • String str="a"+"b"虚拟机直接优化成String str="ab"
  • StringBuilder是线程不安全的字符串变量,字符串凭借在对象内部完成
  • StringBuffer是线程安全的字符串变量

String

subString()

subString会保存一份原字符串的引用,造成截取的字符会阻止回收原始数据

https://blog.csdn.net/chenleixing/article/details/43646255

new String()和字面量创建字符串的区别

  • 使用new String()创建的字符串对象不会进入jvm的字符串池,而是进入到堆中。使用intern()可以放入常量池中(jdk1.7以前)
  • 使用字面量创建会直接进入到字符串池。

String运算

String s1="ab";
String s2="a"+"b";//编译过程直接转换成"ab",在常量池中
String s3="a";
String s4="b";
String s5=s3+s4;//相当于stringBuilder.append()在堆中
s2==s5//false
String s1 = “abc”; 
final String s2 = “a”; 
final String s3 = “bc”; 
String s4 = s2 + s3; 
System.out.println(s1 == s4); //true。在编译器会将final替换
String s1 = “abc”; 
String s2 = “a”; 
String s3 = “bc”; 
String s4 = s2 + s3; 
System.out.println(s1 == s4);//false,s2 + s3相当于是stringBuilder.append()

intern()

String str="ab";
String str1=str.intern();//在常量池中找str,如果找到则返回;没找到则放入常量池中,然后返回
str==str1//true

https://blog.csdn.net/soonfly/article/details/70147205

BigDecimal

  • 用来表示价格比较好,否则将浮点转成整形处理

float

0.1*3==0.3//false 有些浮点数不能精确的表现出来

类型转换

a+=b

byte a=3,b=10;
a+=b;//正常,先ab转换成int进行计算,计算结果强转成byte,再赋值
a=a+b;//编译错误,由于少了类型转换的步骤:改为a=(byte)(a+b);

byte[]->String

  • 使用String(byte[],charset)的构造函数,注意字符编码集

other

switch

  • 1.7前不能使用String作为参数,1.7后开始支持

猜你喜欢

转载自blog.csdn.net/designer01/article/details/81512239
今日推荐