字符串常量池

来源:互联网 发布:mysql 主键作用 编辑:程序博客网 时间:2024/06/05 07:38

字符串是一个比较常用到的东西,但是字符串没有基本数据类型,所以在内存中有一块存储区域来管理曾经用过的字符串直接量,例如定义了一个字符串String s1 = “java” 如果再执行String b = “java” 那么变量a,b 指向的是字符串里面的同一个字符串直接量。

看代码和注释分析字符串和其他基本类型的区别:

package classfile;public class StringTest{    public static void main(String[] args)    {        String str1 = "www";        String str2 = "www";        System.out.println(str1==str2);//true,指向相同的常量池中的字符串直接量        String str3 = new String("kkk");        String str4 = new String("kkk");        System.out.println(str3==str4);//false,用字符串引用比较指向对象的两个不同地址        int a = 8;        int b = 8;        System.out.println(a==b);//true;        int c = new Integer(5);//利用包装类new+构造函数,new出来的对象直接赋值给int变量c,不是整型引用和整型对象的关系属于直接赋值。        int d = new Integer(5);        System.out.println(c==d);//true        System.out.println((new Integer(8))==(new Integer(8)));//false        float f1 = new Float(4.5f);        float f2 = new Float(4.5f);        System.out.println(f1==f2);//true        System.out.println((new Float(4.8f))==(new Float(4.8f)));//    }}
0 0
原创粉丝点击