This question already has answers here:
How do you check if a string is not equal to an object? [duplicate]
(2 answers)
Closed 2 years ago.
if (correctAnswer.equals(userChoice.toLowerCase())) {
System.out.println("Your have provided the correct answer. Well done!");
Where I have .equals above as a String operation, is there a .notequals equivalent for it in Java?
You can use negation operator ! to reverse result of equals method like
if (!correctAnswer.equals(userChoice.toLowerCase()))
Related
This question already has answers here:
How to check type of variable in Java?
(16 answers)
What is the 'instanceof' operator used for in Java?
(18 answers)
Closed 1 year ago.
I want check the variable type. How do I do that? For e.g
if (num is of String type )
{This must be executed}
I'm currently using Java 17. Any suggestions?
You can use instanceof String to check whether a variable is a String.
if (num instanceof String) {
// code to be executed
}
This question already has answers here:
Comparing a string with the empty string (Java)
(9 answers)
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
Lets say we have a string in java. Can we compare this string to "" using the ==?
For example:
String myString = "";
if(myString == "");
Of course you can (insofar that compilation will pass), although you will probably not get the result you expect since using == will compare references not contents.
My favourite way is to use the Yoda Expression "".equals(myString) since then you don't need to pre-test myString for null.
Else you could use myString.isEmpty().
This question already has answers here:
What is the difference between a += b and a =+ b , also a++ and ++a?
(9 answers)
Closed 7 years ago.
Is += the same as =+?
I can't find any reason for why the plus sign is reversible.
For what reasons would I need to use one of the other? Where can i find docs on this i tried searching but didnt see the use of both.
It's not the same.
x+=5 is equivalent to x=x+5.
x=+5 (or x=(+5)) is equivalent to x=5.
This question already has answers here:
How can I check if a single character appears in a string?
(16 answers)
Closed 9 years ago.
I have a string like :
"\"[\"a\",\"b\", \"c\"]\""
How to convert this to a list of strings
Could you suggest me a nice way of doing it in Java?
str.contains("c") does this job. However did not you think to consult String class documentation first?
Use contains():
if (str.contains("\"c\""))
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
I'm new to Java. And I've following problem:
string s = "someword";
if (s == "someword")
// do something
Sometimes doesn't work for me. Don't know why.
Thanks for responds.
In Java == compare reference. Use .equals() for compare value.
Duplication of this: How do I compare strings in Java?