This question already has answers here:
How to write a ternary operator (aka if) expression without repeating yourself
(17 answers)
Is using Optional.ofNullable as a replacement for the ternary operator a good practice?
(6 answers)
Avoid violation of DRY with ternary?
(2 answers)
Closed 2 years ago.
I'm fairly new to Java and I'm trying to check if a variable is null and use its value if its not. Previous developer wrote something like this:
xModel.setName(xService.getName(xID) != null ? xService.getName(xID) : "");
And I would like to refactor it so I wouldn't have to use xService twice to just get the name.
I know I can store the value beforehand but this is just an example. I just wonder if there is a way to do this in Java?
Thanks.
I disagree with all other answers. They require special functionality from specific versions by importing structures from the standard library, or obscure calls that works in this specific case, and all in all just hides the simplicity of what you're trying to do.
Keep it simple (KISS). Don't introduce more complexity and concepts when you don't need them. You're refactoring another developers code, which means this is a project where someone else will probably be reading your code later on. So keep it dead simple.
String name = xService.getName(xID);
xModel.setName(name != null ? name : "");
This is more readable than all other examples and doesn't require intimate knowledge of the standard library and its API.
Objects.toString​( Object o, String nullDefault )
In this particular case you can use java.util.Objects.toString. Second argument is a default value to use in case of a null in the first argument.
xModel.setName(Objects.toString(xService.getName(x.ID), ""));
What you have is already the best core Java can do pre Java 8. From 8 onwards, you may use optionals:
xModel.setName(Optional.ofNullable(xService.getName(xID)).orElse(""));
Related
This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 6 years ago.
i have a string with a math function, like "35+20". i want a new double variable that takes in the result of the math function i.e, 55.0 How do i achieve this? this is actually for android, i'm making a calculator..
Manually parse the string and do a calculation at each operator symbol. It will get more complicated when dealing with brackets, however.
If you want to write it yourself, you'll probably want to implement the Shunting Yard Algorithm.
There are also some libraries that handle it for you.
https://github.com/uklimaschewski/EvalEx
Since you have mentioned you are working on a calculator I am assuming that you might not only be interested in just the + operation but on a bunch of other stuffs too.
You can look in to open source GitHub project linked below which provides the JAVA implementation for the stuff you are trying to do https://github.com/uklimaschewski/EvalEx
which can give you a good set of functionality that you desire.
This project takes in a string as an expression and the returns the result in BigDecimal format.
You can always extend it and tweek it to custom suite you needs.
This question has already been asked, but the answers seem to be incomplete. What does the first colon in the following context mean?
import hudson.model.SCMS;
(...)
SCMS: for (SCM scm : scmTriggerItem.getSCMs()) {
(...)
Additionally, the colon has some new uses in Java 8.
This question (which has originally been asked two years ago) is different from loop-in-java-code, because it is wider. While the answers of the original question do not mention the use of the colon as label, which is answered in question "loop-in-java-code", the latter question doesn't ask for the use of the colon within for loops nor in Java 8.
As the answer from biziclop shows, there are colon usages in the Java syntax that are easily forgotten and not mentioned in the other two questions.
There are four six uses of the : character in the Java language.
To denote a label. Labels can be used to break or continue to in loops.
In an enhanced for statement (also called for-each statement), which allows easy iteration across collections and arrays.
As one half of the ?: conditional operator.
And since Java 8, as part of the :: method reference operator.
In a switch statement, after case or default.
And you can also use it in an assert statement to specify an error message when the assertion fails.
In your case, SCMS: is a label, while for (SCM scm : scmTriggerItem.getSCMs()) is an enhanced for statement.
You can always look up the full syntax reference of Java here. It is amazingly dull but without it I easily missed two of the six cases.
This question already has answers here:
Interview : Java Equals
(7 answers)
Closed 8 years ago.
Is there a performance impact, assuming str is a java.lang.String, of using "String".equals(str) vs str.equals("String")? My gut says, "No, the JVM / compiler will optimize the literal string in either case", but I see the first style crop up enough in various codebases and it just looks so unnatural (at least to me), so I figured there must be a reason besides style.
The only reason for using "String".equals(str) (which I find ugly) is laziness, as it saves you the need to check that str != null prior to calling str.equals("String").
Performance-wise there shouldn't be any difference. You are comparing two String instances either way.
"String".equals(str)
Does not yield the same result as
str.equals("String")
if str == null.
In the first case, it returns false, in the second, it throws a NullPointerException.
"String".equals(str)
Is in fact equivalent to
str != null && str.equals("String")
This question already has answers here:
Method for evaluating math expressions in Java
(8 answers)
Closed 9 years ago.
I tried searching for it via google and here but I'm not finding questions to what I mean (search engines don't understand the context by which I mean function).
Essentially I want to do the following
double f(String function, double a){
return function.Function(a);
}
What would happen is the string function is of the form "x^2+2" it would likely be converted somehow to "x.pow(2) + 2" and then x is replaced by a and the result of the function is returned.
Is there any Java class or method that does what I said (or simple way to do it)? Or any code from another source that does what I said or a variant.
I don't have to code what I said, I just need f(x) to solve root finding problems for any function string passed as input. I thought Java would have such a method somewhere but I can't find it.
So, in Java you have an essential problem because you cannot directly convert a String to a mathematical expression. Your options are as follows:
Search for a library that can convert a particularly formatted string to a mathematical expression.
Parse the string yourself. String parsing is difficult and error prone, and the Java around this would be difficult.
Use Scala, which would allow you to directly compose functions to pass into your function, rather than trying to do the expensive conversion from a human-readable string to a machine-interpretable function. Note that Scala is interoperable with Java, but has a bit of a learning curve. Other functional languages can handle this as well, but may lack interoperability.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there a java equivalent of the python eval function?
There is a String, something like String str = "if a[0]=1 & a[1]=2". How to use this string in a real IF THEN expression? E.g.:
for (Integer[] a : myNumbers) {
if a[0]=1 & a[1]=2 { // Here I'd like to use the expression from str
//...
}
}
Java isn't a scripting language that supports dynamic evaluation (although it does support script execution). I would challenge you to check to see if what you're attempting to do is being done in the right way within Java.
There are two common ways you can approach this, listed below. However they have a significant performance impact when it comes to the runtime of your application.
Script Execution
You could fire up a ScriptEngine, build a ScriptContext, execute the fragment in Javascript or some other language, and then read the result of the evaluation.
http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/
Parsing
You could build a lexical parser that analyses the string and converts that into the operations you want to perform. In Java I would recommend you look at JFlex.
http://www.javaworld.com/javaworld/jw-01-1997/jw-01-indepth.html
http://en.wikipedia.org/wiki/Lexical_analysis
http://jflex.de/
I don't think you can do what you're asking.
Also your java doesn't seem to make much sense. Something like this would make more sense:
for (Integer a : myNumbers) {
if (a.equals(Integer.valueOf(1))){
//...
}
}
You can however say:
if("hello".equals("world")){
//...
}
And you can build a string:
String str = "if "+a[0]+"=1 & "+a[1]+"=2"
And you can put that together and say:
String str = "if "+a[0]+"=1 & "+a[1]+"=2"
if(str.equals("if 1=1 & 2=2")){
//...
}
But I think you're probably just trying to do something the wrong way