这段代码将一个字符串分离为令牌,并将它们存储在一个字符串数组中,然后将一个变量与第一个home…为什么它不工作?
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");
}
}
The == operator checks if the two references point to the same object or not.
.equals() checks for the actual string content (value).
注意.equals()方法属于类Object(所有类的超类)。您需要根据您的类需求重写它,但是对于String,它已经实现,并且它检查两个字符串是否具有相同的值。
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.
有人在更高的帖子上说==用于int和检查null。
它也可以用来检查布尔运算和字符类型。
但是要非常小心,仔细检查你使用的是char类型而不是String类型。
例如
String strType = "a";
char charType = 'a';
对于字符串,您将检查
这是正确的
if(strType.equals("a")
do something
but
if(charType.equals('a')
do something else
是不正确的,你需要做下面的事情
if(charType == 'a')
do something else
如果你要比较字符串的任何赋值,即原始字符串,"=="和.equals都可以,但对于新的字符串对象,你应该只使用.equals,在这里"=="将不起作用。
例子:
String a = "name";
String b = "name";
If (a == b) and (a.equals(b))将返回true。
But
String a = new String("a");
在这种情况下,if(a == b)将返回false
所以最好使用.equals操作符…