Runtime boolean and String error in java? - java

Hi that println giving me error but it working fine if I just print them separately. Any Idea why this happening?
class StringTesting
{
public static void main(String me[])
{
String s1="Varun";
String s2="varun";
String s3="Varun";
String s4=new String("Varun");
String s5=new String("Varun");
System.out.println(" "+s1==s3+" "+s1==s2+" ");//here its giving me error
}
}
And also thanks in Advance :)

In terms of operators, + has the precedence on ==.
It means that this code :
" "+s1==s3+" "+s1==s2+" "
is translated by the compiler by something like that :
" Varun"=="Varun Varun"=="Varun "
the first part " Varun"=="Varun Varun" produces a boolean
and applying to it the "Varun " String with the == comparator, it results to :
booleanExpression == "Varun "
Comparing boolean with a String is not valid.
Anyway, even if it was, you don't want to as you want to output the boolean result of the == comparison between the objects.
So just put between parentheses the == comparisons to indicate to the compiler that operations in have to be evaluated together :
" "+(s1==s3)+" "+(s1==s2)+" "
It will produce a valid concatenation :
String + boolean + String + boolean + String

According to the Java documentation on String, the proper way to compare two strings is by using the .equals method.
System.out.println("s1 == s2 ?: " + s1.equals(s2))
By using the == operator between two Objects you are comparing memory locations, not the actual primitive value(s) contained in the object.

You can't compare booleans and strings using == and this is what is indeed happening there because of the order of operators being applied.
You can fix that using simple brackets:
System.out.println(" " + (s1 == s3) + " " + (s1 == s2) + " ");
Of course, if you do not combine results of two different operators, that will work just fine:
System.out.println(s1 == s3);
So, it was enough to just read the compilation error.

Related

Selenium Assert Equals to Value1 or Value2

I want to test in Selenium (Java, Testng)
If my actual value is equal to one of the two values because my value can be Value1 or Value2 and both values will be correct.
If I want to assert only one equality I use this construction:
String expectedPopUpV1 = "Value1";
String expectedPopUpV2 = "Value2";
String actualPopUp = driver.findElement(By.cssSelector(Value)).getText();
Assert.assertEquals(actualPopUp,expectedPopUp);
but what should I do if I want to make something like
Assert.assertEquals(actualPopUp,expectedPopUp1||expectedPopUp1);
You can use assertTrue(boolean condition, String message) for this and give the details in the message
boolean isEqual = actualPopUp.equals(expectedPopUpV1) || actualPopUp.equals(expectedPopUpV2);
Assert.assertTrue(isEqual, "The text " + actualPopUp + " is not " + expectedPopUpV1 + " or " + expectedPopUpV2);
below option should also work using ternary operator:
Assert.assertEquals(expectedPopUpV1.equalsIgnoreCase(actualPopUp )?expectedPopUpV1:expectedPopUpV2 , actualPopUp );
There isn't any such method available. The two closest options I can think of:
if(!actualPopUp.equals(expectedPopUp1) || !actualPopUp.equals(expectedPopUp2) {
Assert.fail("insert failure messsage here");
}
or
if(actualPopUp.equals(expectedPopUp1) || actualPopUp.equals(expectedPopUp2) {
Assert.assertTrue("insert message");
}
The other option would be to really extend the Assert capability by constructing your own with a Builder pattern to be in the tune of:
AssertBuilder.with(actualPopUp).equals(expectedPopUp1).or(expectedPopUp2);
But that may be too complicated for a simple use case.

Comparison of two String return always false java

I have two variable and when i make
system.out.println(var1+" && "+var2)
I found this : "var1" && var2
var1 with quote and var2 without quote so this is why i found always false
what should i do ??
system.out.println(var1+" && "+var2)
won't compile, let alone return or result in a value.
&& can not be used for comparisons, it's used to implement the logical AND.
If you want to compare objects, you'll need to use the '==' operator for a referential comparison, or the equals method if you want to compare values.
For String instances, you have an additional equalsIgnoreCase method you can use.
so: if var1 and var2 are objects, you can try this:
System.out.println((var1 == var2)); // compare references
and
System.out.println(var1.equals(var2)); // compare values
If they are primitives, you'll need to use the '==' operator
If they are booleans you want to check:
System.out.println(var1&&var2);
will do the trick
First of all, you should check if the values you are getting in those variables are correct, and the desired.
If they are correct, then, to delete the quotes you can use the String#replace method to replace all the double quotes with an empty:
var1.replace("\"", "");
Note that here you should escape the double quote \".
Note: This answer supposes that you are comparing the Strings correctly (using String#equals).
String intint = "INT";
String gouc = "GOUc";
String fg2a = "FG2c";
String fg2c = "FG2c";
String goua = "GOUa";
affichageBroadInfos(broadInfos);
Iterator<RncBroadInfo> iter = broadInfos.iterator();
while (iter.hasNext()) {
RncBroadInfo str = iter.next();
// if (!(str.getBroadClass().equals("INT"))) { this return false
if (!(str.getBroadClass().replace("\"", "").equals(intint))) {
System.out.println("ToComprare Twoe Strings " + str.getBroadClass().replace("\"", "") + " && " + intint);
System.out.println("To Remove Interface" + str.toString());
System.out.println("type var 1" + str.getBroadClass().getClass());
System.out.println("type var 2" + intint.getClass());
System.out.println("result of Comparision " + str.getBroadClass().equals(intint));
iter.remove();
}
}

Class Hello in a test

I have come across this question in a test:
class Hello {
public static void main(String[] args){
String hello = "Hello", lo = "lo";
System.out.println(hello == ("Hel" + "lo"));
System.out.println(hello == ("Hel" + lo));
System.out.println(hello == ("Hel" + lo).intern());
}
}
The output is:
true
false
true
Why is the second output false?
It prints 'false' because the concatenation of the String constant "Hel" and the String object 'lo' results in a seaparate, anonymous string object, with its own unique object reference. Thus, the "hello" String object and the concatenated string are different objects based on object reference (== operator, not by String value with String.equals()).
== compares the references of two sides.
Here, for hello == ("Hel"+lo), the references of two sides are not the same. So, it returns false.
For comparing values, use equals() method.
I think it Comparision Literal Problem.
It Works.
System.out.print((hello.equals("Hel"+lo)) + " ");
System.out.print((hello == ("Hel"+"lo")) + " ");
I think it is because in the second output ("Hel" + lo) is no more in the string. The equality "==" operator compares object memory location and not characters of String.By default Java puts all string literal into string pool, but you can also put any string into pool by calling intern() method of java.lang.String class, like string created using new() operator.

Android replaceAll and string comparison with ==

While auditing an android source code, I found a string comparison bug which used == instead of equals(). However, the app is working well surprisingly!
After some testing, I found that replaceAll() method is hiding the bug.
String description = " ";
description = description.trim();
Result1.setText(description + " == " + "" + ": " + (description == ""));
prints "==:false" as I expected. However,
String description = " ";
description = description.trim().replaceAll("\\s+|\\r+|\\n+", " ");
Result1.setText(description + " == " + "" + ": " + (description == ""));
prints "==:true"! (Android 4.4.2, API 19)
I run the same code in my desktop (javac 1.6.0_45) and it prints "==:false" as I expected.
Is it a bug in Android or is it intended behavior?
No, it's not a bug -- it's just an implementation detail leaking out.
The java compiler creates a pool of strings used in the code. The empty string is surely one of these. Any time you set a variable to the empty string at compile-time, it will point to the same instance of the empty string. So
String a = "";
String b = "";
if (a == b) {
//this will always be true in practice, although I don't know if it's guaranteed
}
Now imagine that trim() and replaceAll() are implemented differently:
String trim() {
byte[] b = getBytes();
...
return new String(b, 0, len);
}
String replaceAll (String needle, String replacement) {
String result = "";
int pos = 0;
while (indexOf(needle, pos) != -1) {
...
result = result + replacement;
pos = ...;
}
return result;
}
Because trim() calls a String constructor, it necessarily creates a new String. But replaceAll starts with an empty String and builds up. And the empty String that it starts with is the same empty string as all the other empty strings in your source code.
These are fake implementations -- it's just a hypothesis that this is how it works. It matches the observed data, but I didn't read the Android code. Still, it demonstrates that different implementations of similar functions could lead to the effect that you're seeing.
In other words, it's not a bug, but it's not a behavior you want to depend on. If you do want to depend on two strings that .equal() also being ==, you can use String.intern().

Java == behaving ambiguously

I came across this question in a Facebook group. I know I should be using equals() method but I want to know why this is happening
class Main
{
public static void main (String[] args)
{
String s1="abc:5";
String s2="abc:5";
System.out.println(s1==s2);
System.out.println("s1 == s2 " + s1==s2);
}
}
OUTPUT
true
false
This is due to operator precedence. '+' has a higher precedence than ==. You are actually comparing ("s1 == s2" + s1) to s2.
http://introcs.cs.princeton.edu/java/11precedence/
The confusion is in the order of operations. What is happening is that you're concatenating "s1 == s2 " and s1, then using == on that result and s2.
They are different objects, so false is printed (and "s1 == s2" is not printed). Put parentheses:
System.out.println("s1 == s2 " + (s1==s2));
This will print s1 == s2 true because both s1 and s2 refer to the same interned string literal, "abc:5".
Oh I just make some change in the code and get that + first doing "s1 == s2 s1" then == with s2 which is not true. New code
class Main
{
public static void main (String[] args)
{
String s1="abc:5";
String s2="abc:5";
System.out.println(s1==s2);
System.out.println("s1 == s2 " + (s1==s2));
System.out.println("s1 == s2 " + s1==s2);
}
}
OUTPUT
true
s1 == s2 true
false
this is easy to understand once you thought about it: the 2. println first adds "s1 == s2" and your string s1 and then compares it with s2, so it outputs false, because "s1 == s2abc:5" is not "abc:5"
It is adding the strings "s1 == s2 " + s1 and then computing whether that is equal to s2. It is not so it is printing false.
The Java Operator Precedence might help you here.
I think when using "==" the system will just check if the two things share the same location in the systems memory. However, if you use the ".equals" method the system will check if the two Strings share the same characters.
Your code
System.out.println(s1==s2);
System.out.println("s1 == s2 " + s1==s2);
Since s1 and s2 are the same String literals
`s1==s2` is true
Thus the code can be written as
System.out.println(true); => true
System.out.println("true" + s1==s2);
Now, "true" + s1==s2 is comprehended as ("true" + s1)==s2 due to higher precedence given to "+". Thus
"true"+s1 => trueabc:5 and
s2 => "abc:5"
Hence
System.out.println("true" + s1==s2); => false
I think its because of operator precedence of something like that, if you do System.out.println(""+(s1==s2));, it will print true.

Categories

Resources