A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 杨超11 初级黑马   /  2019-3-11 17:23  /  641 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

初始化:

一般由String声明的字符串,长度是不可变的,这也是它与StringBuffer和StringBuilder最直观的一个区别。一般初始化方式:String s = "hello world";经过这条语句,JVM的栈内存中产生一个s变量,堆内存中产生hello world字符串对象。s指向了hello world的地址。像上面这种方式产生的字符串属于直接量字符串对象,JVM在处理这类字符串的时候,会进行缓存,产生时放入字符串池,当程序需要再次使用的时候,无需重新创建一个新的字符串,而是直接指向已存在的字符串。看下面程序:
package heima.string;

public class StringTest {

        public static void main(String[] args) {
                String s = "hello world";
                String s2 = "hello world";
                System.out.println(s == s2);
        }
}
该程序输出:true 因为s和s2都指向了hello world字符串,他们的地址是同一个。 我们常说,String的一个很大的特点,就是它是一个“不可变的字符串”,就是说,当一个String对象完成创建后,该对象的内容就固定下来了,但是为什么还会有下面这种情况呢?
package com.xtfggef.string;

public class StringInit {

        public static void main(String[] args) {
                String str = "I like";//---------1--------
                System.out.println(System.identityHashCode(str));
                str = str + "java";//--------2---------
                System.out.println(System.identityHashCode(str));
        }
}
该程序输出:

14576877
12677476

说明:str似乎是变了,这是为什么呢?其实是这样的:str只是一个引用变量,当程序执行完1后,str指向“I like”。当程序执行完2之后,连接运算符会将两个字符串连在一起,并且让str指向新的串:"I like java",所以,从这里应该可以看得出来,最初的对象确实没有改变,只是str所指向的对象在不断改变。

String对象的另一种初始化方式,就是采用String类提供的构造方法进行初始化。String类提供了16种构造方法,常用的有五种:

String() --------- 初始化一个String对象,表示一个空字符序列

String(String value) --------- 利用一个直接量创建一个新串

String(char[] value) --------- 利用一个字符数组创建

String(char[] value,int offset,int count) --------- 截取字符数组,从offset开始count个字符创建

String(StringBuffer buffer) --------- 利用StringBuffer创建

形如:

String s = new String();

String s1 = new String(“hello”);

char[] c = {'h','e','l','l','o'};

String s2 = new String(c);

'String s3 = new String(c,1,3);

以上就是String类的基本初始化方法。

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马