Java-字符串问题
2016-03-01 10:16
330 查看
String具有不变性。
当两个字符串都是这样声明的时候,其实这里面它们指向的是同一个内存地址。
String s1 = "hello";
String s2 = "hello";
可以通过下面的两个例子做比较:
例1:
public class StringTestTwo {
public static void main(String[] args){
String str1 = "hello";
String str2 = "hello";
System.out.println(str1.equals(str2));
System.out.println(str1==str2);
}
}
打印输出的结果为:
true
true
例2:
public class StringTestTwo {
public static void main(String[] args){
String str1 = new String("hello");
String str2 = new String("hello");
System.out.println(str1.equals(str2)); //equals 判断两个字符串的内容是否一致
System.out.println(str1==str2); //判断两个字符串的地址是否一致,如果地址一致了那么内容肯定一致
}
}
打印结果为:
true
false
通过这两个例子就应该知道其中的要点了。
还有就是注意,StringBuffer类中的append()方法的使用,请与String类中的concat()方法进行比较。
例1:
public class StringTestTwo {
public static void main(String[] args){
StringBuffer stbu = new StringBuffer("Hello,");
stbu.append("teacher!");
stbu.append(" My name is wangjinghsuai!");
System.out.println(stbu);
}
}
打印的结果为:
Hello,teacher! My name is wangjinghsuai!
例2:
public class StringTestTwo {
public static void main(String[] args){
String str = new String("Hello,");
String str1 = str.concat("teacher!");
System.out.println(str1);
}
}
打印的结果为:
Hello,teacher!
转载文章链接:http://blog.sina.com.cn/s/blog_9759d74d01019ru6.html
当两个字符串都是这样声明的时候,其实这里面它们指向的是同一个内存地址。
String s1 = "hello";
String s2 = "hello";
可以通过下面的两个例子做比较:
例1:
public class StringTestTwo {
public static void main(String[] args){
String str1 = "hello";
String str2 = "hello";
System.out.println(str1.equals(str2));
System.out.println(str1==str2);
}
}
打印输出的结果为:
true
true
例2:
public class StringTestTwo {
public static void main(String[] args){
String str1 = new String("hello");
String str2 = new String("hello");
System.out.println(str1.equals(str2)); //equals 判断两个字符串的内容是否一致
System.out.println(str1==str2); //判断两个字符串的地址是否一致,如果地址一致了那么内容肯定一致
}
}
打印结果为:
true
false
通过这两个例子就应该知道其中的要点了。
还有就是注意,StringBuffer类中的append()方法的使用,请与String类中的concat()方法进行比较。
例1:
public class StringTestTwo {
public static void main(String[] args){
StringBuffer stbu = new StringBuffer("Hello,");
stbu.append("teacher!");
stbu.append(" My name is wangjinghsuai!");
System.out.println(stbu);
}
}
打印的结果为:
Hello,teacher! My name is wangjinghsuai!
例2:
public class StringTestTwo {
public static void main(String[] args){
String str = new String("Hello,");
String str1 = str.concat("teacher!");
System.out.println(str1);
}
}
打印的结果为:
Hello,teacher!
转载文章链接:http://blog.sina.com.cn/s/blog_9759d74d01019ru6.html
相关文章推荐
- Java 异常处理
- java并发编程
- Java反射
- MavenEclipse
- 如何使用Android studio打开eclipse项目
- Java中Properties类的使用
- Java 流(Stream)、文件(File)和IO
- java 常用算法和时间复杂度
- java回调再回首
- Java 方法
- JAVA学习20160301
- JAVA 生成随机数,并根据概率、比率
- Zookeeper实现集群和负载均衡---(5)Zabbix集成Zookeeper示例
- Java并发编程:线程池的使用
- First Missing Positive
- Java多态中重写static函数
- 用Eclipse上传项目到svn服务器
- Java 正则表达式
- Struts2中的ModelDriven机制及其运用
- java中length属性、length()方法、size()方法的区别