This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
I'm using String.valueOf to convert char to string. But the return value seems not exactly same as a string of the same letter. Codes below:
String myString = "s";
char myChar = 's';//both string and char are assigned as letter 's'
String stringFromChar = String.valueOf(myChar);
if (myString == stringFromChar) {
out.println("equal");
} else {
out.println("not equal");
}
Every time it prints not equal. Please help, thanks! :)
== compare the reference, not the actual value. You must use equals to compare the value.
Read this article if you don't understand it's clear and simple.
NEVER DO THIS AGAIN!!! PROMISE ME!!! =P
When comparing strings always, always, always use the equals method. See Below!
String myString = "s";
char myChar = 's';//both string and char are assigned as letter 's'
String stringFromChar = String.valueOf(myChar);
if (myString.equals(stringFromChar)) {
System.out.println("equal");
} else {
System.out.println("not equal");
}
}
what happens when converting char to string?
Well, you are using the String.valueOf(char) method, whose javadoc does not say how it does the conversion. But the behaviour you are seeing strongly suggests that the JVM you are using creates a new String object each time you call the method.
But you should depend on this happening.
The bottom line is that you should always use the equals method to compare strings. Comparing strings with == will often give you false negatives ... depending on how the strings were created / obtained. You've just been bitten by that. Learn.
Reference:
How do I compare strings in Java?
Related
This question already has answers here:
Test if a string contains any of the strings from an array
(15 answers)
Closed 2 years ago.
If I want to check whether a String contains "CVR", "CPR" and "NR". How do I do so? I tried with following method but got some issues
String testString = "cpr1210";
if (testString.contains("cpr||cvr||nr")) {
System.out.println("yes");
}
I might use String#matches() here, with a regex alternation:
String input = "cpr1210";
if (input.matches("(?i).*(?:cpr|cvr|nr).*")) {
System.out.println("MATCH");
}
If you really wanted to use String#contains(), then you would need to have three separate calls to that method, for each sequence.
As mentioned in my comment to your question, you may use String#contains().
String testString = "cor1210";
// will not print yes, because none of the sequences fit
if (testString.contains("cpr") || testString.contains("cvr") || testString.contains("nr")) {
System.out.println("yes");
}
Make sure your logic-syntax in the if-clause is correct.
You can check whether a String contains another String (a substring) with the String.contains() method. It returns a boolean value. Keep in mind that this method is case sensitive. If you want to do case-insensitive search then use the same technique, convert both input and search string in same case and then call the method.
String testString = "cor1210";
//checks whether testString contains CVR, CPR or NR
if (testString.contains("CVR")||testString.contains("CPR")||testString.contains("NR")){
System.out.println("yes");
}
The problem I am having is using .contains() for an array. This is my current line of code:
if (strings[i].contains(symbol) = true){
strings[] is an array that stores user inputted data, the error message i get for this is "The left-hand side of an assignment must be a variable". I understand what this means, my question is, can I use one string from the array when using .contains() or am I going about this the wrong way?
Any help will be appreciated. Thanks.
The problem is that
strings[i].contains(symbol) = true
is an assignment because of the =. You probably mean
strings[i].contains(symbol) == true
and, because the left hand side is a boolean,
strings[i].contains(symbol)
is already sufficient.
my question is, can I use one string from the array when using .contains()
If you read the Java API for String (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html), contains() is a method from String class.
By knowing that, you can use .contains() on a single String element / a String variable.
String str = "abc";
str.contains(symbol); //This is ok.
String[] strs = {"abc", "def"};
str[0].contains(symbol); //This is ok too.
Both of the above are allowed, because both are String.
String[] strs = {"abc", "def"};
str.contains(symbol); //This is wrong!
One more thing which you should have noted by now in your codes is:
When comparison, use == and not single =
And when comparing strings or objects, use .equals()
Of course, you can also write it as:
if(strings.[i].contains(symbol)) //if this statement is true
if(!strings.[i].contains(symbol)) //if this statement is not true
instead of
if(strings.[i].contains(symbol) == true) //if this statement is true
if(strings.[i].contains(symbol) == false) //if this statement is not true
I'm trying to make a basic program where it checks if a word is a palindrome, and I need to figure out how to do two things.
How do I figure out how many letters are in a string?
and
How do I compare two chars to see if they are the same?
Thanks in adv.
How do I figure out how many letters are in a string?
String in Java is immutable object which means it does not change. So the following code creates new string every time it is needed:
String s = "Hello";
s += " World";
After above introduction the answer to question nr 1 is
int len = s.length();
How do I compare two chars to see if they are the same?
String has access method for its characters, that you can use to access and compare them:
char one = s.charAt(0);
char two = s.charAt(1);
if (one == two) {
:
}
For your assignment I would recommend to use public char[] toCharArray() method and loop the array for accessing each character.
1.) StringName.length() <- Java has a method that will return the length of the string
2.) charName == charName2 <- primitive type can use the comparison operator
You have some good ideas that will help you write a palindrome program. I will offer no hints though so you can figure it out. good luck. <-Taken (bad guy) voice
This question already has answers here:
How do I compare strings in Java?
(23 answers)
String comparison - Android [duplicate]
(17 answers)
Closed 8 years ago.
When I compare ("String"=="String"), what exactly I am comparing, the two objects or two references?
Please explain the output of following code snippets:
1) System.out.println("String".toString()=="String"); // output is true
2) System.out.println("String".trim()=="String"); // output is true
3) System.out.println("String ".trim()=="String"); // output is false
According to statement 1 and 2, the output of 3rd statement should also be true. Please explain what is going on here.
From my previous answer, You have to remember, == compares the object references, not the content.
trim() returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
in the first case the answer is true no surprise about that because the references are equal
in the second case there are no leading or trailing spaces so trim returns the same string again the references are equal
in the last case trim returns a copy as the string has a trailing white space which results in a different reference so your comparison will be false.
In java you should never compare strings with the equality operator ==, since that operator compares references rather than contents. The compiler is smart enough to reuse one reference for all equal literals found in the code (so the four occurrences of String in 1) and 2) are probably the same instance). However in 3) you have two different literals and there is no guarantee that "String ".trim() will be represented by the same instances as the literals.
See also: https://stackoverflow.com/a/513839/55787
Use .equals() instead.
== compares whether the two String references you are comparing point to same String instance or not.
To answer your question you need to check the source code of methods in String class
public String trim() {
int len = count;
int st = 0;
int off = offset; /* avoid getfield opcode */
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[off + st] <= ' ')) {
st++;
}
while ((st < len) && (val[off + len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}
public String toString() {
return this;
}
As you can see it return this in case of trim if there is nothing to trim which is why you get true. Also toString simply returns this.
you have to use the method
equals()
to compare Strings. Instead with == you are comparing
references.
== compares memory location . In the first case , the toString method returns the same object ,and since both "String" objects being compared point to the same object on the constant pool, the result is true. In the second case, the trim method does no modification to the String so it returns the same object, with the same result. The third case and the second call to trim returns a different object, not located on the constant pool
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am getting a value as 9999912499 from the database.
I have separated it in two parts 99999 and 12499 using substring.
Now I want to check whether if the 1st string is equal to 99999 then i do some processing otherwise something other processing.
But controls never gets in to the if loop
Following is a snapshot:
String strPscId = Long.toString(pscID);
String convPscID = strPscId.substring(5, strPscId.length());
String checkNine = strPscId.substring(0,5);
BigDecimal jpaIdObj = jeuParam.getJpaIdObj();
Long mod_id = modele.getModId();
log.info("outstrPscId == " +strPscId);
log.info("outconvPscID == " +convPscID);
log.info("outcheckNine == " +checkNine);
log.info("outjpaIdObj == " +jpaIdObj);
log.info("outmod_id == " +mod_id);
if(checkNine == "99999") { <method-call> }
else { <another - method - call> }
For some reason, the people that make java decided that == shouldn't be used to compare Strings, so you have to use
checkNine.equals("99999");
Look at the following code:
String str1 = "abc";
String str2 = str1;
In the first line, a new string is created and stored in your computer's memory. str1 itself is not that string, but a reference to that string. In the second line, str2 is set to equal str1. str2 is, like str1, only a reference to a place in memory. However, rather than creating an entirely new string, str2 is a reference to the same place in memory that str1 is a reference to. == checks if the references are the same, but .equals() checks if the each character in a string is the same as the corresponding character in the other string.
boolean bool1 = (str1 == str2);
boolean bool2 = str1.equals(str2);
If this code were added to the code above that, both bool1 and bool2 would be true.
String str1 = "abc";
String str2 = new String(str1);
boolean bool1 = (str1 == str2);
boolean bool2 = str1.equals(str2);
In this case bool2 is still true, but bool1 is false. This is because str2 isn't set to equal str1, so it isn't a reference to the same place in memory that str1 is a reference to. Instead, new String(str1) creates an entirely new string that has the value of str1. str1 and str2 are references to two different places in memory. They contain the same value, but are fundamentally different in that they are stored in two different places, and therefore are two different things.
If I replaced new String(str1) with "abc" or str1, bool1 would be true, because without the key word new, the JVM only creates a new string to store in memory if absolutely necessary. new forces the JVM to create an entirely new string, whether or not any place in memory already has the same value as the new string being created.
.equals() is slow but generally more useful than ==, which is far faster but often does not always give the desired result. There are many times when == can be used with the same result as .equals(), but it can be difficult to tell when those times are. Unless you a knowledgeable programmer making something where speed is important, I would suggest that you always use .equals().
You need use equals method, rather than == to compare strings.
Change from
if(checkNine == "99999")
to
if(checkNine.equals("99999"))
The == operator is used to compare the content of two variables. This works as expected when using primitive types (or even wrapper classes because of auto-boxing). However, when we are using == with a reference to an object (e.g., checkNine), the content is the reference to the object but not the value of the object. This is where equals() method is used.
if("99999".equals(checkNine)){
<method-call>
}
else {
<another - method - call>
}
if(checkNine.equals( "99999")) {
<method-call>
}
else {
<another - method - call>
}
if (strPscId.startsWith("99999"))
{
bla bla
}
else
{
sth else than bla bla
}