This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
I have written this code:
public String[] removeDuplicates(String[] input){
int i;
int j;
int dups = 0;
int array_length = input.length;
for(i=0; i < array_length; i++){
//check whether it occurs more than once
for(j=0; j < array_length; j++){
if (input[i] == input[j] && i != j){
dups++; //set duplicates boolean true
input[j] = null; //remove second occurence
} //if cond
} // for j
} // for i
System.out.println("Category contained " + dups + " duplicates.");
return input;
}
which is supposed to check whether an array of strings contains one or more duplicates. However, even when I define the array like this:
String[] temp = new String[2];
temp[0] = "a";
temp[1] = "a";
The if condition is not "triggered". Did I misunderstand how && works? In my opinion, the program should first check whether the two strings are identical (which they are...) and then whether the two indices are the same. If not, it should perform the operations.
However, the programs seems to think otherwise.
One of the most common mistakes in Java is to assume that a String is an object when its a reference to an object. When you use == you are comparing references, not their contents. This is why .equals() is required to compare their contents.
BTW you can remove duplicates with
public static String[] removeDuplicates(String[] input){
return new HashSet<String>(Arrays.asList(input)).toArray(new String[0]);
}
The == operator in Java checks if the two objects are the same, not that they are equal. Two strings may have identical content, and compare negatively for equality. You need to use equals instead:
if (i != j && input[i].equals(input[j])){
}
If null values are allowed among the input elements, you need to add a null check to your condition to avoid an exception:
if (i != j && input[i] != null && input[i].equals(input[j])){
}
Never use == to check that two objects have the same value. Use equals()
== will check their memory positions (if both objects are in fact only one), equals() is the method that will tell you if both represent the same information.
While working with Strings (and any non-primitive type), remember that == makes a comparation by reference, not by value. Use equals() instead.
if (input[i].equals(input[j]) && i != j){
dups++; //set duplicates boolean true
input[j] = null; //remove second occurence
} //if cond
As a rule of thumb, use == when you want to check if two objects are EXACTLY the same object (you can think of it as if both pointers where referencing the same address).
You should use String.equals for checking string content. The == operator just checks the object reference:
if (input[i] != null && input[i].equals(input[j]) && i != j) {
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
Java newbie here, I'm experimenting with some simple code using NetBeans. The program simply takes in a few strings into an Array of a predetermined length, while not allowing the previously used ones to be added.
String[] AnArray = new String[3];
for (int i=0; i<AnArray.length; i++) {
System.out.println("Insert a string:");
Scanner s = new Scanner(System.in);
String astring = s.next();
for (String AnArray1 : AnArray) {
if (astring.equals(AnArray1)) { /* THIS IS WHERE I CHANGE astring.equals(AnArray1) TO astring == AnArray1 */
System.out.println ("String already used");
break;
}
else
AnArray[i] = astring;
}
}
for (String AnArray1 : AnArray) {
System.out.println(AnArray1);
}
If the string was already used, it should print out a message "String already used" and not add it, leaving the field empty (null).
If I use .equals, it works correctly (well, as I expect it to).
However, if I use '==' it prints out the message, but still adds the (already used) string to the Array.
Note: All advice is appreciated, but I'd be most grateful for an explanation as to HOW/WHY this IS happening (as opposed to what I should do to improve my code).
EDIT: I don't see how this is a duplicate. If someone can paste the relevant part of the answer to my question, I would be grateful. My question is: since the condition is True in BOTH cases (using == or .equals) why does the .equals() follow the break command while == triggers else AS IF it's ALSO false?
I hope the below summary helps you in your case:
use == to compare primitive e.g. boolean, int, char etc, while
use equals() to compare objects in Java.
== return true if two reference are of same object. Result of
equals() method depends on overridden implementation.
For comparing String use equals() instead of == equality
operator.
In Java, == compares the object's references, not the object's contents. That is, with == you check whether the two references point to the same object in memory (which implies that they also have the same contents). With .equals(), however, you check whether the contents of the objects, i.e. the string characters, are the same. Also see e.g. What is the difference between == and equals() in Java?.
Edit: Here's a working example that tries to stick as close to your original code as possible:
String[] AnArray = new String[3];
for (int i=0; i<AnArray.length; i++) {
System.out.println("Insert a string:");
Scanner s = new Scanner(System.in);
String astring = s.next();
boolean alreadyContains = false;
for (int k=0; k<i; k++) {
AnArray1 = AnArray[k];
if (astring.equals(AnArray1)) {
alreadyContains = true;
break;
}
}
if (alreadyContains) {
System.out.println ("String already used");
} else {
AnArray[i] = astring;
}
}
for (String AnArray1 : AnArray) {
System.out.println(AnArray1);
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
In this program below:
public class medianTemp {
public static void main(String[] args){
int length = args.length;
int[] n = new int[length];
n[0] = Integer.parseInt(args[0]);
System.out.print(n[0] + " ");
for (int i = 1; i < length; i++ ){
String c = args[i];
if (c.equals(".")){
n[i] = n[i-1] + 0;
System.out.print(n[i] + " ");
}
if (c.equals("+")){
n[i] = n[i-1] + 1;
System.out.print(n[i] + " ");
}
if (c.equals("-")){
n[i] = n[i-1] - 1;
System.out.print(n[i] + " ");
}
Inside the for loop and inside the if statements. If I use for example args[i] == "." (instead of converting args[i] to string), the code above doesn't work and only the initial integer is displayed. Can someone please tell me why this happens?
== compares objects based on their memory location when they are not primitives. Strings are not primitives, so while the content of 2 String objects may be equal the address of each one in memory is different and == returns false.
In java, String objects (and nearly all objects) need to be compared with equals(). Two String objects may have the same value but be different objects (i.e. duplicates in memory a la new String()). The == comparison compares references.
You just need to use equals for string comparison.
Example from this website : http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/
String a = new String ("a");
String b = new String ("a");
System.out.println (a == b);
It returns false, while the following code returns true.
String a = new String ("a");
String b = new String ("a");
System.out.println (a.equals(b));
== is a relational operator, referring to the relationships that values can have with one another.
Also, the == operator obviously means "Equal To" and only works for raw data types.
These types include double, int, and float. However, the == operator will not work in a boolean expression (only true/false works).
So in sum, it's really how you put your program together to get this operator to work. I recommend reading JAVA programming books such as the "JAVA 2" Series. Hope this helped!
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
(This may be a duplicate, I was not aware of .equals. My apologies.)
I was messing around in Java today when I decided to make a 4 character string generator. I have the program generate every possible combination of characters that I defined. This isn't for a project, I just wanted to see if this was possible. My problem lies with the string checking. I'll post the code first.
String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char[] chars = text.toCharArray();
String name = "Mike";
String pass;
outerLoop:
for (int a = 0; a < chars.length; a ++) {
for (int b = 26; b < chars.length; b++) {
for (int c = 26; c < chars.length; c++) {
for (int d = 26; d < chars.length; d++) {
pass = chars[a]+""+chars[b]+""+chars[c]+""+chars[d];
System.out.println(pass);
if (pass == name){
System.out.print("password");
break outerLoop;
}
}
}
}
}
The nested if will check if pass is equal to Mike. If it is, then it prints password and will break the for loop.
Is pass = chars[a]... the correct way to do this? When I tested it without the if, I had it print out pass and it printed all of the combinations correctly. It did print Mike, but it did not catch in the if.
I also changed the nested for loops so they start with the lower case because the program was taking a while to run when I made minor changes.
if (pass == name){
should be
if (pass.equals(name)){
use String.equals() method to check string equality. == operator simply checks if two reference variables refer to the same object. equals() method checks if two strings are meaningfully equal.
Strings should be compared using equals()
This comes up at least once per day. There should be a "close question" option dedicated to it. Nevertheless, here goes again...
The == operator tests if the two operands are the same instance.
The .equals() method compares the values of the two operands, but only if the class has implemented this method (which String does), otherwise it behaves the same as == (which is how the Object class implements it).
static int findPerson(String n, int NP, Friend[] giftGivers){
int index = 0;
for (int i = 0; i < NP; i++){
if (giftGivers[i].name == n){
index = i;
}
}
return index;
}
I have this code in Java for a method to search through an array of Friends to find the index number of the person with the name input by String n. however i have found that the index number does not set to the index number it is should be. Is it because it is in the if statement?
if (giftGivers[i].name == n) is wrong, use if (giftGivers[i].name.equals(n))
BTW, there is no need to use NP. It's C-style, not necessary (actually, pretty dangerous) in Java. Instead of
for (int i = 0; i < NP; i++),
just say for (int i = 0; i < giftGivers.length; i++)
You need to use equals to compare strings not ==.
== will compare the object references rather than the actual string value.
If you don't care about case, then there is also an equals method that ignores case
(giftGivers[i].name == n){
should be
(giftGivers[i].name.equals(n)){
String/Object comparison should use .equals() instead of ==
== will check for reference equality. equals() check for object equality.
.equals() method checks for equality of two string objects, == operator checks if two refrence variables point to the same String object.
In your case you have to use .equals() method
if (giftGivers[i].name.equals(n))
refer to String API.
Note that if you wanna check if two strings are equal case insensitive use equalsIgnoreCase()
public static int seqSearch(int numRecords, String[] stuName,
double[] stuGpa, String nameKey, double gpaKey)
for(int i = 0; i < numRecords; i++)
if(stuName[i] == nameKey && stuGpa[i] == gpaKey)
return i;
return -1;
So, how would I used an if statement to control this? I'm doing sequential search to find if the name is found in the array and if the gpa is in the array, then it should return the position it was found in (i). But, all it does do is return -1 and print out that none were found.
You have two separate problems here:
You should be comparing strings using the equals() method (or one of it's kin) - otherwise you are comparing whether two strings are the same reference (instance) rather than equivalent sequences of characters.
You should avoid comparing doubles using == as equality for doubles is more nuanced. Check out this paper for more information about why.
See this question about why using == for floating point comparison is a bad idea in java.
Aside from that, I would also mention that your implementation makes the assumption that both stuName and stuGpa are arrays of the same length. This could easily not be the case ... and is probably something worth asserting before you begin iterating over the arrays.
Strings must be compared with .equals in Java, not ==.
if(stuName[i].equals (nameKey) && stuGpa[i] == gpaKey)
You probably want
if (stuName[i].equals(nameKey) && stuGpa[i].equals(gpaKey))
if(stuName[i] == nameKey is unlikely to be right, you are comparing object identities not string content. Try if(stuName[i].equals(nameKey)
You are comparing two Strings.
Strings are immutable.
Please use "equalsIgnoreCase()" or "equals()" to compare Strings
See examples here
http://www.java-samples.com/showtutorial.php?tutorialid=224
An essential problem is that
stuName[i] == nameKey
Is only comparing whether the objects are the same String Object in memory.
You actually want to use nameKey.equals(stuName[i]), to compare the actual string values.
And you might want to use .equalsIgnoreCase for case insensitivity.
The following is correct for the if statement. stuName[i] is a string so compare with .equals. stuGpa[i] is a double so use ==.
if(stuName[i].equals(nameKey_ && stuGpa[i] == gpaKey)
Your problem is not the conditional if statement, but the conditional operator ==. == refers to the pointer value of the object where as the .equals method returns something computed by the object.
Like everyone has said before, switch your == to .equals in this next line:
public static int seqSearch(int numRecords, String[] stuName,
double[] stuGpa, String nameKey, double gpaKey)
for(int i = 0; i < numRecords; i++)
if(stuName[i].equals(nameKey) && stuGpa[i] == gpaKey)
return i;
return -1;
To actually answer the question about the control of the if statement...
I believe what you're doing is fine with the the multiple return statements, BUT...
I personally prefer one entry point and only one exit point for my methods. It always feels dirty to me having multiple exit points.
So, I would consider the following code instead:
public static int seqSearch(int numRecords, String[] stuName, double[] stuGpa, String nameKey, double gpaKey)
int value = -1;
for(int i = 0; i < numRecords; i++) { // Don't forget your braces, they aren't required, but wait until you add a newline and forget to add them...
if(some.boolean().equals(comparison.here())) {
value = i;
break;
}
}
return value;
}
Best of Luck.