Java String.equals与==

Java String.equals与==,java,string,Java,String,这段代码将一个字符串分割成令牌,并将它们存储在字符串数组中,然后将一个变量与第一个主变量进行比较。。。为什么不起作用 public static void main(String...aArguments) throws IOException { String usuario = "Jorman"; String password = "14988611"; String strDatos = "Jorman 14988611"; StringTokeniz

这段代码将一个字符串分割成令牌,并将它们存储在字符串数组中,然后将一个变量与第一个主变量进行比较。。。为什么不起作用

public static void main(String...aArguments) throws IOException {

    String usuario = "Jorman";
    String password = "14988611";

    String strDatos = "Jorman 14988611";
    StringTokenizer tokens = new StringTokenizer(strDatos, " ");
    int nDatos = tokens.countTokens();
    String[] datos = new String[nDatos];
    int i = 0;

    while (tokens.hasMoreTokens()) {
        String str = tokens.nextToken();
        datos[i] = str;
        i++;
    }

    //System.out.println (usuario);

    if ((datos[0] == usuario)) {
        System.out.println("WORKING");
    }
}
使用该函数比较字符串,而不是使用
=
运算符

函数检查字符串的实际内容,
=
操作符检查对对象的引用是否相等。请注意,字符串常量通常是“插入”的,因此具有相同值的两个常量实际上可以与
=
进行比较,但最好不要依赖于此

if (usuario.equals(datos[0])) {
    ...
}
注意:比较是在“usuario”上进行的,因为这在代码中保证为非null,尽管您仍然应该检查
datos
数组中是否确实有一些令牌,否则您将得到一个数组越界异常。

而不是

datos[0] == usuario
使用


=
比较变量的引用,其中
.equals()
比较您想要的值。

您应该使用它来比较两个字符串是否相等,而不是只比较引用的运算符==。

注意,在某些情况下,使用“==”运算符可以得到预期的结果,因为java处理字符串的方式-字符串文本在编译过程中被插入(请参见
string.intern()
),所以当您在两个类中编写例如
“hello world”
,并将这些字符串与“==”进行比较时,您可以得到结果:true,根据;当第一个字符串是字符串文字(即通过
“i am string literal”
定义)而第二个字符串是在运行时构造的,即使用“new”关键字(如
new string(“i am string literal”)
)比较相同的字符串(如果它们具有相同的值),则
=
(相等)运算符返回false,因为它们都是
String
类的不同实例

唯一正确的方法是使用
.equals()
->
datos[0]。equals(通常是)
==
仅当两个对象是对象的同一实例(即具有相同的内存地址)时才表示


更新:2013年4月1日我更新了这篇文章,下面的评论在某种程度上是正确的。最初我声明interning(String.intern)是JVM优化的副作用。虽然它确实节省了内存资源(这就是我所说的“优化”),但它是语言的主要功能,如果在将字符串插入数组之前对其调用
intern()
,它也会起作用。 当且仅当内部字符串的值相等(
equals()
)时,它们才是引用相等的(
==

equals()<代码>字符串
类重写它以检查两个字符串是否相等,即内容是否相等,而不是引用是否相等

=
运算符检查两个对象的引用是否相同

以这些项目为例

String abc = "Awesome" ;
String xyz =  abc;

if(abc == xyz)
     System.out.println("Refers to same string");
这里的
abc
xyz
都是指相同的
字符串
“Awesome”
。因此表达式
(abc==xyz)
true

String abc = "Hello World";
String xyz = "Hello World";

if(abc == xyz)
    System.out.println("Refers to same string");
else
    System.out.println("Refers to different strings");

if(abc.equals(xyz))
     System.out.prinln("Contents of both strings are same");
else
     System.out.prinln("Contents of strings are different");
这里的
abc
xyz
是两个内容相同的不同字符串
“Hello World”
。因此这里的表达式
(abc==xyz)
false
,其中as
(abc.equals(xyz))
true

String abc = "Hello World";
String xyz = "Hello World";

if(abc == xyz)
    System.out.println("Refers to same string");
else
    System.out.println("Refers to different strings");

if(abc.equals(xyz))
     System.out.prinln("Contents of both strings are same");
else
     System.out.prinln("Contents of strings are different");
希望您理解
=
.equals()


谢谢。

让我们分析以下Java,以了解字符串的标识和相等性:

public static void testEquality(){
    String str1 = "Hello world.";
    String str2 = "Hello world.";

    if (str1 == str2)
        System.out.print("str1 == str2\n");
    else
        System.out.print("str1 != str2\n");

    if(str1.equals(str2))
        System.out.print("str1 equals to str2\n");
    else
        System.out.print("str1 doesn't equal to str2\n");

    String str3 = new String("Hello world.");
    String str4 = new String("Hello world.");

    if (str3 == str4)
        System.out.print("str3 == str4\n");
    else
        System.out.print("str3 != str4\n");

    if(str3.equals(str4))
        System.out.print("str3 equals to str4\n");
    else
        System.out.print("str3 doesn't equal to str4\n");
}
当第一行代码
String str1=“Hello world.”
执行时,一个字符串
\Hello world。”
已创建,变量str1
引用它。另一个字符串
“Hello world。”
由于优化而在执行下一行代码时不会再次创建。变量
str2
也引用现有的
“Hello world”。

操作符
==
检查两个对象的标识(两个变量是否引用同一个对象)。由于
str1
str2
在内存中引用相同的字符串,因此它们彼此相同。方法
equals
检查两个对象的相等性(两个对象是否具有相同的内容)。当然,
str1
str2
的内容是相同的

当code
String str3=new String(“Hello world”)
执行时,将创建内容为
“Hello world.”
的字符串的新实例,并由变量
str3
引用。然后再次创建另一个内容为“Hello world”的字符串实例。
,并由
str4
。由于
str3
str4
引用了两个不同的实例,因此它们并不相同,但它们的 内容相同

因此,输出包含四行:

Str1 == str2

Str1 equals str2

Str3! = str4

Str3 equals str4

=
运算符比较Java中对象的引用。您可以使用字符串的
equals
方法

String s = "Test";
if(s.equals("Test"))
{
    System.out.println("Equal");
}

如果要比较字符串的任何赋值,即基本字符串,则“==”和.equals都将起作用,但对于新字符串对象,应仅使用.equals,此处“==”将不起作用

例如:

String a = "name";

String b = "name";
如果(a==b)
(a.equals(b))
将返回true

但是

在这种情况下,
if(a==b)
将返回
false


因此,最好使用
.equals
运算符…

使用拆分而不是标记器,它肯定会提供精确的输出 例如:

string name=“Harry”;
字符串salary=“25000”;
字符串namsal=“Harry 25000”;
字符串[]s=namsal.split(“”);

for(int i=0;i通常
.equals
用于
对象
比较,您要验证两个
对象
是否具有相同的值

==String a = "name";

String b = "name";
String a = new String("a");
string name="Harry";
string salary="25000";
string namsal="Harry 25000";
string[] s=namsal.split(" ");
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
if(s[0].equals("Harry"))
{
System.out.println("Task Complete");
}
public class Demo
{
  public static void main(String[] args)
  {
              String str1 = "Jorman 14988611";
    String str2 = new StringBuffer("Jorman").append(" 14988611").toString();
    String str3 = str2.intern();
    System.out.println("str1 == str2 " + (str1 == str2));           //gives false
    System.out.println("str1 == str3 " + (str1 == str3));           //gives true
    System.out.println("str1 equals str2 " + (str1.equals(str2)));  //gives true
    System.out.println("str1 equals str3 " + (str1.equals(str3)));  //gives true
  }
}
String foo = "hi";
String bar = "hi";
if (foo == bar) ...
// These two have the same value
new String("test").equals("test") ==> true 

// ... but they are not the same object
new String("test") == "test" ==> false 

// ... neither are these
new String("test") == new String("test") ==> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object
"test" == "test" ==> true 

// concatenation of string literals happens at compile time resulting in same objects
"test" == "te" + "st"  ==> true

// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) ==> false
    String strType = "a";
    char charType = 'a';
    if(strType.equals("a")
        do something
    if(charType.equals('a')
        do something else
    if(charType == 'a')
         do something else
The == operator checks if the two references point to the same object or not.
.equals() checks for the actual string content (value).
Case1)
String s1 = "Stack Overflow";
String s2 = "Stack Overflow";
s1 == s1;      // true
s1.equals(s2); // true
Reason: String literals created without null are stored in the string pool in the permgen area of the heap. So both s1 and s2 point to the same object in the pool.
Case2)
String s1 = new String("Stack Overflow");
String s2 = new String("Stack Overflow");
s1 == s2;      // false
s1.equals(s2); // true
Reason: If you create a String object using the `new` keyword a separate space is allocated to it on the heap.