Java tryParseInt best practice [duplicate] - java

This question already has answers here:
Best implementation for an isNumber(string) method
(19 answers)
Closed 7 years ago.
I have a lot of code that gathers user input and parses it,
I want to parse integer values without throwing exceptions.
My current tryParseInt() function is code is simple:
public static Integer tryParseInt( String text )
{
if(text == null)
return null;
try
{
return new Integer( text.trim() );
}
catch ( NumberFormatException e )
{
return null;
}
}
But i am getting lots of NumberFormatExceptions and i am worried becouse that may impact my app performance.
Can anyone suggest me on best practice for parsing user inputs.
Thank you

You can go with regex as it is more fail proof
public static Integer tryParseInt(String text) {
if (text != null && !text.isEmpty()) {
if (text.trim().matches("[0-9]+")) {
return Integer.valueOf(text.trim());
}
}
return null;
}

This is a very helpful experiment and indeed my experience is removing exceptions is better for performance

If you are getting a lot of NumberFormatExceptions, you might consider checking the parsing input before the actual parsing.
BTW the return new Integer( text.trim() ); is not very efficient as you will be allocating a lot of unnecessary objects (in the range from -128 to 127).
public static Integer tryParseInt(String text) {
if(text == null)
return null;
try {
return Integer.valueOf(text.trim());
}
catch (NumberFormatException e) {
return null;
}
}

Related

Java - How to deal with null value passed by argument? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I wrote this simple function:
private String getOperatorForCardinality(String op)
{
String operator ="";
if(op!=null)
{
if(op.equals(">="))
{
operator = ">=";
}
else if (op.equals("<="))
{
operator = "<=";
}
}
else
{
operator = "empty";
}
return operator;
}
which returns a string.
In the main program I call this function, when the argument is null the compiler displays the error of NullPointerException.
The reason is pretty clear, but I do not know how to deal with the null value when is passed by argument.
It is impossible for the code you posted to throw a NPE. The error is somewhere else, or you are not running the code you think you are (ie haven't recompiled etc).
That said, your method can be simplified to:
private static List<String> OPS = Arrays.asList("<=", ">="); // can add more valid ops
private static String getOperatorForCardinality(String op) {
if (op == null)
return "empty";
return OPS.contains(op) ? op : "";
}
Or if you don't mind nested ternaries:
private static String getOperatorForCardinality(String op) {
return OPS.contains(op) ? op : op == null ? "empty" : "";
}
Less code is usually clearer code, and leaves less places for bugs to lurk.
It is called defensive programming and you should do something like:
private String getOperatorForCardinality(String op) {
if(null == op) {
//return null;
//throw new NullPointerException("...");
}
....
}
You should think about how your method should react, need to return null if parameter is null or throw an exception? Generally you cant be sure a parameter will never be null so you have always to check and take action.
This can't throw a null pointer exception:
private String getOperatorForCardinality(String op)
{
String operator = "";
if(">=".equals(op))
{
operator = ">=";
}
else if ("<=".equals(op))
{
operator = "<=";
} else {
operator = "empty";
}
return operator;
}
try opposite
if (op==null)
operator = "empty";

Check if a String is Integer [duplicate]

This question already has answers here:
What's the best way to check if a String represents an integer in Java?
(40 answers)
Closed 7 years ago.
I need to check whether the String is an Integer. And I found such solution:
private boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Is there a more beautiful and proper way to do this without try/catch clause?
You can try a regex like:
Code
private boolean isInteger(String str) {
return str.matches("\\-?\\d+");
}
Edit
Thanks #Maloubobola for noting that my first attempt would not parse signed integers.
You can try regex. Here is one for positive and negative numbers
private boolean isInt(String string) {
return string.matches("-?\\d+");
}

How can I loop through Exception getCause() to find root cause with detail message [duplicate]

This question already has answers here:
Java - find the first cause of an exception
(12 answers)
Closed 3 years ago.
I am trying to call saveOrUpdate() in hibernate to save data. Since columns have unique index, so its throws ConstraintViolationException when I look through via Eclipse debugger.
Since root cause could be different for different exception while inserting data to table.
I wanted to know, how can I loop / traverse through getCause() to check what is the root cause of exception and its message.
Update:
Thanks everyone for your kind response, thing is I want output like in below image:
I need to access detailMessage field.
(I am really sorry If could not make my question more clear.)
Thanks.
The Apache ExceptionUtils provide the following method:
Throwable getRootCause(Throwable throwable)
as well as
String getRootCauseMessage(Throwable th)
I normally use the implementation below instead of Apache's one.
Besides its complexity, Apache's implementation returns null when no cause is found, which force me to perform an additional check for null.
Normally when looking for an exception's root/cause I already have a non-null exception to start with, which is for all intended proposes is the cause of the failure at hand, if a deeper cause can't be found.
Throwable getCause(Throwable e) {
Throwable cause = null;
Throwable result = e;
while(null != (cause = result.getCause()) && (result != cause) ) {
result = cause;
}
return result;
}
Using java 8 Stream API, this can be achieved by:
Optional<Throwable> rootCause = Stream.iterate(exception, Throwable::getCause)
.filter(element -> element.getCause() == null)
.findFirst();
Note that this code is not immune to exception cause loops and therefore should be avoided in production.
Are you asking for something like this?
Throwable cause = originalException;
while(cause.getCause() != null && cause.getCause() != cause) {
cause = cause.getCause();
}
or am I missing something?
Guava's Throwables provides the following methods:
Throwable getRootCause(Throwable throwable)
as well as
String getStackTraceAsString(Throwable throwable)
In APACHE; the implementation is like below.
The highlight is list.contains(throwable) == false
public static Throwable getRootCause(final Throwable throwable) {
final List<Throwable> list = getThrowableList(throwable);
return list.size() < 2 ? null : (Throwable)list.get(list.size() - 1);
}
public static List<Throwable> getThrowableList(Throwable throwable) {
final List<Throwable> list = new ArrayList<Throwable>();
while (throwable != null && list.contains(throwable) == false) {
list.add(throwable);
throwable = ExceptionUtils.getCause(throwable);
}
return list;
}
} catch (Exception ex) {
while (ex.getCause() != null)
ex = ex.getCause();
System.out.println("Root cause is " + ex.getMessage());
}
Were you expecting something more complicated?
Try this, you can put this function in a kind of Util class:
public static Throwable getRootException(Throwable exception){
Throwable rootException=exception;
while(rootException.getCause()!=null){
rootException = rootException.getCause();
}
return rootException;
}
Example of usage :
catch(MyException e){
System.out.println(getRootException(e).getLocalizedMessage());
}
Source : How to get the root exception of any exception
Recursively:
public static Throwable getRootCause(Throwable e) {
if (e.getCause() == null) return e;
return getRootCause(e.getCause());
}

How avoid multiple IF loops in Java [duplicate]

This question already has answers here:
Avoiding NullPointerException in Java
(66 answers)
Closed 9 years ago.
What is the best way to avoid multiple if blocks which is used for null checks in Java?
The following is my sample code. Which one is the most optimized way?
if (address!=null} {
if (firstName!=null) {
if (lastName!=null) {
}
}
}
Use &&. && is logical and. && combines two values and returns a boolean which is true if and only if both of its operands are true
if(address!=null && firstName!=null && lastName!=null)
{
}
For instance
boolean b;
b = 3 > 2 && 5 < 7; // b is true
b = 2 > 3 && 5 < 7; // b is now false
if loop is a wrong word. You should say if statements As in you case you can use OR (||) or AND (&&)statement like this
if(address!=null && firstName!=null && lastName!=null)
{
}
Try AND(&&) if you want to pass all checks or intead of nested if statements and try OR(||) for non nested like else if or simply say if you want to pass anyone of your condition But
if all of these are Strings then you should try like this
"yourValue".equals(stringValue)This will skip the null check.
Use and operator (&&)
if(address!=null && firstName!=null && lastName!=null)
{
//DoSomething here
}
And I suggest you to see Short circuit evaluation
there are no if LOOPS
boolean complete = address != null && firstName != null && lastName != null;
if (complete)
{
}
What about:
public boolean notNulls(Object ... args) {
for(Object arg : args)
if (arg == null) return false;
return true;
}
Use:
if (notNulls(address, firstName, lastName)) {
// do something
}
As others point out, a logical and (&&) is probably the best way to consolidate your logic. An && operation will only evaluate to true if both sides evaluate to true.
if (address != null && firstName != null && lastName != null) {
// Whatever you want to do with that...
} else {
// Whatever you want to do with bad input
}
For the sake of diversity, you could also use a try-catch approach. In Java, a NullPointerException will be thrown if you try to call a method on a null value, which you can catch and handle.
try {
// Whatever you want to do with that...
} catch (NullPointerException npe) {
// Whatever you want to do with bad input
}
This approach can be helpful if you've got a really big set of inputs that might be null, although in general I wouldn't advocate it. (The problem with the second approach is that if you call some other method from the try part that triggers a NullPointerException, it will end up in the catch block here, even though it may be totally unrelated to these inputs - i.e. you could make it hard for yourself to spot a bug in a different part of your program.)

How can I tell if a Java integer is null?

Greetings,
I'm trying to validate whether my integer is null. If it is, I need to prompt the user to enter a value. My background is Perl, so my first attempt looks like this:
int startIn = Integer.parseInt (startField.getText());
if (startIn) {
JOptionPane.showMessageDialog(null,
"You must enter a number between 0-16.","Input Error",
JOptionPane.ERROR_MESSAGE);
}
This does not work, since Java is expecting boolean logic.
In Perl, I can use "exists" to check whether hash/array elements contain data with:
#items = ("one", "two", "three");
##items = ();
if (exists($items[0])) {
print "Something in \#items.\n";
}
else {
print "Nothing in \#items!\n";
}
Is there a way to this in Java? Thank you for your help!
Jeremiah
P.S. Perl exists info.
parseInt() is just going to throw an exception if the parsing can't complete successfully. You can instead use Integers, the corresponding object type, which makes things a little bit cleaner. So you probably want something closer to:
Integer s = null;
try {
s = Integer.valueOf(startField.getText());
}
catch (NumberFormatException e) {
// ...
}
if (s != null) { ... }
Beware if you do decide to use parseInt()! parseInt() doesn't support good internationalization, so you have to jump through even more hoops:
try {
NumberFormat nf = NumberFormat.getIntegerInstance(locale);
nf.setParseIntegerOnly(true);
nf.setMaximumIntegerDigits(9); // Or whatever you'd like to max out at.
// Start parsing from the beginning.
ParsePosition p = new ParsePosition(0);
int val = format.parse(str, p).intValue();
if (p.getIndex() != str.length()) {
// There's some stuff after all the digits are done being processed.
}
// Work with the processed value here.
} catch (java.text.ParseFormatException exc) {
// Something blew up in the parsing.
}
Try this:
Integer startIn = null;
try {
startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
.
.
.
}
if (startIn == null) {
// Prompt for value...
}
ints are value types; they can never be null. Instead, if the parsing failed, parseInt will throw a NumberFormatException that you need to catch.
There is no exists for a SCALAR in Perl, anyway. The Perl way is
defined( $x )
and the equivalent Java is
anInteger != null
Those are the equivalents.
exists $hash{key}
Is like the Java
map.containsKey( "key" )
From your example, I think you're looking for
if ( startIn != null ) { ...
For me just using the Integer.toString() method works for me just fine. You can convert it over if you just want to very if it is null. Example below:
private void setCarColor(int redIn, int blueIn, int greenIn)
{
//Integer s = null;
if (Integer.toString(redIn) == null || Integer.toString(blueIn) == null || Integer.toString(greenIn) == null )
I don't think you can use "exists" on an integer in Perl, only on collections. Can you give an example of what you mean in Perl which matches your example in Java.
Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.
This indicates it only applies to hash or array elements!
This should help.
Integer startIn = null;
// (optional below but a good practice, to prevent errors.)
boolean dontContinue = false;
try {
Integer.parseInt (startField.getText());
} catch (NumberFormatException e){
e.printStackTrace();
}
// in java = assigns a boolean in if statements oddly.
// Thus double equal must be used. So if startIn is null, display the message
if (startIn == null) {
JOptionPane.showMessageDialog(null,
"You must enter a number between 0-16.","Input Error",
JOptionPane.ERROR_MESSAGE);
}
// (again optional)
if (dontContinue == true) {
//Do-some-error-fix
}

Categories