在讨论两者区别之前我们先明确.equals()和==的区别
String a = "abc";
String b = new String("abc");
String c = "abc";
String d = new String("abc");
System.out.println(a==b);
System.out.println(a==c);
System.out.println(b==d);
System.out.println(a.equals(b));
输出的结果是:false
true
false
true
String是引用类型,==既比较地址又比较值,.equals()只比较值。
如果按正常声明并赋值String类型,如String a="abc";系统会自动在内存中查找是否有abc这个值,如有,将会把a的头指针指向已存在的abc值。而new出来的字符串,不管内存中本来有没有abc值,都会新建一块内存,把abc存进去。需要注意的是,如果:
String a=new String("abc");
String b="abc";
System.out.println(a==b);
结果为:false
猜测原因为new出来的类型和直接赋值的类型在内存中存储方式不一样,所以系统找不到已存在的字符串abc。因不了解Java底层写法。所以……姑且这么记吧。
JDK API官方文档写法:
String str = "abc";
等效于:
char data[] = {'a', 'b', 'c'}; String str = new String(data);
//在类的内部,同类型的对象引用,可以调用类内的private属性信息
public String(String original) {
int size = original.count;
char[] originalValue = original.value;
}
String(char[] value)
分配一个新的 String,使其表示字符数组参数中当前包含的字符序列
String(String original)
初始化一个新创建的 String 对象,使其表示一个与参数相同的字符序列;换句话说,新创建的字符串是该参数字符串的副本
String相关常用操作:
返回指定字符在此字符串中第一次出现处的索引
int index = url.indexOf("8081");
System.out.println("index=" + index);
String sub = url.substring(index);
System.out.println(sub);
String[] upwd = cookie.split(",");
for(int i=0;i<upwd.length;i++){
System.out.println(upwd[i]);
}
String aa = "102";
Integer bb = new Integer(aa);
Integer cc = Integer.parseInt(aa);
Integer dd = Integer.valueOf(aa);
System.out.println("dd=" + dd);
String kk = String.valueOf(bb);
String aa = "2016-10-13";
String bb = "08/23/2016";
SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat s2 = new SimpleDateFormat("MM/dd/yyyy");
try {
Date d1 = s1.parse(aa);
Date d2 = s2.parse(bb);
} catch (Exception e) {
e.printStackTrace();
}
//日期转字符
Date today = new Date();
SimpleDateFormat s3 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String pp = s3.format(today);
System.out.println(pp);