differet way to creat String
1,use new operator:
String s=new String("Hello");
2,a short one:
String s="Hello";
两种方法当用于字符串时有相同的结果,但不用NEW关键字会创建JAVA字符串池中指向同一个字符串的指针。
字符串池是JAVA存储资源的一种方法。
以下程序用于检验:
public class DifferentWayToCreatString
{
public static void main(String args[])
{
String s = "Hello";
String s2 = "Hello";
if (s == s2)
{
System.out.println("Equal without new operator");
}
String t = new String("Hello");
String u = new String("Hello");
if (t == u)
{
System.out.println("Equal with new operator");
}
}
}
//输出结果Equal without new operator
String s=new String("Hello");
2,a short one:
String s="Hello";
两种方法当用于字符串时有相同的结果,但不用NEW关键字会创建JAVA字符串池中指向同一个字符串的指针。
字符串池是JAVA存储资源的一种方法。
以下程序用于检验:
public class DifferentWayToCreatString
{
public static void main(String args[])
{
String s = "Hello";
String s2 = "Hello";
if (s == s2)
{
System.out.println("Equal without new operator");
}
String t = new String("Hello");
String u = new String("Hello");
if (t == u)
{
System.out.println("Equal with new operator");
}
}
}
//输出结果Equal without new operator
本文探讨了Java中创建字符串的两种不同方法:使用new关键字与直接赋值,并通过示例程序展示了这两种方法如何影响字符串池中的引用。直接赋值的方式使得字符串指向同一个对象,而使用new则创建新的对象。





