Ternary operator in System.out - java

I found below sysout in our project and it is always printing 'Not Null'. Even I have initialize the Val variable or not, it is printing 'Not Null'.
Also why it is not printing the "mylog" in front? Can someone explain?
String Val = null;
System.out.println("mylog : " + Val!=null ? "Not Null" :"Is Null");

Use paranthesis:
System.out.println("mylog : " + (Val!=null ? "Not Null" :"Is Null"));
Otherwise it gets interpreted as:
whatToCheck = "mylog: " + val
System.out.println(whatToCheck !=null ? "Not Null" : "Is Null"
which evaluates to something like "mylog: null" or "mylog: abc".
And that is always a non-null String.

"mylog : " + Val!=null
will be evaluated to
"mylog : null"
which is not null.
Parenthesis for the rescue.
Why is null converted to the String "null"? See the JLS - 15.18.1.1 String Conversion:
... If the reference is null, it is converted to the string "null"
Also it's very important to understand that this is happening because of Java operator precedence.

Use brackets around your expression:
System.out.println("mylog : " + (Val!=null ? "Not Null" :"Is Null"));

Check it following way:
String Val = null;
System.out.println("mylog : " + (Val!=null ? "Not Null" :"Is Null"));
Output :
mylog : Is Null

Related

System.out.println Not doing what I expect when printing something that evaluates to a boolean

I'm not sure how to describe my question for a title, so here's my code:
public class NullLogic {
public static void main(String[] args) {
NullLogic nl = new NullLogic();
System.out.println("nl.getNull() = " + nl.getNull() );
System.out.println("nl.getNull() == null = " + (nl.getNull() == null) );
System.out.println("nl.getNull() == null = " + nl.getNull() == null );
}
private String getNull() {
return null;
}
}
Here's the output:
nl.getNull() = null
nl.getNull() == null = true
false
Ok---the first line is no problem, exactly what I'd expect.
Second line is also good.
Now I've got a problem with the third line, I know the statement that evaluates to a boolean should be in brackets, but I figure I should get a runtime error or something, not a successful execution that suppresses the the string part of the sysout.
What's going on here?
This isn't a serious problem that I need to solve, but I don't know what's going on here and I'd like to know.
Thanks!
System.out.println("nl.getNull() == null = " + nl.getNull() == null )
is evaluated as
System.out.println(("nl.getNull() == null = " + nl.getNull()) == null )
i.e., first you concatenate two Strings (the first is not null - "nl.getNull() == null = ", and the second is null, but even if both were null, concatenating them would result in a not null String).
The result of this concatenation is the String: "nl.getNull() == null = null".
Then you compare "nl.getNull() == null = null" to null, which evaluates to false.

Print the object and check null

public void printManagerAvailable(Manager mgr) {
System.out.println(" Is Manager object available : " + mgr!=null);
}
Output:
true
Why output is only true here? I'm expecting:
Is Manager object available : true
because it thinks that you are saying " Is Manager object available : " + mgr is all to the left of != null. In other words, it does " Is Manager object available : " + mgr first and then it compares " Is Manager object available : [Object:Manager]" != null.
Do this.
Manager mgr = new Manager();
mgr.setChangeClass(5);
mgr.setChangeClockIn(10);
System.out.println(" Is Manager object available : " + (mgr!=null));
Other answers cover what is happening, this is why it is happening:
The order of operator precedence in Java puts addition, +, ahead of equality, !=.
It's important to realize that it's not caused by left-to-right ordering here.
So what you have is applying the operators in the order like so:
("Is null : " + mgr) != null
And to fix it you can use brackets to force the precedence the other way:
"Is null : " + (mgr != null)
Try using this line of code.
System.out.println(" Is Manager object available : " + (mgr == null ? "is null" : "not null"));

there is not StringBuffer in class file [duplicate]

I have the following code
System.out.println("" + null);
and the output is null.
How does Java do the trick in string concatenation?
Because Java converts the expression "A String" + x to something along the lines of "A String" + String.valueOf(x)
In actual fact I think it probably uses StringBuilders, so that:
"A String " + x + " and another " + y
resolves to the more efficient
new StringBuilder("A String ")
.append(x)
.append(" and another ")
.append(y).toString()
This uses the append methods on String builder (for each type), which handle null properly
Java uses StringBuilder.append( Object obj ) behind the scenes.
It is not hard to imagine its implementation.
public StringBuilder append( Object obj )
{
if ( obj == null )
{
append( "null" );
}
else
{
append( obj.toString( ) );
}
return this;
}
The code "" + null is converted by the compiler to
new StringBuffer().append("").append(null);
and StringBuffer replaces null with the string "null". So the result is the string "null".

Error with Jongo parsing JSON

I'm using a combination of Java Play Framework, MongoDB and Jongo as my go between for a basic web CRUD app. I keep receiving a JSON parse exception even though my string doesn't contain any illegal characters. It's actually failing on closing curly bracket at the end of the statement. Below is my error and code. The query string is just a string builder, searching if an object is empty or has a value, if it has a value it's appended to a string.
Jongo method:
public static Iterable<OneDomain> findWithQueryString(String queryString){
return domains().find("{#}", queryString).as(OneDomain.class);
}
Controller Methods:
String builder example:
if(queryStringBuilder.toString().equalsIgnoreCase("")){
queryStringBuilder.append("date: {$gte : " + searchObj.dateFrom + ", $lt: " + searchObj.dateTo + "}");
}else{
queryStringBuilder.append(" , ");
queryStringBuilder.append("date: {$gte : " + searchObj.dateFrom + ", $lt: " + searchObj.dateTo + "}");
}
String queryString = queryStringBuilder.toString();
Iterable<OneDomain> filteredIterable = OneDomain.findWithQueryString(queryString);
Gives me this error:
Caused by: com.mongodb.util.JSONParseException:
{"source : Online Lists , blacklist : true , vetted : true , is : false , isNot : true"}
^
with the error on the "}" ending it.
In addition to that, if I try to escape the characters by putting in a \" so it becomes \"date\" it will parse and error out like so:
Caused by: com.mongodb.util.JSONParseException:
{"\"source\" : \"Online Lists\" , \"blacklist\" : true , \"vetted\" : true , \"is\" : false , \"isNot\" : true"}
You're building JSON by hand, and doing it wrong. You need to learn the basic JSON syntax requirements
A basic JSON-encoded object is
{"key1":"value1","key2":"value with \" escaped internal quote"}
Note all of the quotes. Your json string is a single very long object key with no associated value, which is not permitted. All keys must have values.

iReport/jasperReports how can i check in xml data source if node exsicts

i new to iReport , my question is in the expression editor , how can i build expression that checks if xml node
extincts and base on that print string
i have this expression that returns me null in the result :
( $F{root_customer}.isEmpty() ? "Entity name:" :"Customer id:" )
the root_customer does not exsict in the xml
Try something along the following lines in your expression.
( $F{root_customer} == null ? "Entity name:" + $F{someField}
:"Customer id:" + + $F{root_customer})

Categories

Resources