String
!String 类是Java基础类库中使用量最高的类,必须掌握!
Java没有内置的字符串类型,而是在Java的标准类库中提供了一个预定义类,很自然的叫String。每个用双引号括起来的都是String类的一个实例,举例几种创建字符串的方式:
public static void main(String args[]) {
//1.字符直接量
String name = "Xiaoming";
System.out.println(name);
//print:Xiaoming
//2.new String("");
String address = new String("China Beijing");
System.out.println(address);
//print:China Beijing
//3.字符数组
char[] character = {'a','b','c'};
String charStr = new String(character);
System.out.println(charStr);
//print:abc
//4.返回数组下标组成的字符串,含头不含尾
char[] character1 = {'a','b','c','d'};
String charStr1 = new String(character1,0,2);
System.out.println(charStr1);
//print:ab
//... ... 以上都是String可用的构造方法,其他不常用,不再列举。
}
不可变
//源码
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
... ...
}
String 是 final
修饰的类,所以,字符串一旦创建不可改变,也叫做不可变字符串。就像字符串“Hello”永远包含字符H、e、l、l、o的代码单元序列,而不可能修改其中任任何一个字符,当然通过其他的API也能达到跟修改一样的效果。
比较两个字符串是否相等
!比较字符串是否相同一定不能用 ==,要用equals()方法!
public static void main(String args[]) {
String a = "abc";
String b = "abv";
System.out.println(a.equals(b));//print:false
String c = new String("abc");
System.out.println(a.equals(c));//print:true
}
空字符串和Null串
#1
空字符串也是一个字符串对象,有自己的长度(0)和内容(空),可以用一下代码判单字符串是否是空字符串:
public static void main(String args[]) {
String empty = "";
//1:
if(empty.length() == 0) {}
//或
//2:
if(empty.equals("")) {}
}
#2
空字符串也可以放一个特殊的值,这个值是null
,这表示目前没有任何对象和该变量关联。要检查一个字符串是否为null可以用以下方法检查:
public static void main(String args[]) {
String nullStr = null;
if( nullStr == null) {}
}
#3
有时既要检查一个字符串不为 null
也不是空字符串,这种情况下需要使用以下条件:
public static void main(String args[]) {
String instance = "not null not empty";
if( instance != null && instance.length() != 0) {}
}
子串
通过方法可以从现有的字符串中截取出一个字串,例如:
public static void main(String args[]) {
String say = "Hello word !";
/*
* String substring(int startIndex,int endIndex);
* 返回下标startIndex,endIndex之间的字符串,但不包含endIndex下标的字符。
*/
String substring = say.substring(0,5);
System.out.println(substring);
//Hello
}