Why is FindBugs complaining here? - java

public int getFreezeColumns() {
Integer currentValue = (Integer) checkValueBinding("freezeColumns", this.freezeColumns);
if (currentValue != null) {
return currentValue;
}
return 0;
}
FindBugs says :
A primitive is boxed, and then immediately unboxed. This probably is due to a manual boxing in a place where an unboxed value is required, thus forcing the compiler to immediately undo the work of the boxing.
How can I possibly fix this ?

I think the complaint is somewhat misleading: you are not boxing the return value of checkValueBinding which is an Object, but you are casting it to Integer prematurely
Try changing the code to see if it helps you avoid the warning:
public int getFreezeColumns() {
Object currentValue = checkValueBinding("freezeColumns", this.freezeColumns);
if (currentValue != null) {
return (Integer)currentValue;
}
return 0;
}

Seems to me like it's complaining that you are creating an Integer, and then converting it to int right away to return it.
What does checkValueBinding return? Do you really need to wrap it into an Integer?

Related

Returning null in a function that should return an integer

The code identifies the integer that is closest to 0 in an array and if there are 2 or more values that meet this condition the return value should be null.The problem is that when I make the condition to return null it displays an error because the function is supposed to return an integer.
static int function(int [] arr){
int closest=arr[0];
for(int i=1;i<arr.length;i++){
if(Math.abs(arr[i])<closest){
arr[i]=closest;
}
else if(arr[i]==closest){
return null;
}
}
return closest;
}
I am very new to Java (learned Python before),if there is a better/more eficient approach to this code please share.
You can convert the return type to Integer which can hold null and will auto box and unbox to an int:
static Integer function(int [] arr){
int closest=arr[0];
for(int i=1;i<arr.length;i++){
if(Math.abs(arr[i])<closest){
arr[i]=closest;
}
else if(arr[i]==closest){
return null;
}
}
return closest;
}
However this is probably not the best solution. You could instead return Integer.MAX_VALUE to signify that two of the elements were equidistant from zero. This depends on how you plan to handle the case where there are two elements of equal distance to 0.
If you need to support null (e.g. Python's None) then you should return the wrapper type Integer.
static Integer function(int [] arr) {
// ...
}
The obvious answer is to return Integer instead of int.
static Integer function(int[] arr) {
Autoboxing will take care of wrapping the primitive; autounboxing will take care of giving your client code NullPointerException.
But you said efficient, but allocating a genuine object is not efficient (small values will use a common object, but that still isn't great). Throwing an exception would be even less efficient (supposing it happens frequently enough.)
The routine could perhaps return any int value and we want to shove in an extra possible outcode. So one possibility is to go one larger and return a long with Long.MIN_VALUE as the special value. May require casting on the client code to get back to an int.
static Integer function(int[] arr) {
Long.MIN_VALUE is interesting in that Long.MIN_VALUE == Math.abs(Long.MIN_VALUE).
It's at this point we realise there's appears to be a bug in the code (not sure as I really know what it is supposed to be doing).
if(Math.abs(arr[i])<closest){
This is always true for Integer.MIN_VALUE. Probably you want to swap that around with.
if (-Math.abs(arr[i]) > -closest){
Converting to long before doing the comparison is also possible but less clever. (Integer overflows - bleurgh.)
Another way around the problem is to let the client code choose an appropriate value to signal the same as whatever null is supposed to indicate.
static int function(int[] arr, int dflt) {
[...]
} else if (arr[i] == closest) {
return dflt;
[...]

Can we combine two methods that differ largely based on type?

I have two similar, but of different types, blocks of code in Java:
private Integer readInteger() {
Integer value = null;
while (value == null) {
if (scanner.hasNextInt()) {
value = scanner.nextInt();
} else {
scanner.next();
}
}
return value;
}
private Double readDouble() {
Double value = null;
while (value == null) {
if (scanner.hasNextDouble()) {
value = scanner.nextDouble();
} else {
scanner.next();
}
}
return value;
}
Is it possible to make just one method which would work for both of them?
I'd say, use a generic method, combined with the functional interfaces introduced in Java 8.
The method read now becomes a higher order function.
private <T> T read(Predicate<Scanner> hasVal, Function<Scanner, T> nextVal) {
T value = null;
while (value == null) {
if (hasVal.test(scanner)) {
value = nextVal.apply(scanner);
} else {
scanner.next();
}
}
return value;
}
Calling code becomes:
read(Scanner::hasNextInt, Scanner::nextInt);
read(Scanner::hasNextDouble, Scanner::nextDouble);
read(Scanner::hasNextFloat, Scanner::nextFloat);
// ...
So the readInteger() method can be adapted as follows:
private Integer readInteger() {
return read(Scanner::hasNextInt, Scanner::nextInt);
}
You could have something with three methods:
One which says if there is a value of the right type
Another which gets the value of the right type.
Another which discards whatever token you have.
For example:
interface Frobnitz<T> {
boolean has();
T get();
void discard();
}
You can pass this into your method:
private <T> T read(Frobnitz<? extends T> frob) {
T value = null;
while (value == null) {
if (frob.has()) {
value = frob.get();
} else {
frob.discard();
}
}
return value;
}
And then just implement Frobnitz for your Double and Integer cases.
To be honest, I'm not sure this gets you very much, especially if you've only got two cases; I'd be inclined just to suck up the small amount of duplication.
A lot of people have answered that you can use generics, but you can also simply remove the readInteger method, and only use the readDouble, as integers can be converted to doubles without data loss.
This is about code duplication.
The general approach is to turn similar code (you have) into equal code that can be extracted to a common parameterized method.
In your case what make the two code snipped differ is the access to methods of Scanner. You have to encapsulate them somehow. I'd suggest to do this with Java8 Functional interfaces like this:
#FunctionalInterface
interface ScannerNext{
boolean hasNext(Scanner scanner);
}
#FunctionalInterface
interface ScannerValue{
Number getNext(Scanner scanner);
}
Then replace the actual invocation of methods in scanner with the functional interface:
private Integer readInteger() {
ScannerNext scannerNext = (sc)->sc.hasNextInt();
ScannerValue scannerValue = (sc)-> sc.nextInt();
Integer value = null;
while (value == null) {
if (scannerNext.hasNext(scanner)) {
value = scannerValue.getNext(scanner);
} else {
scanner.next();
}
}
return value;
}
There is one more problem that the type of the value variable differs. So we replace it with its common supertype:
private Integer readInteger() {
ScannerNext scannerNext = (sc)->sc.hasNextInt();
ScannerValue scannerValue = (sc)-> sc.nextInt();
Number value = null;
while (value == null) {
if (scannerNext.hasNext(scanner)) {
value = scannerValue.getNext(scanner);
} else {
scanner.next();
}
}
return (Integer)value;
}
Now you have to places with a big equal section. You can select one of those sections starting with Number value = null; ending with the } before return ... and invoke your IDEs automated refactoring extract method:
private Number readNumber(ScannerNext scannerNext, ScannerValue scannerValue) {
Number value = null;
while (value == null) {
if (scannerNext.hasNext(scanner)) {
value = scannerValue.getNext(scanner);
} else {
scanner.next();
}
}
return value;
}
private Integer readInteger() {
return (Integer) readNumber( (sc)->sc.hasNextInt(), (sc)-> sc.nextInt());
}
private Double readDouble() {
return (Double) readNumber( (sc)->sc.hasNextDouble(), (sc)-> sc.nextDouble());
}
Comments argue against the use of custom interfaces against predefined interfaces from the JVM.
But my point in this answer was how to turn similar code into equal code so that it can be extracted to a single method rather that giving a concrete solution for this random problem.
Not an ideal solution but it still achieves the necessary removal of duplicate code and has the added benefit of not requiring Java-8.
// This could be done better.
static final Scanner scanner = new Scanner(System.in);
enum Read{
Int {
#Override
boolean hasNext() {
return scanner.hasNextInt();
}
#Override
<T> T next() {
return (T)Integer.valueOf(scanner.nextInt());
}
},
Dbl{
#Override
boolean hasNext() {
return scanner.hasNextDouble();
}
#Override
<T> T next() {
return (T)Double.valueOf(scanner.nextDouble());
}
};
abstract boolean hasNext();
abstract <T> T next();
// All share this method.
public <T> T read() {
T v = null;
while (v == null) {
if ( hasNext() ) {
v = next();
} else {
scanner.next();
}
}
return v;
}
}
public void test(String[] args) {
Integer i = Read.Int.read();
Double d = Read.Dbl.read();
}
There are some minor issues with this such as the casting but it should be a reasonable option.
A totally different approach from my other answer (and the other answers): don't use generics, but instead just write the methods more concisely, so you don't really notice the duplication.
TL;DR: rewrite the methods as
while (!scanner.hasNextX()) scanner.next();
return scanner.nextX();
The overall goal - write it as a single method - is only possible if you accept some amount of additional cruft.
Java method signatures do not take into account the return type, so it's not possible to have a next() method return an Integer in one context, and Double in another (short of returning a common supertype).
As such, you have to have something at the call sites to distinguish these cases:
You might consider passing something like Integer.class or Double.class. This does have the advantage that you can use generics to know that the returned value matches that type. But callers could pass in something else: how would you handle Long.class, or String.class? Either you need to handle everything, or you fail at runtime (not a good option). Even with a tighter bound (e.g. Class<? extends Number>), you still need to handle more than Integer and Double.
(Not to mention that writing Integer.class and Double.class everywhere is really verbose)
You might consider doing something like #Ward's answer (which I do like, BTW: if you're going to do it with generics, do it like that), and pass in functional objects which are able to deal with the type of interest, as well as providing the type information to indicate the return type.
But, again, you've got to pass these functional objects in at each call site, which is really verbose.
In taking either of these approaches, you can add helper methods which pass the appropriate parameters to the "generic" read method. But this feels like a backwards step: instead of reducing the number of methods to 1, it's increased to 3.
Additionally, you now have to distinguish these helper methods somehow at the call sites, in order to be able to call the appropriate one:
You could have overloads with a parameter of value type, rather than class type, e.g.
Double read(Double d)
Integer read(Integer d)
and then call like Double d = read(0.0); Integer i = read(0);. But anybody reading this code is going to be left wondering what that magic number in the code is - is there any significance to the 0?
Or, easier, just call the two overloads something different:
Double readDouble()
Integer readInteger()
This is nice and easy: whilst it's slightly more verbose than read(0.0), it's readable; and it's way more concise that read(Double.class).
So, this has got us back to the method signatures in OP's code. But this hopefully justifies why you still want to keep those two methods. Now to address the contents of the methods:
Because Scanner.nextX() doesn't return null values, the method can be rewritten as:
while (!scanner.hasNextX()) scanner.next();
return scanner.nextX();
So, it's really easy to duplicate this for the two cases:
private Integer readInteger() {
while (!scanner.hasNextInt()) scanner.next();
return scanner.nextInt();
}
private Double readDouble() {
while (!scanner.hasNextDouble()) scanner.next();
return scanner.nextDouble();
}
If you want, you could pull out a method dropUntil(Predicate<Scanner>) method to avoid duplicating the loop, but I'm not convinced it really saves you that much.
A single (near-)duplicated line is way less burdensome in your code than all those generics and functional parameters. It's just plain old code, which happens to be more concise (and, likely, more efficient) than "new" ways to write it.
The other advantage of this approach is that you don't have to use boxed types - you can make the methods return int and double, and not have to pay the boxing tax unless you actually need it.
This may not be of advantage to OP, since the original methods do return the boxed type; I don't know if this is genuinely desired, or merely an artefact of the way the loop was written. However, it is useful in general not to create those objects unless you really need them.
Reflection is an alternative if you don't care about performance.
private <T> T read(String type) throws Exception {
Method readNext = Scanner.class.getMethod("next" + type);
Method hasNext = Scanner.class.getMethod("hasNext" + type);
T value = null;
while (value == null) {
if ((Boolean) hasNext.invoke(scanner)) {
value = (T) readNext.invoke(scanner);
} else {
scanner.next();
}
}
return value;
}
Then you call
Integer i = read("Int");

Way to parseInt without try-catch in Java 8?

Is there a better way to try to convert to int a string that can be or not an integer?
Integer.parseInt(String value) will work well with "25" or "019" but not with "hello" or "8A".
In Java 8, we have optional values, for example:
public static void main(String[] args) {
Optional<Integer> optionalResult = functionThatReturnsOptionalInteger();
Integer finalValue = optionalResult.orElse(0);
System.out.println(finalValue);
}
public static Optional<Integer> functionThatReturnsOptionalInteger() {
Integer[] ints = new Integer[0];
return Stream.of(ints).findAny();
}
You do not need to check nulls, because the Optional wrapper expose useful methods to deal with this kind of situations.
But if you want to parseInt a string, that can be null, or does not contains a valid integer, the solution is the same as always:
public static Integer parseIntOrDefault(String toParse, int defaultValue) {
try {
return Integer.parseInt(toParse);
} catch (NumberFormatException e) {
return defaultValue;
}
}
How can improve this with Java 8 features, why Integer.parseInt() has not been overloaded to return an Optional in case of bad argument? (Or just add a new method Integer.parseIntOptional() to Integer wrapper)
There doesn't exist anything like this in the standard library afaik, but you can write a method that parses a String into an Optional<Integer> like this:
public static Optional<Integer> parseInt(String toParse) {
try {
return Optional.of(Integer.parseInt(toParse));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
Unlike other answers that are now deleted, I don't think this really has to do with Java being backwards-compatible.
Because an empty Optional represents a value that is absent, it would mean that the method actually worked but no results are returned.
However, parsing hello as an integer will not work and has to throw an exception, because it is an error rather than an empty result. Keep in mind that NumberFormatException extends IllegalArgumentException.
More generally speaking, Optional was made for dealing with possibly absent values (instead of using null for that), and not for error handling. Also, Optional doesn't provide any way to know what is the error and why there is one.
I don’t want to speculate why such method does not exist, but if you like neither, perform a pre-test nor catch an exception, you need a re-implementation, e.g.
public static OptionalInt parseInt(String s) {
if(s.isEmpty()) return OptionalInt.empty();
final int len = s.length(), limit;
final boolean negative;
int i = 0;
switch(s.charAt(0)) {
case '-':
i=1;
if(len==1) return OptionalInt.empty();
negative = true;
limit = Integer.MIN_VALUE;
break;
case '+':
i=1;
if(len==1) return OptionalInt.empty();
// fall-through
default:
negative = false;
limit = -Integer.MAX_VALUE;
}
final int limitBeforeMul = limit / 10;
int result = 0;
for(; i < len; i++) {
int digit = Character.digit(s.charAt(i), 10);
if(digit < 0 || result < limitBeforeMul || (result *= 10) < limit + digit)
return OptionalInt.empty();
result -= digit;
}
return OptionalInt.of(negative? result: -result);
}
This basically does the same as Integer.parseInt, but returns an empty OptionalInt for invalid strings instead of throwing an exception…
As you might notice, the hardest part is to handle numbers close to Integer.MIN_VALUE resp. Integer.MAX_VALUE correctly.
Without a try-catch and still returning an Optional - you could do
Optional<Integer> result = Optional.ofNullable(input)
.filter(str -> str.matches("-?\\d+"))
.map(Integer::parseInt);
EDIT: Regex updated to support negative numbers
WARNING: As pointed out in the comments, will still throw a RuntimeException if the parsed String turns out to be outside the range of Integer.MIN_VALUE and Integer.MAX_VALUE
Google's Guava library provides a helper method to do this: Ints.tryParse(String).It runs null when the string is not parsable. You can checkout the documentation.
Using Mutiny it can be written like this.
If you just want to do something with the result you could do it in a single expression
Uni.createFrom()
.item(() -> Integer.parseInt(toParse))
.onFailure().recoverWithItem(defaultValue)
.subscribe().with(i -> System.out.println(i));
Or create a method like the one intended
public static Integer parseIntOrDefault(String toParse, int defaultValue) {
Integer[] toReturn = new Integer[]{null};
Uni.createFrom()
.item(() -> Integer.parseInt(toParse))
.onFailure().recoverWithItem(defaultValue)
.subscribe().with(i -> toReturn[0] = i);
return toReturn[0];
}
This solution adds a library, but the lib is not specific to handle this problem. It uses reactive programing, futures, callbacks and a fluent API and proves to be flexible enough to solve this problem.

Java: unary if - npe

Why does this code can cause a NPE? Findbugs give me the hint, that this can occur and it does sometimes :-)
Any ideas?
public Integer whyAnNPE() {
return 1 == 2 ? 1 : 1 == 2 ? 1 : null;
}
EDIT: The code in the question wasn't present when I wrote this answer.
Here's another method to make it slightly clearer:
public static Integer maybeCrash(boolean crash) {
return true ? (crash ? null : 1) : 0;
}
The important point is that we have two conditional expressions here. The inner one is of type Integer due to the last bullet point in the determination of the type as specified in section 15.25.
At that point, we've got a situation like this:
public static Integer maybeCrash(boolean crash) {
Integer tmp = null;
return true ? tmp : 0;
}
Now for the remaining conditional expression, the previous bullet point applies, and binary numeric promotion is performed. This in turn invokes unboxing as the first step - which fails.
In other words, a conditional like this:
condition ? null-type : int
involves potentially boxing the int to an Integer, but a conditional like this:
condition ? Integer : int
involves potentially unboxing the Integer to int.
Original answer
Here's a rather simpler example which is actually valid Java:
public class Test {
public static void main(String[] args) {
int x = args.length == 0 ? 1 : null;
}
}
This is effectively:
int tmp;
if (args.length == 0) {
tmp = 1;
} else {
Integer boxed = null;
tmp = boxed.intValue();
}
Obviously the unboxing step here will go bang. Basically it's because of the implicit conversion of a null expression to Integer, and from Integer to int via unboxing.

How could this Java method be improved?

I am parsing XML files and I have several methods similar to:
public static Integer getInteger(Object integer) {
if (integer == null) {
return 0;
}
try {
return Integer.parseInt(integer.toString(), 10);
} catch (Exception ex) {
return 0;
}
}
So basically, you pass an object in with the assumption of converting it to an Integer (I also have versions for Float, etc).
This seems to work well but being a Java newbie, I was wondering how you would improve it. I am especially interesting in the boxing/unboxing aspect (at least, from a C# developer's perspective).
Thanks
EDIT
Sorry, I wasn't clear to what goes into the method. Yes, it's for an XML file now so it's always a string. But the string could be empty or maybe even null. I guess I wanted to always return a 0 if there was an error of any kind.
You shouldn't generally catch Exception. Catching NumberFormatException would be more appropriate here.
Any reason for converting to Integer instead of int? Why not let the caller perform the boxing conversion if they need it?
You don't say whether integer is an instance of Integer or not. If it is you can just cast it:
Integer i = (Integer) integer;
having checked for null and instanceof first.
If it is not an instance of Integer then what you're doing seems reasonable, although you only need to catch a NumberFormatException.
You should use instanceof operator, then make safe casting (so if Object integer is instanceof Integer, cast it).
Then you don't have to catch Exception (which in this case is unchecked NumberFormatException)
public static Integer getInteger(Object integer) {
if (integer == null) {
return 0;
}
if (integer instanceof Integer) {
return (Integer)integer;
}
return 0;
}
EDIT
If data is coming from XML, then it will of course never be Integer :) Then parsing from String is required still, so see other answers.
As Jon hinted, returning int (the primitive data type) instead of Integer (the wrapper class) would probably be better (assuming you never want to return null).
Also, adding this code could be a shortcut, when the input is often an Integer object or other Number subclass (I'm calling the input input because it's too confusing otherwise):
if (input instanceof Number) {
return ((Number) integer).intValue();
}
Returning Integer makes sense if you want to signal, that a value is empty. You're testing that already but you shouldn't return 0, unless you have a very clear and somewhat special requirement to do so. No value is not equal to 0.
Also, you can add more special cases besides null, like check for empty string:
public static Integer getInteger(Object integer) {
if (integer == null) {
return 0;
}
try {
String s = integer.toString();
if (s.isEmpty())
return 0;
return Integer.parseInt(s, 10);
} catch (Exception ex) {
return 0;
}
}
On the other side, you can cut all special cases, and go with only:
public static Integer getInteger(Object integer) {
try {
return Integer.parseInt(integer.toString(), 10);
} catch (Exception ex) {
return 0;
}
}
In the end, performance gains (or losses) depends on what portion of your input data is null, empty, unparsable integers, or "normal" integer strings.

Categories

Resources