JAVA常用类库之String类

String两种实例化方式比较:

String类一旦申明则不可改变,两种实例化方式为:

方式一:使用构造方法String str = new String("hello");
方式二:采用直接赋值的方式:String str = "hello";
  一个字符串其实就是一个String类的匿名对象,匿名对象就是已经开辟了堆内存空间并且可以直接使用的的对象。实际上对于String str = "hello world";而言,其实就是把一个堆中开辟好堆内存空间的使用权交给str对象,其实,使用此方法还有一个好处就是:如果一个字符串已经被另一个名称所引用,则以后再有相同的字符串申声明时,则不会再开辟新的空间,而是直接使用已存在的空间。
  String类的设计使用了一个共享设计模式。 在JVM的底层实际上会自动维护一个对象池(字符串对象池),如果现在采用了直接赋值的模式进行String类对象的实例化操作,那么该实例化对象(字符串)将自动的保存到这个对象池之中,如果下次继续有人使用了直接赋值的模式声明了String类的对象,那么如果此时对象池之中有指定的内容,那么将直接进行引用,如果没有,则开辟新的字符串对象,而后将其保存在对象池之中以供下次使用。(所谓的对象池就是一个对象数组)。 所以结论如下:
   · 直接赋值:只会开辟一块堆内存空间,并且该字符串对象可以保存在对象池中以供下次使用;
   · 构造方法:会开辟两块堆内存空间,一块将称为垃圾,并且不会自动保存在对象池之中,可以使用intern()方法手工入池。
在以后的开发中使用直接赋值的方式。

String中常用的方法有:

序号 方法名称 描述
1 public String(char[] value) 将字符串数组中的所有内容变为字符串
2 public String(char[] value,int offset,int count) 将部分字符数组中的内容变为字符串
3 public char charAt(int index) 取得指定索引位置的字符,索引从0开始
4 pubic char[] toCharArray() 将字符串变为字符数组返回
5 public String(byte [] bytes) 将字节数组变为字符串
6 public String(lbyte [] byte,int offset,int length) 将部分字节数组变为字符串
7 public byte [] getByte() 将字符串以字节数组的形式返回
8 public void byte[] getBytes(String charsetName) throws UnsopportedEncodingException 编码转换处理
9 public boolean equals(String anObject) 区分大小写的比较
10 ppublic boolean equalsIgnorCase(String anotherString) 不区分大小写的转换
11 public int compareTo(anotherString) 比较两个字符串的大小关系
12 public boolean contains(String s) 判断一个字符串是否存在
13 public int indexOf(String str) 从开头查找指定字符串的位置,查找到了返回位置的索引,如果查不到则返回-1
14 public int indexOf(String str,int fromIndex) 从指定位置开始查找子字符串的位置
15 public int lastIndexOf(String str) 从后向前开始查找子字符串的位置
16 public int lastIndexOf(String str,int fromIndex) 从指定位置由后向前查找
17 public boolean startsWith(String prefix) 从头开始判断是否以指定的字符串开头
18 public boolean startsWith(String prefix,int toffset) 从指定位置开始判断是否以指定的字符串开头
19 public boolean endsWith(String suffix) 判断是否以指定的子字符串结尾
20 public String replaceAll(String regex,String replacement) 替换所有的内容
21 public String replaceFirst(String regex,String replacement) 替换首个内容
22 public String[] split(String regex) 将字符串全部拆分
23 public String [] split(String regex,int limit) 将字符串全部拆分,该数组的长度就是limit极限
24 public String subString(int beginIndex) 从指定索引截取到结尾
25 public String subString(int beginIndex,int endIndex) 截取指定索引内的内容
26 public String trim() 去掉字符串左右两边的空格,保留中间的空格
27 public String toUpperCase() 字符串转大写
28 public String toLowerCase() 字符串转小写
29 public String intern() 字符串如对象池
30 public String concat(String str) 字符串连接,相当于+
31 public int length() 取得字符串的长度
32 public loolean isEmpty() 判断是否为空字符串(但不是null,而是长度为0)

你可能感兴趣的:(JAVA)