Can someone please explain what this line of java code is doing?
public String getTitleNavContainer(boolean isThisLandingPage) {
return isThisLandingPage ? StringUtils.EMPTY : "title-nav-container";
}
I can see what it is doing but I am wondering how I would modify this so that if it is landing page it does one thing otherwise do something else.
Thanks for your help.
return isThisLandingPage ? StringUtils.EMPTY : "title-nav-container";
is the same as:
public String getTitleNavContainer(boolean isThisLandingPage) {
if ( isThisLandingPage ){
return StringUtils.EMPTY;
}
else{
return "title-nav-container";
}
}
It's just a shorter way to write it, making the code easier to read.
The above line is called ternary operator
Ternary Operator takes three parameter and its sudo code is
condition ? statement1 : statement2
Condition: This part should have valid conditional statement and that should return only boolean value
Statement1: If condition is true then statement1 will execute
Statement2: If condition is false then statement2 will execute
Now look at your code block
public String getTitleNavContainer(boolean isThisLandingPage) {
return isThisLandingPage ? StringUtils.EMPTY : "title-nav-container";
}
if isThisLandingPage is true then StringUtils.EMPTY will execute else title-nav-container execute
For quick understanding, convert the code as if-else statement
if (isThisLandingPage)
{
return StringUtils.EMPTY;
}
else
{
return title-nav-container;
}
You are using the ternary operator (or the conditional operator) is an alternative to the Java if/then/else syntax, but it goes beyond that, and can even be used on the right hand side of Java statements.
Basically it evaluates the predicate
;(boolean expression) (if it is true) (if it is false)
isThisLandingPage ? StringUtils.EMPTY : "title-nav-container";
And this expression returns that value depending on the boolean expression, this value is the one that the function returns the Empty String "" from this class doc or the String "title-nav-container".
I hope this help you
Related
I'm curious is it possible to call a method that returns a boolean value in the condition part of a while loop?
As in:
while(someMethod()!= true){
//Do stuff
}
And the method simply returns a true or false. Is this possible or not and if so is there a correct syntax or a better way?
Edit: Thanks for the quick responses. As an extension to my question is it possible to call the method multiple times for different things but require them all to be the same before exiting the loop?
For example:
while(!(someMethod(input_a) == someMethod(input_b))){
//Do stuff
}
Where both of the returned values are the returned values are equal?
Hope this will help you
public boolean functionOne(int i){
// some operation
if(i == 1) return true;
else return false;
}
public void otherFunc(){
int i = 0;
if(functionOne(i)) { // e.g: if(functionOne(i) == true)
// your code
// 0!=1 so result is fort
}
if(!functionOne(i)){ // e.g: if(functionOne(i) == false)
// your code
// 0!=1 it is false, but ! before functionOne negate so ! of false is true
}
// **for your while**
while(functionOne(i)){ // while function returns true
// code
}
// **or**
while(!functionOne(i)){ // while function returns false
// code
}
}
Yes of course!
public static boolean someMethod(){
return false;
}
public static void main(String[] args){
while(!someMethod()){
//do something
System.out.println("Hi");
}
}
Like in this code, an infinite loop will be called if the method returns false, but if the method returns true, it will just come out of the while loop. :)
Less is best:
while (!someMethod()) {
// Do stuff
}
It's never a good idea to compare to a boolean result to a boolean literal. Prefer using the result in-line, using the logical unary not operator ! as required.
Answering the now-edited version of the question, less is still best:
while (someMethod(input_a) != someMethod(input_b))
You can find the specification of the while loop in JLS Sec 14.12:
The while statement executes an Expression and a Statement repeatedly until the value of the Expression is false.
WhileStatement:
while ( Expression ) Statement
WhileStatementNoShortIf:
while ( Expression ) StatementNoShortIf
The Expression must have type boolean or Boolean, or a compile-time error occurs.
So, you can use anything which is an Expression of type boolean (or Boolean).
And if you click through the productions in the language spec:
Expression, contains
AssignmentExpression, contains
ConditionalExpression, contains
ConditionalOrExpression, contains
ConditionalAndExpression, contains
InclusiveOrExpression, contains
ExclusiveOrExpression, contains
AndExpression, contains
EqualityExpression, contains
RelationalExpression, contains
ShiftExpression, contains
AdditiveExpression, contains
MultiplicativeExpression, contains
UnaryExpression, contains
UnaryExpressionNotPlusMinus, contains
PostfixExpression, contains
Primary, contains
PrimaryNoNewArray, contains
MethodInvocation
Phew! That's pretty deeply buried! (You can read this like an inheritance hierarchy, so every MethodInvocation is a PrimaryNoNewArray, and every PrimaryNoNewArray is a Primary etc).
So, transitively, every MethodInvocation is an Expression, hence it's fine to use it as the expression in a while loop.
Addressing your edit: yes, that's fine too. If you look at the detail of the EqualityExpression:
EqualityExpression:
RelationalExpression
EqualityExpression == RelationalExpression
EqualityExpression != RelationalExpression
As already described above, you can use an EqualityExpression as the Expression in a WhileStatement. And something of the form
RelationalExpression != RelationalExpression
is an EqualityExpression by the rule shown. Since all MethodInvocations are RelationalExpressions, you can use method invocations in the while statement as you've shown:
while(someMethod(input_a) != someMethod(input_b)) {
(a != b is an easier way of writing !(a == b)).
This is the way we have done loops over java iterators. For instance:
Iterator[String] iterator = util.Arrays.asList("One", "Two", "Three").iterator();
while(iterator.hasNext()) {
println(iterator.next());
}
We have also done something similar for the JDBC ResultSet interface.
Basically I have a if..else logic as below
if(request.getParameter("action")=="delete" && request.getParameter("action")!=null)
{
//delete operation
}
else
{
//update operation
}
But during update process "action" parameter do not get attached with URL and hence NullPoitnerException is thrown.
Any solution to fix it?
Thanks in advance!
If your request.getParameter(x) returns null when x is not set, you could simply swap the two conditions in your if-clause.
Thus
if(request.getParameter("action")=="delete" && request.getParameter("action")!=null)
would become
if(request.getParameter("action")!=null && request.getParameter("action")=="delete")
Since && is a short-circuit Boolean And in Java, this will cause the the second half of the statement to be executed only if the part before the && evaluates to true - thereby preventing your NullPointerException.
request.getParameter("action")=="delete" is a comparison with a string literal, though. You are most likely better off using .equals() instead.
In Java 8 you can do like this
Optional<String> paramOptional=Optional.ofNullable(request.getParameter());
paramOptional.ifPresent(param->{
//Do something with param
});
OR
String param =paramOptional.orElse("you else string");//if null then this string will be return
Netbeans gives me The conditional statement is redundant warning for this:
return (this.getId(person) == null) ? false : true;
And if I comply with that, it changes to this:
return (this.getId(person) != null);
Are these two equal? How is the second one conditional?
Yes , They both are conceptually same.
The second one is not conditional. Its an expression resolves into boolean, So simply you can result of that expression.
Why it is redundant in first case is , It's just like writing
if(true){
return true;
}else{
return false;
}
Look at your condition
this.getId(person) != null;
your this.getId(person) may be null or may not. So that expression resolves as true or false . That's it. Right ? So your IDE is telling that use that expression result.
You can unwrap the first form to something like this:
boolean cnd = (this.getId(person) == null);
if (cnd)
return true;
else
return false;
This clearly shows that switching on a boolean value just to return the same boolean value is redundant.
The second statement is not conditional but it provides the same result with fewer hops.
The expression this.getId(person) == null will return you true or false. Again adding a ternary operator is redundant.
You are returning a boolean value and
return (this.getId(person) != null);
is a boolean conditional statement that will evaluate to true or false. This is why the compiler is telling you that the conditional statement is redundant. It will still compile the other way but its more typing and it's not as clean.
class string1 {
static public void main(String[] ar) {
String s1 = "test";
String s2 = new String();
if(s2=null) { // line 0
System.out.println(s1);
System.out.println(s2.length()); //Line 1
}
}
}
What i expected to happen was
a) s2 will be set to null because its an assignment operation as I am not using ==
b) And I will get a NPE at Line 1 during Runtime
and instead I got the following output as shown below.
Output is
if(s2=null)
^
required: boolean
found: String
1 error
Can someone explain why I am getting compile error ?
Java will not implicitly cast to a boolean like some languages will. You must put an expression that evaluates to a boolean inside of conditional:
if ((s2 = null) != null) { }
This condition of course makes no sense, but it's the equivalent of what you're attempting to do. It's worth noting by the way that assignments should rarely be done in a condition.
You should do like this:
if( (s2 = null) != null)
{
// do stuff
}
The reason you are getting this error because you have to explicitly put the code for boolean evaluation in conditions as Java doesn't implicitly cast it boolean.
The if condition evaluates only boolean conditions.
And the assignment operator does not give a boolean result here.
That is the reason for getting exception.
If you use if ((s2 = null) != null) instead of if(s2=null) it will work.
You should note the fact that in java there are only two boolean values : true and false unlike some other languages which use 0 as false and anything else as true .
Can someone explain why I am getting compile error ?
In an if statement the condition can either be true or false which are returned by comparison operations and by the boolean variables.
In,
if(s2=null)
the s2=null doesn't evaluate to any boolean value i.e, true or false therefore the compiler error :
required: boolean
found: String
An if-then statement is executed by first evaluating the Expression.
From, JLS - Chapter14 : Blocks and Statements
14.9.1. The if-then Statement
An if-then statement is executed by first evaluating the Expression.
If the result is of type Boolean, it is subject to unboxing
conversion (ยง5.1.8).
If evaluation of the Expression or the subsequent unboxing conversion
(if any) completes abruptly for some reason, the if-then statement
completes abruptly for the same reason.
Otherwise, execution continues by making a choice based on the
resulting value:
If the value is true, then the contained Statement is executed; the
if-then statement completes normally if and only if execution of the
Statement completes normally.
If the value is false, no further action is taken and the if-then statement completes normally.
Besides what everyone else said, s2 will never be null - you just assigned a new String to it! Are you sure you're not conflating string length/existence tests from other languages?
I work with a Java project and Eclipse(Version 3.6.2) as IDE, in a enum comparison i get a strange behaviour, following an example of the weirdness :
Global Variable :
StatusType status = StatusType.SIGNATURE;
Code :
String trsStatus = "END";
if(trsStatus.equals("END") && (this.status.compareTo(StatusType.SIGNATURE) != 0)){
//Do something
}
This comparison succeeds and enter in the if block, Why ? In this case the second evaluation(this.status.compareTo(StatusType.SIGNATURE) != 0) of the if statements fail because the result is false ! Why java however enter in the block ???
If i evaluate the expression on the expression watcher of eclipse debugger the value of the statements are :
trsStatus.equals("END") ---> true
(this.status.compareTo(StatusType.SIGNATURE) != 0) ---> false
I've done another test, if i assign the result of the second expression in the if statements to a boolean variable :
boolean sign = (this.status.compareTo(StatusType.SIGNATURE) != 0);
i get this result :
(this.status.compareTo(StatusType.SIGNATURE) != 0) ---> false
sign ---> true
Why ?!?
How this can be possible ?
Could it be that StatusType overrides compareTo() in some weird way?
Are there any other threads that could be changing the value of the status field?
In any case, you should use equals() or even == rather than compareTo() here.
this.status.compareTo(StatusType.SIGNATURE) != 0 will return zero, because zero means they are equal. compareTo() returns either 1, -1, or 0, based on which value is considered greater.
The only sensible reason I could imagine is that
this.status != StatusType.SIGNATURE
Period. You probably set status to some other value unknowingly. Maybe with another thread. Who knows. What does status evaluate to, in your debugger?
In any case, there is certainly no such "bug" in Java. Unless you post some more code that proves it ;-)
You should use: this.status != StatusType.SIGNATURE.
public class Test {
public static void main(String[] args) {
TestEnum e = TestEnum.SIGNATURE;
System.out.println(e.compareTo(TestEnum.SIGNATURE));
String test = "test";
if (test.equals("test") && e.compareTo(TestEnum.SIGNATURE) != 0) {
System.out.println("I'm here");
}
}
}
I did the following test. It does not enter the if block and print "I'm here".
Can you post your snippet?