This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I don't know what's going on with it. Code below. I'm not trying to get anyone to code the whole thing for me, just don't know what's wrong and would like a little help
private void javabutton1(java.awt.event.ActionEvent evt) {
String testa= new String (jPasswordField2.getPassword());
String testb= new String (jPasswordField3.getPassword());
if (testa.toString() == testb.toString()){
JOptionPane.showMessageDialog(this, "Success");
}
}
When I replace testa.toString() == testb.toString()) with "A" == "A".
The messagebox "Success" is achieved but this entry comparison won't work
Also: The text entered in both jPasswordField2 and jPasswordField3 are the same.
You should try:
testa.equals(testb)
And there is no point of doing this:
String testa = getSomething();
String temp = testa.toString();
// becasue
testa.equals(temp) // always true
If you would have something like:
String a = getSomething();
String b = a;
a == b // now this is true, because they have the same reference/pointer
Use .equals() when comparing strings.
Try with String.equals()
Consider two different reference variables str1 and str2
str1 = new String("abc");
str2 = new String("abc");
if you use the equals()
System.out.println((str1.equals(str2))?"TRUE":"FALSE");
You will get the output as TRUE
if you use ==
System.out.println((str1==str2)?"TRUE":"FALSE");
Now you will get the FALSE as output because both str1 and str2 are pointing to two different objects even though both of them share the same string content. It is because of new String() everytime a new object is created.
Fix your issue by using String.equals(string) like this
String testa= new String (jPasswordField2.getPassword());
String testb= new String (jPasswordField3.getPassword());
if (testa.equals(testb)){
JOptionPane.showMessageDialog(this, "Success");
}
Basically, you should never use == to compare Strings, instead use equals(), so for you:
testa.equals(testb)
The difference is that == is used to compare references, it is saying: "Do these two String references point to the same String object in memory?"...this is unpredictable due to how Java stores Strings, which basically accounts for why "A" == "A" returns true...not something to go into here.
The equals() method is more what you would expect, in the Java Class String, this method basically checks whether or not each character in the String is the same, and returns true if they do.
If it's an object, you should use equals() to compare, if its a primitive data type, such as an int (or you are checking if a reference is null) then use ==.
While I agree with Takendarkk that answer duplicate questions promotes their repeated posting, I think there is at least one issue that should be noted which has not been mentioned. StephenTG asked a poignant question in the comments: "Why do you need to convert your Strings to Strings?"
Given the name of your variables, if you are indeed using the swing JPasswordField, then the getPassword() method returns a char[] array. You don't need to convert this to a string, you can compare them using java.utils.Arrays#equals(char[]. char[]) to get the result you desire. Your code might look like this:
private void javabutton1(java.awt.event.ActionEvent evt) {
char[] testa = jPasswordField2.getPassword();
char[] testb = jPasswordField3.getPassword();
if (Arrays.equals(testa, testb)){
JOptionPane.showMessageDialog(this, "Success");
}
}
Related
I was asked to predict the output of this code :
String party1 = "party";
String party2= "PARTY".toLowerCase();
if(party1==party2){
System.out.println("EQUAL");
}else{
System.out.println("NOT EQUAL");
}
I thought the result of toLowerCase() would be interned automatically and hence the same reference to party1 would be returned, but I was wrong since the code ouptuts "NOT EQUAL".
Does toLowerCase() (toUpperCase() as well) return a new String ?
Edit : I am not using == to compare Strings, I just want to know about the behaviour of toLowerCase() method
If the result of any String operation were internalised, the pool would be growing extremely and unnecessarily rapidly. Any intermediate action on a Spring would result in a new element in the pool. It would be beneficial for a VERY small number of cases within a VERY specific domain. Therefore, it's not the default policy and that's why intern() exists.
String party1 = "party";
String party2 = "PARTY".toLowerCase().intern();
System.out.println(party1 == party2 ? "EQUAL" : "NOT EQUAL");
There is nothing special about toLowerCase(): any String method would return a new String since Strings are immutable.
Answer is in String.toLowerCase() method itself.. as you can check by your self toLowerCase() method returns a new lowercase string (a new String object) and == checks for the object reference and returns true if they are same which are different in your case.. that's why its returning false.. hope you get it.
public String toLowerCase(Locale locale) {
if (locale == null) {
throw new NullPointerException();
}
........
............
return new String(result, 0, len + resultOffset);
}
Strings are immutable.Generally whenever we try to modify a string a new string literal is created in the Constant literal pool and a new reference to it is returned.Although "party" and "PARTY".toLowerCase() have same values i.e. party but in constant pool they refer to two different literals and have two different references. By using == operator you are comparing references and not the values.Since they have different references it prints NOT Equal.Try using party1.equals(party2) and it will print EQUAL as it compares content and not reference.
As of my knowledge on any operations on string it will duplicate the string so never use '==' instead use .equals()
String party1 = "party";
String party2= "PARTY".toLowerCase();
System.out.println(party1);
System.out.println(party2);
if(party1.equals(party2)){
System.out.println("EQUAL");
}else{
System.out.println("NOT EQUAL");
}
This gave the result equal
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Actually am testing the functionality of Scanner.
I have a very simple program which has a String variable which contains "abc".Then am reading other String(value "abc") from Scanner using next() method(even i tried with nextLine()).
Then am comparing using the ==, to check whether they are equal according to ==(i know i can compare with equals method which is working as excepted), the strange thing is that it is returning false when i compare using == , even though their hashcode() s are equal and equals() method returning true..
import java.util.Scanner;
public class Tester1234 {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String str1="abc";
System.out.println("Eneter abc");
String str2=scanner.next();
System.out.println("str1.hascode()"+str1.hashCode()+"\tstr2.hascode()"+str2.hashCode()+"\tstr2.equals(str1)"+str1.equals(str2));
if(str1==str2)
{
System.out.println("equal");
}
else
{
System.out.println("not equal");
}
}
}
I want to know why it is behaving like this ??
Thanks...!
You are wrong as for the statement that
i know Strings with same content will point to same object in StringPool...
It is true as for literals whitch are hardcoded strings in the code. Compiler creates string pool on compile time and use existing references. But if you are building string on runtime using StringBuilder/StringBuffer (what i belive the Scanner does internally) you are NOT USING entities in string pool, thats why you will get two different objects (references) for the same string content. Workaround for such behaviour is to use intern() however it is performance hit, as interned strings are goint into permgen, and will not be garbage collected.
If we create an String like this...
String str1 = "abc";
object str1 created in String-Pool, and if we create
String str2 = new String("abc");
then, it created in heap, means another new Object.
this is the reason that your condition if(str1==str2) returns false, because these both are different objects.
But there hashcode is equal because both are "abc", so equals method returns true.
you are right that hashcode and equals returning true, hence it will return true for str2.equals(str1).
But str2 is new String and hence it is having difference memory address thats why it will not work for str2==str1. here you are comparing memory address and not content of the string.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
thank you for taking the time to read this. Sorry if my question is dumb, I tried searching but couldn't quite figure out why I'm having this problem. I was trying to test some code for another application, but I'm having issues. Perhaps I just don't understand arrays properly.
I have a method named halfStepUp in a class named Transpose that, for testing purposes, should return "c#" if given "c" and "d#" if given "d". This is the code:
public class Transpose{
public static String halfStepUp(String note){
String n = null;
if (note == "c") n = "c#";
if (note == "d") n = "d"#;
return n;
}
}
I have the following code in my main method:
String [] scale = new String[2];
scale[0] = "c";
scale[1] = "d";
System.out.println(Transpose.halfStepUp(scale[0]));
This prints "null." What am I doing wrong?
I know the method works because if I use
System.out.println(Transpose.halfStepUp("c"));
It works fine. The solution is probably embarrassingly easy but I couldn't find a good way to word it when searching for help.
Thanks again for reading, and any answers are greatly appreciated!
To add a little more info to the answers you already got:
Java has two types of storage. One is the stack, which includes variable names and their values. One is the heap, that is just a huge collections of free-floating objects.
Now, if you're working with primitive types (like int, boolean or char), assigning a variable like
int myInt = 1;
pushes that variable on thje stack - the name is myInt, the value is 1.
If you, however, have an object (like strings are), assigning a variable does a little bit more.
String myString = "Hey!";
now creates an object (instance of String) somewhere on the heap. It has no name there, only some address in the memory where it can be found.
In addition to that, it pushes a variable on the stack. The name is myString - and the value is the address of the object on the heap.
So why is this relevant to comparing variables? Because == compares values of variables. ON THE STACK, that is. SO if you compare primitive types, everything works as expected. But if you're comparing Objects, == still only compares the values of the variables - which is, in that case, the addresses to the objects. If the addresses are the same, it returns true. That does mean, both variables point to the same object. If the addresses are different, == returns false., Without ever looking at the heap, where the objects really are.
An example:
String a = new String("Hey!");
String b = a;
if (a == b) System.out.println("true");
else System.out.println("false");
will echo "true" - because both variables contain the same object.
String a = new String("Hey!");
String b = new String("Hey!");
if (a == b) System.out.println("true");
else System.out.println("false");
will echo "false" - because you have two objects on the heap now, and a points to the one, while b points to the other. So while the contents of both objects may be the same, the contents of a and b on the stack are different.
Therefore, to compare any object, always use .equals() if you want to compare contents, not instance-equality.
[Addendum]:
With strings, this is even more complicated. As you already found out already,
String a = "Hey!"; // mention the difference to the example above:
String b = "Hey!"; // I did NOT use the `String()` cosntructor here!
if (a == b) System.out.println("true");
else System.out.println("false");
will actually give you "true". Now why is THAT? One might think that we still create two objects. But actually, we are not.
String is immutable. That means, once a String has been created, it cannot be modified. Ever. Don'T believe that? Take a look!
String myString = "test"; // we create one instance of String here
myString += " and more"; // we create another instance of String (" and more")
// and append that. Did we modify the instance stored in
// myString now? NO! We created a third instance that
// contains "test and more".
Therefore, there is no need to create additional instances of String with the same content - which increases performance, as Strings are widely used, in masses, so we want to have as few of them as possible.
To archive that, the JVM maintains a list of String Objects we already created. And every time we write down a String literal (that is something like "Hey!"), it looks in that lists and checks if we already created an instance that has that value. If so, it returns a pointer to that exact same instance instead of creating a new one.
And THIS is, why "Hey!" == "Hey!" will return true.
You should use the .equals() method when comparing strings, not ==. The == operator compares the references to see if they are pointing to the same underlying object. The .equals() method, compares the underlying objects to each other to see if they are semantically equivalent.
Try this instead: (edited from comments)
public class Transpose{
public static String halfStepUp(String note){
String n = null;
if ("c".equals(note)) n = "c#"; //using .equals as a string comparison
if ("d".equals(note)) n = "d#"; //not "d"#
return n;
}
}
The glitch is in this line:
if (note == "c") n = "c#";
This compares strings by address, not by value. Try using "c".equals(note) instead.
class Transpose{
public static String halfStepUp(String note){
String n = null;
if (note == "c") n = "c#";
if (note == "d") n = "d#";
return n;
}
}
public class TransposeTest {
public static void main(String... args) {
String [] scale = new String[2];
scale[0] = "c";
scale[1] = "d";
System.out.println(Transpose.halfStepUp(scale[0]));
}
}
working code
As it is stated the == operator compares object references to check if they are referring to the same object on a heap. If so why am I getting the "Equal" for this piece of code?
public class Salmon {
public static void main(String[] args) {
String str1 = "Str1";
String str2 = "Str1";
if (str1 == str2) {
System.out.println("Equal");
} else {
System.out.println("Not equal");
}
}
}
The program will print Equal. (At least using the Sun Hotspot and suns Javac.) Here it is demonstrated on http://ideone.com/8UrRrk
This is due to the fact that string-literal constants are stored in a string pool and string references may be reused.
Further reading:
What is String literal pool?
String interning
This however:
public class Salmon {
public static void main(String[] args) {
String str1 = "Str1";
String str2 = new String("Str1");
if (str1 == str2) {
System.out.println("Equal");
} else {
System.out.println("Not equal");
}
}
}
Will print Not equal since new is guaranteed to introduce a fresh reference.
So, rule of thumb: Always compare strings using the equals method.
Java stores all Strings in a string table internally during a run. The references to the two strings are identical because in memory they're stored in the same place. Hence, Equal.
Your statement is right, that == compares object references. Try the same thing with any other class but Strings and you won't get the same result.
This code won't print Equal.
But if the two strings were the same, this case would be special.
Now that you've updated your code, it is the case :
A simple (but not totally exact) explanation is that the compiler see that the two strings are the same and do something like :
String str1 = "Str1";
String str2 = str1;
What really happens here is that the compiler will see the literal string and put it in the "String literal pool".
As a String can't be modified (it's immutable) the literal values of Strings (those found during compilation) are put in a "pool".
This way, if two different literal strings which have the same content (like in this particular case), the memory isn't wasted to store "Str1" and "Str1" two times.
People, you are forgetting that the process of placing literal strings in the pool is called "interning". The class String has a method called intern(). This method puts any string into the pool, even if it is not in the pool initially (not literal). This means that code like this:
String a = "hello";
String b = new String("hello");
b = b.intern();
System.out.println(a == b);
will print "true".
Now, why would someone need this? As you can imagine, string comparison a.equals(b) might take a long time if strings are the same length but different close to the end.
(Just look at the .equals() source code.).
However, comparing references directly is the same as comparing integers (pointers in C speak), which is near instant.
So, what does this give you? Speed. If you have to compare the same strings many, many times, your program performance will benefit tremendously if you intern these strings. If however you are going to compare strings only once, there will be no performance gain as the interning process itself uses equals().
I hope this explains this.
thanks
Comments above have summed it up pretty well.
I don't have a Java environment handy, but attempting the following should clarify things for you (hopefully this works as I anticipate).
String str1 = "Str1";
String str2 = "Str"; str2 += "1";
Should now print Not equal
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
This code separates a string into tokens and stores them in an array of strings, and then compares a variable with the first home ... why isn't it working?
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");
}
}
Use the string.equals(Object other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.
if (usuario.equals(datos[0])) {
...
}
NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos array otherwise you'll get an array-out-of-bounds exception.
Meet Jorman
Jorman is a successful businessman and has 2 houses.
But others don't know that.
Is it the same Jorman?
When you ask neighbours from either Madison or Burke streets, this is the only thing they can say:
Using the residence alone, it's tough to confirm that it's the same Jorman. Since they're 2 different addresses, it's just natural to assume that those are 2 different persons.
That's how the operator == behaves. So it will say that datos[0]==usuario is false, because it only compares the addresses.
An Investigator to the Rescue
What if we sent an investigator? We know that it's the same Jorman, but we need to prove it. Our detective will look closely at all physical aspects. With thorough inquiry, the agent will be able to conclude whether it's the same person or not. Let's see it happen in Java terms.
Here's the source code of String's equals() method:
It compares the Strings character by character, in order to come to a conclusion that they are indeed equal.
That's how the String equals method behaves. So datos[0].equals(usuario) will return true, because it performs a logical comparison.
It's good to notice that in some cases use of "==" operator can lead to the expected result, because the way how java handles strings - string literals are interned (see String.intern()) during compilation - so when you write for example "hello world" in two classes and compare those strings with "==" you could get result: true, which is expected according to specification; when you compare same strings (if they have same value) when the first one is string literal (ie. defined through "i am string literal") and second is constructed during runtime ie. with "new" keyword like new String("i am string literal"), the == (equality) operator returns false, because both of them are different instances of the String class.
Only right way is using .equals() -> datos[0].equals(usuario). == says only if two objects are the same instance of object (ie. have same memory address)
Update: 01.04.2013 I updated this post due comments below which are somehow right. Originally I declared that interning (String.intern) is side effect of JVM optimization. Although it certainly save memory resources (which was what i meant by "optimization") it is mainly feature of language
The == operator checks if the two references point to the same object or not.
.equals() checks for the actual string content (value).
Note that the .equals() method belongs to class Object (super class of all classes). You need to override it as per you class requirement, but for String it is already implemented and it checks whether two strings have the same value or not.
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.
equals() function is a method of Object class which should be overridden by programmer. String class overrides it to check if two strings are equal i.e. in content and not reference.
== operator checks if the references of both the objects are the same.
Consider the programs
String abc = "Awesome" ;
String xyz = abc;
if(abc == xyz)
System.out.println("Refers to same string");
Here the abc and xyz, both refer to same String "Awesome". Hence the expression (abc == xyz) is 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");
Here abc and xyz are two different strings with the same content "Hello World". Hence here the expression (abc == xyz) is false where as (abc.equals(xyz)) is true.
Hope you understood the difference between == and <Object>.equals()
Thanks.
== tests for reference equality.
.equals() tests for value equality.
Consequently, if you actually want to test whether two strings have the same value you should use .equals() (except in a few situations where you can guarantee that two strings with the same value will be represented by the same object eg: String interning).
== is for testing whether two strings are the same Object.
// 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
It is important to note that == is much cheaper than equals() (a single pointer comparision instead of a loop), thus, in situations where it is applicable (i.e. you can guarantee that you are only dealing with interned strings) it can present an important performance improvement. However, these situations are rare.
Instead of
datos[0] == usuario
use
datos[0].equals(usuario)
== compares the reference of the variable where .equals() compares the values which is what you want.
Let's analyze the following Java, to understand the identity and equality of Strings:
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");
}
When the first line of code String str1 = "Hello world." executes, a string \Hello world."
is created, and the variable str1 refers to it. Another string "Hello world." will not be created again when the next line of code executes because of optimization. The variable str2 also refers to the existing ""Hello world.".
The operator == checks identity of two objects (whether two variables refer to same object). Since str1 and str2 refer to same string in memory, they are identical to each other. The method equals checks equality of two objects (whether two objects have same content). Of course, the content of str1 and str2 are same.
When code String str3 = new String("Hello world.") executes, a new instance of string with content "Hello world." is created, and it is referred to by the variable str3. And then another instance of string with content "Hello world." is created again, and referred to by
str4. Since str3 and str4 refer to two different instances, they are not identical, but their
content are same.
Therefore, the output contains four lines:
Str1 == str2
Str1 equals str2
Str3! = str4
Str3 equals str4
You should use string equals to compare two strings for equality, not operator == which just compares the references.
It will also work if you call intern() on the string before inserting it into the array.
Interned strings are reference-equal (==) if and only if they are value-equal (equals().)
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.intern();
i++;
}
//System.out.println (usuario);
if(datos[0]==usuario) {
System.out.println ("WORKING");
}
Generally .equals is used for Object comparison, where you want to verify if two Objects have an identical value.
== for reference comparison (are the two Objects the same Object on the heap) & to check if the Object is null. It is also used to compare the values of primitive types.
== operator compares the reference of an object in Java. You can use string's equals method .
String s = "Test";
if(s.equals("Test"))
{
System.out.println("Equal");
}
If you are going to compare any assigned value of the string i.e. primitive string, both "==" and .equals will work, but for the new string object you should use only .equals, and here "==" will not work.
Example:
String a = "name";
String b = "name";
if(a == b) and (a.equals(b)) will return true.
But
String a = new String("a");
In this case if(a == b) will return false
So it's better to use the .equals operator...
The == operator is a simple comparison of values.
For object references the (values) are the (references). So x == y returns true if x and y reference the same object.
I know this is an old question but here's how I look at it (I find very useful):
Technical explanations
In Java, all variables are either primitive types or references.
(If you need to know what a reference is: "Object variables" are just pointers to objects. So with Object something = ..., something is really an address in memory (a number).)
== compares the exact values. So it compares if the primitive values are the same, or if the references (addresses) are the same. That's why == often doesn't work on Strings; Strings are objects, and doing == on two string variables just compares if the address is same in memory, as others have pointed out. .equals() calls the comparison method of objects, which will compare the actual objects pointed by the references. In the case of Strings, it compares each character to see if they're equal.
The interesting part:
So why does == sometimes return true for Strings? Note that Strings are immutable. In your code, if you do
String foo = "hi";
String bar = "hi";
Since strings are immutable (when you call .trim() or something, it produces a new string, not modifying the original object pointed to in memory), you don't really need two different String("hi") objects. If the compiler is smart, the bytecode will read to only generate one String("hi") object. So if you do
if (foo == bar) ...
right after, they're pointing to the same object, and will return true. But you rarely intend this. Instead, you're asking for user input, which is creating new strings at different parts of memory, etc. etc.
Note: If you do something like baz = new String(bar) the compiler may still figure out they're the same thing. But the main point is when the compiler sees literal strings, it can easily optimize same strings.
I don't know how it works in runtime, but I assume the JVM doesn't keep a list of "live strings" and check if a same string exists. (eg if you read a line of input twice, and the user enters the same input twice, it won't check if the second input string is the same as the first, and point them to the same memory). It'd save a bit of heap memory, but it's so negligible the overhead isn't worth it. Again, the point is it's easy for the compiler to optimize literal strings.
There you have it... a gritty explanation for == vs. .equals() and why it seems random.
#Melkhiah66 You can use equals method instead of '==' method to check the equality.
If you use intern() then it checks whether the object is in pool if present then returns
equal else unequal. equals method internally uses hashcode and gets you the required result.
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
}
}
The .equals() will check if the two strings have the same value and return the boolean value where as the == operator checks to see if the two strings are the same object.
Someone said on a post higher up that == is used for int and for checking nulls.
It may also be used to check for Boolean operations and char types.
Be very careful though and double check that you are using a char and not a String.
for example
String strType = "a";
char charType = 'a';
for strings you would then check
This would be correct
if(strType.equals("a")
do something
but
if(charType.equals('a')
do something else
would be incorrect, you would need to do the following
if(charType == 'a')
do something else
a==b
Compares references, not values. The use of == with object references is generally limited to the following:
Comparing to see if a reference is null.
Comparing two enum values. This works because there is only one object for each enum constant.
You want to know if two references are to the same object
"a".equals("b")
Compares values for equality. Because this method is defined in the Object class, from which all other classes are derived, it's automatically defined for every class. However, it doesn't perform an intelligent comparison for most classes unless the class overrides it. It has been defined in a meaningful way for most Java core classes. If it's not defined for a (user) class, it behaves the same as ==.
Use Split rather than tokenizer,it will surely provide u exact output
for E.g:
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");
}
After this I am sure you will get better results.....