This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
Replace will create new object and both side this new will be compared. then why it showing false.
When exactly created new string will be added in string pool?
if("String".replace("g", "G") == "String".replace("g", "G"))
{
System.out.println("True");
} else {
System.out.println("False");
}
because replace() will always return a new String instance. So the 2 same calls to replace method will return 2 different instances with same value.
use equals() instead of == if you want to compare value
Use intern() on both replaced values if you want to add the string to the string constants pool (and are bent on using == :P)
if ("String".replace("g", "G").intern() == "String".replace("g", "G").intern()) {
System.out.println("True");
} else {
System.out.println("False");
}
}
OP :
true
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
When the code is 20, nonSmoking should be 1, but always returns null. After debugging I saw that it always returns null
How to set a variable nonSmoking correctly?
public static String mapSmokingAmenities(ContentFragmentList list){
SolrContentFragment solrFragments = list.getFragment(SolrContentFragment.class);
List<String> ausstattungPositions = solrFragments.getAusstattungPosition();
String nonSmoking = new String();
for(String code : ausstattungPositions){
if(code == "20" || code == "36"){
nonSmoking = "1";
}
if(code == "51"){
nonSmoking ="0";
}
}
return nonSmoking;
}
Comparing objects using == compares the address. You can find out if a object points to the same instance you want to work with. Only primitive datatypes (int/...) can be compared with value like that.
For Strings as being object please use equals() method for the value compare.
If you have custom DTO/POJO where you want to compare value and not reference you need to overwrite the hashCode and equals method there.
Probably this could help
public static String mapSmokingAmenities(ContentFragmentList list){
SolrContentFragment solrFragments = list.getFragment(SolrContentFragment.class);
List<String> ausstattungPositions = solrFragments.getAusstattungPosition();
String nonSmoking = "";
for(String code : ausstattungPositions){
switch(code) {
case "20":
case "36":
nonSmoking = "1";
break;
case "51":
nonSmoking = "0";
break;
default:
// do nothing
break;
}
}
return nonSmoking;
}
You should use an enum for your codes and your result. Be aware, that you set nonSmoking every time being code 20, 36 or 51. Probably you should break your for loop. Don't create a new String but use an empty String "".
This question already has answers here:
Java how to use stream map to return boolean [duplicate]
(2 answers)
How to match stream elements but return false if non exists?
(6 answers)
Use Streams to return Boolean if all the List values in a Map are empty/not-empty
(3 answers)
How to use stream on method that return boolean value with condition
(4 answers)
Closed 2 years ago.
I have a method that works fine. This is how it looks.
private boolean roomWithMoreThanTenFurnitures(Building building) {
if (building != null && building.hasRooms()) {
for (Room room : building.getRooms()) {
if (room.getFurnitures.size() > 10) {
return true;
}
}
}
return false;
}
I wanna switch this to Lambda. In came uo with the shell, but I am not sure how fill in the if (condition) return true or return false outside.
building.getRooms().forEach(room -> {
//??
});
You cannot do it this way - the foreach is for executing some action for every of the collection/stream element not for filtering them or mapping to a result
You need e.g. anyMatch method - for example
building.getRooms().stream().anyMatch(room -> room.getFurnitures.size() > 10)
You can do it like this. Returns false based on the initial conditions, then streams the rooms. This presumes the rooms can be streamed (e.g a List). If they are an array you will need to do something similar to Arrays.stream(building.getRooms())
private boolean roomWithMoreThanTenFurnitures(Building building) {
if (building != null && building.hasRooms()) {
return building.getRooms().stream()
.anyMatch(room -> room.getFurnitures.size() > 10);
}
return false;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have a line in file config.properties
clean=true
and use following code to get this property
private static String clean;
Properties prop = new Properties();
try {
prop.load(new FileInputStream("config.properties"));
clean = prop.getProperty("clean");
}
I use System.out.println(">"+clean+"<") to see the output and get ">true<", which indicates there is no blank, no \n
However, when I use
if (clean == "true") {
// program does not go here
}
else {
// program goes here
}
what is the possible reason?...
Try the following:
== checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
if (clean.equals("true")) {
// program does not go here
}
else {
// program goes here
}
The Problem is you are using equality operator which doesn't compare literal instead references. So you have to use equals method to do literal check
if ("true".equals(check)) {
// Now Program will go here
}
else {
// and now here
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm writing some codes that test if there is "xx" in a string. For instance, doubleX("aaxxbb") should return true, and doubleX("axabb") should return false.
Here is my code:
private static boolean doubleX(String str) {
for(int i=0;i<str.length()-1;i++){
System.out.println(str.substring(i,i+2));
if(str.substring(i,i+2) == "xx") return true;
}
return false;
}
Why does doubleX("aaxxbb") return false?
You have to use .equals instead of ==. For more information, follow the duplication message.
return str.contains("xx");
Is a lot clearer though.
You should understand the difference between == and equals: the first one compares references, the second compares actual values.
Your code is wildly inefficient.
I'd try something like this:
private static boolean doubleX(String str) {
return (str.indexOf("xx") != -1);
}
Use equals() for checking the content of a String to another rather than ==. == checks for reference equality.
private static boolean doubleX(String str) {
for(int i=0;i<str.length()-1;i++){
System.out.println(str.substring(i,i+2));
if(str.substring(i,i+2).equals("xx")) return true;
}
return false;
}
Even you can directly code like:
private static boolean doubleX(String str) {
return str.contains("xx");
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I seem to be having a problem with a boolean test. when I use this code:
public boolean setPkg (String inPkg)
{
boolean isValid;
if ((inPkg.toUpperCase() != "A" ) || (inPkg.toUpperCase() != "B" ) || (inPkg.toUpperCase() != "C"))
isValid = false;
else
{
pkg = inPkg;
isValid = true;
}
return isValid;
}
It returns false on "A". However when I only test for "A":
...
if (inPkg.toUpperCase() != "A" )
isValid = false;
else
{
pkg = inPkg;
isValid = true;
}
return isValid;
...
it returns true.
what am I missing?
I have also tried to use multiple if else statements to test for A, B, or C and i get false for A. B and C dont get tested as an exception of my making is getting thrown.
Two things over here :
replace != with equals method for comparison
replace || with &&
Always use oneString.equals(otherString), not oneString == otherString, when comparing strings.
For example, instead of:
(inPkg.toUpperCase() != "A" )
use this instead:
(!(inPkg.toUpperCase().equals("A")))
NEVER compare strings with == or !=. See: How do I compare strings in Java?
The issue is that you're using == to compare strings. This doesn't do what you think it does (it compares string references, not the character sequences).
Use s1.equals(s2) instead, as in
!inPkg.toUpperCase().equals("A")
etc.
See Java comparison with == of two strings is false?
== and != compares the Object references. they are not equal as they are not the same object.
String.equals(otherString) compares the content of the String. You want to use this function.