当我们实习字符串时,我们确保该字符串的所有使用都指向同一个实例.
我假设底层字符串对象在堆中.
但是,引用变量存储在内存中的哪个位置?
它是否具有与以下相同的行为static- 其中引用存储在permgen中并且仅在类加载器(和应用程序)退出后才使字符串实例可用于gc?
我碰到了这段代码,有些困惑
java.lang.String s = new String("hello");
Run Code Online (Sandbox Code Playgroud)
我不确定将哪个变量s初始化为java.lang.String,以及此vs String hold =“ hello”的目的是什么。我试图浏览一些文档,但找不到任何东西。
我对Java的字符串池有一些了解。网络中的所有示例都明确地创建了变量。但是,如果我从方法返回硬编码的字符串,将会发生什么。是使用字符串池还是为每个方法调用一次又一次创建字符串。我找不到有关此案的任何信息。
我有这样的例子:
public class TestService {
@Override
protected Optional<String> getPayTypeCode() {
return Optional.of("LDV");
}
//...
}
Run Code Online (Sandbox Code Playgroud)
常量示例:
public class TestService {
private static final String PAY_CODE = "LDV";
@Override
protected Optional<String> getPayTypeCode() {
return Optional.of(PAY_CODE);
}
//...
}
Run Code Online (Sandbox Code Playgroud)
我想知道,我的第一种情况是使用字符串池吗?哪种情况会更快?
我对字符串对象的创建感到有点困惑.有人能告诉我,在下面两种情况下会创建多少个String对象?
1)
String s = new String("abc");
s = s + "xyz";
Run Code Online (Sandbox Code Playgroud)
2)
String s = new String("abc");
String s1 = "xyz";
Run Code Online (Sandbox Code Playgroud) 以下代码让我感到困惑,任何人都可以解释为什么这两个测试表现不同?为什么第一个测试中的String比较返回false而第二个测试中的比较返回true?
public class Student {
/**
* Why the string "java" doesn't added to the 'String Pool' by intern() method ?
*/
@Test
public void test1() {
String str1 = new String("ja") + new String("va");
str1.intern();
String str2 = "java";
// Result:false
System.out.println("Result:" + (str1 == str2));
}
/**
* Any other strings will be added to 'String Pool' as expected after intern() is invoked.
*/
@Test
public void test2() {
String str1 = new String("ja1") …Run Code Online (Sandbox Code Playgroud)