sonar complain Ternary operators should not be nested.
Is there any way possible to remove this complaint since I am beginner in java I would like some help in this issue.
object form = null;
if(objs.getForm() != null)
form = objs.getForm();
String getName = form != null
? referenceObjType + form.getName()
: "" + (objs.getType() == null ? ""
: "(" //$NON-NLS-1$
+ objs.Type().getTypeName() + ")"
+ objs.getName());
What about something like this? Nested ternary operators are quite bad practice.
String getName= "";
if (form != null) {
getName = referenceObjType + form.getName();
} else {
getName = objs.getType() == null ? "" : String.format("(%s)%s",objs.Type().getTypeName(), objs.getName());
}
You need to use parenthesis to group the second ternary operator:
String getName = form != null
? referenceObjType + form.getName()
: "" + (objs.getType() == null ? ""
: "(" //$NON-NLS-1$
+ objs.Type().getTypeName() + ")"
+ objs.getName());
In java the additive operator (+) has a higher preference than the equality operator (==).
see: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
So without the parenthesis the statement
"" + objs.getType() == null
The String concatenation is done first and the result then checked against null. Since an empty String that you append something to cannot be null, this statement will always yield false and one part of your ternary operator will never be reachable.
If you are a beginner with Java I would refrain from using ternary operators so you could really understand what each statement is doing.
The issue:
I believe the else statements (the ones starting with ":") are not reachable because form will never be null. Also you are appending a string prior to checking if it is null. This will always return that it is not null.
You also need to group your second ternary operator with a parentheses like so:
String getName = form != null
? referenceObjType + form.getName()
: "" + (objs.getType() == null ? ""
: "(" //$NON-NLS-1$
+ objs.Type().getTypeName() + ")"
+ objs.getName());
It is hard to give you a complete answer since I do not know your original problem and cannot see other code but I hope this helps
Related
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.
This question already has answers here:
String concatenation does not work properly in Java when concatenating 2 results of ternary operators
(4 answers)
Closed 5 years ago.
So how is the Java (#Android) ternary operator supposed to behave really ?
Check these simple examples:
boolean trigger = true;
String myStr_NOK = trigger ? "YES:" : "NO:"
+ " if trigger was TRUE"
+ " this is NOT visible :-o");
String myStr_OK = (trigger ? "YES:" : "NO:")
+ " if trigger was TRUE"
+ " this is visible as should.");
// I think the first comments missed this fact:
trigger = false;
String myStr_NOK = trigger ? "YES:" : "NO:"
+ " if trigger was FALSE"
+ " this IS concatenated AGAIN");
Now that is a masterpeace of Java logic, that my brain just refuses to swallow.
Do you REALLY have to encapsulate the ternary operator in Java (Android) in brackets, else you do not get the rest of composed string ?
See: myStr_NOK only contains "YES:", since the ternary operator was not in brackets ?
In this page, it clearly states, that no brackets are required. As I would rightfully expect.
Quote:
Note that the parentheses in this example are optional, ...
EDIT:
Let me re-phrase my Q:
What does the standard say about ternary operator ? My observation is such, that withOUT parenthesis around the ternary operator, the further string concatenation is performed ONLY when expression is FALSE. If TRUE, it does not concatenate. Does anyone find this meaningful, obvious and expected behavior ?
And now my original Q that got downvotes:
What am I getting wrong, or has the world just gone mad ?
It does not misbehave at all.
Your first example is basically this written out:
if(true) "YES";
else "NO" + theOtherStrings;
Your second example is written out like this
String string;
if(true) string = "YES";
else string = "NO";
string = string + theOtherStrings
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.
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();
}
}
I want to understand why the following code throws Null pointer exception.
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> names = null;
System.out.println("Result is: " + names == null ? null : names.size());
}
}
The issue is that your print statement is evaluated as:
System.out.println(("Result is: " + names) == null ? null : names.size());
This is due to the fact that + has more precedence than ?: operator So, as the string - "Result is null" is not equal to null, evaluating names.size() throws NPE.
Note that, when null is used in string concatenation, it is automatically converted to "null". So, "Result is: " + null will not throw NPE. This is as per JLS - String Conversion:
If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
To fix the issue, you should add parenthesis around your conditional expression to enforce greater precendence to it:
System.out.println("Result is: " + (names == null ? null : names.size()));
Correcting Jigar's answer, this actually works:
someString + null
To fix OP's code, just add parenthesis - in this way the operations will be performed in the correct order and the result will be as expected:
System.out.println("Result is: " + (names == null ? null : names.size()));
you are writing "Result is: " + names which is not equivalent to null so its trying to print names.size(). But when names.size() is called it throw null pointer exception as names is still null.
Modify
System.out.println("Result is: " + names == null ? null : names.size());
to
System.out.print("Result is: ");
System.out.println( names == null ? null : names.size());
then you will get null as output.