Java: (int)(float)Float.valueOf(s) or Float.valueOf(s).toInt() - java

I just bumped into this little problem and I wanted the input of other people on this
I was wandering what was the best solution to convert a String to an int
(int)(float)Float.valueOf(s)
or
Float.valueOf(s).toInt()
s is a String inputed from a textfield so I can not guarantee that it is necessarily an int
my instincts is that the double cast is ugly and should be avoided
Your input?

Your requirements are unclear:
If you are expecting an integer and don't want to allow the user to enter a number with a decimal point in it, simply use Integer.valueOf(String) or Integer.parseInt(String) and catch the NumberFormatException.
If you want to allow numbers with decimal points, then use Float.valueOf(String) or Float.parseFloat(String).
If you simply want to truncate the float to an int then either Float.intValue() or two casts are equivalent. (The javadoc for intValue explicitly states this.)
If you want to round to the nearest int, use Math.round() instead of a cast.
You should catch NumberFormatException whatever approach you take, since the user could enter rubbish that is not a valid base-10 number (with or without a decimal point) ... or that exceeds the bounds of the number type.
(I suppose that you could use a regex or something to check the String before trying to convert it, but it is simpler to just let the exception happen and deal with it. The exception efficiency issue is unlikely to be a practical concern in this use-case.)
On your original question as to whether intValue() is better than two casts: it is a matter of style. The two approaches do the same thing ... according to the javadoc. It is possible that one will be slightly more efficient than the other, but:
that shouldn't be a concern for your use-case, and
the only way to know for sure would be to profile the two alternatives on your execution platform ... and frankly it is not worth the effort.

You should use Integer.valueOf(..), and catch the NumberFormatException (if the string cannot be parsed as an integer).

Integer.parseInt(string) would be best
int x = Integer.parseInt(s);
Would be best to check if the string is an int before calling this.

As others pointed out, its just matter of style not performance... but if you are worried about performance you should validate the text field data in browser itself by javascript using a regex
^[0-9]*$
which would allow only integers to be submitted to your back-end code and hence improving performance by avoiding one network trip. Still you should validate the data in back-end, for that you can use
Integer.parseInt(String s) throws NumberFormatException

Related

Disable Java making big number smaller? (10,000,000,000 to 1E10)

I have a big number in a database; in this case, 10,000,000,000. Whenever I use that information for something, like sending a message with it, instead of 10,000,000,000, it says 1E10, and I really do not want that.
Can I avoid that in any way?
If I go to the database, the value is 10,000,000,000.
It's the same number, just represented in scientific notation.
Since you don't describe how you are storing the value, you can use DecimalFormat#getNumberInstance to help format it to one that doesn't contain the scientific notation.
double foo = 10000000000L;
System.out.println(foo);
System.out.println(DecimalFormat.getIntegerInstance().format(foo));
This outputs:
1.0E10
10,000,000,000

Which is better - Integer.parseInt() and catch exception or verify String with pattern before conversion? [duplicate]

This question already has answers here:
Which is better/more efficient: check for bad values or catch Exceptions in Java
(11 answers)
Closed 9 years ago.
I have seen two styles for checking whether a variable is a valid integer in Java. One by doing an Integer.parseInt and catching any resulting exception. Another one is by using Pattern.
Which of the following is better approach?
String countStr;
int count;
try {
count = Integer.parseInt(countStr);
} catch (Exception e) {
//return as the variable is not a proper integer.
return;
}
or
String integerRegex = "([0-9]{0,9})";
if (countStr.isEmpty() || !Pattern.matches(integerRegex, countStr)) {
//return as the variable is not a proper integer.
return;
}
My question here is, is doing an Integer.parseInt() and catching an exception for validation a standard way to validate an int? I admit that my regex is not perfect. But is there any built-in methods available in Java for validation of int? Actually isn't it better to do some validation instead of simply catching the exception?
Using the approach above is better as it considers all types of possible errors and handles all cases. For instance what you have written will not parse negative numbers correctly.
It only makes sense to write your own verifier if you want to validate a given subset of all integers.
A general advice: don't re-invent the wheel unless you have strong reasons to do so.
There's a really good reason to not go with the second approach if you actually want to check if the given string can be represented as a 32bit integer and not just that it represents an integer in the mathematical sense.
I'm sure we all agree that 2147483648 (2**31 for those paying attention) is a perfectly fine integer, but it's only one of infinitely many numbers for which the two options will give different results. So if you want to check if you can represent a string as a 32bit integer use the parseInt method, if you just want to see if it's an integer go with the regex.
PS: That said don't catch Exception, but the correct NumberFormat exception instead..
These two function serve different purposes. If you just want to make sure that the string cotains a particular pattern, then use the second approach. If you need to convert it, then you should can parseInt() In this case it wouldn't make sense to check it and convert it as well.
However, if you have specific requirements for the number, then you may have to check it first regardless, because parseInt() may not always throw an exception if it can parse something which still doesn't fit your requirement.
If you just validat an Integer, I think the second way is better.
These two methods both will work fine, but obviously different focus. The former focuses on the transformation itself, while the latter is clearly more attention checked. And you want to check a number is, so I think the second method is better. Also, I think, some of the second method more readable, allowing code maintenance is a clear to see, where the logic is in checking the validity of a number instead of a string into a number.

difference between String.valueOf(int) , `+` string operator and Integer.toString(int)

Not confident about whether this will be downvoted or closed... I need expert opinion on this.
The context is in our application, we have written code like :
//countryId is an integer, searchCity() expects two String parameters
loadCity(countryName , countryId + "");
Will it make any difference if I change (I am being forced to do so) the call like :
loadCity(countryName, String.valueOf(countryId));
Or,
loadCity(countryName, Integer.toString(countryId));
Will this make any difference in sense of performance?
For the example you have given, the answer will really depend on the type of 'integer' you are using.
loadCity(countryName , countryId + "");
For an Integer object this is equivelent to :
loadCity(countryName, countryId.toString() + "");
Whereas for an int primitive, this code is equivelent to :
loadCity(countryName, String.valueOf(countryId) + "");
In either case, as ArjunShankar pointed out there is a good chance that the compiler has optimised your code anyway. So if your question is 'do I go back and refactor all my code?', then I would say 'don't sweat the small stuff'. But in the future use a more conventional approach to avoid the down votes.
I'd say the main difference is readability. There's no use in micro-benching here. IMHO String#valueOf reads the best.
From the docs of String.valueOf
"The representation is exactly the one returned by the Integer.toString method of one argument."
I would use String.valueOf because you can use it on more then just Integers, i.e. you don't have to know whether you have an int, double, bool, etc....
They are same.... because
the method String.valueOf(int i) implicitly calls Integer.toString(i, 10);
A search on both methods informed me all of these are equivalent:
String.valueOf(countryId)
Integer.toString(countryId)
countryId.toString() //Only if countryId is an Integer
Because they all call:
Integer.toString(countryId, 10)
The only difference is if you wish to use a different radix, ie:
Integer.toString(countryId, radix)
Personally I think countryId.toString() reads better when using an Integer. Otherwise Integer.toString(countryId) is the way to go. But that is just my personal opinion. Performance-wise you should use Integer.toString(countryId, 10).
I think that adding an empty string to an int to convert it to a String is a bad practice.

small java problem

Sorry if my question sounds dumb. But some time small things create big problem for you and take your whole time to solve it. But thanks to stackoverflow where i can get GURU advices. :)
So here is my problem. i search for a word in a string and put 0 where that word occur.
For example : search word is DOG and i have string "never ever let dog bite you" so the string
would be 000100 . Now when I try to convert this string into INT it produce result 100 :( which is bad. I also can not use int array i can only use string as i am concatinating it, also using somewhere else too in program.
Now i am sure you are wondering why i want to convert it into INT. So here my answer. I am using 3 words from each string to make this kind of binary string. So lets say i used three search queries like ( dog, dog, ever ) so all three strings would be
000100
000100
010000
Then I want to SUM them it should produce result like this "010200" while it produce result "10200" which is wrong. :(
Thanks in advance
Of course the int representation won't retain leading zeros. But you can easily convert back to a String after summing and pad the zeros on the left yourself - just store the maximum length of any string (assuming they can have different lengths). Or if you wanted to get even fancier you could use NumberFormat, but you might find this to be overkill for your needs.
Also, be careful - you will get some unexpected results with this code if any word appears in 10 or more strings.
Looks like you might want to investigate java.util.BitSet.
You could prefix your value with a '1', that would preserve your leading 0's. You can then take that prefix into account you do your sum in the end.
That all is assuming you work through your 10 overflow issue that was mentioned in another comment.
Could you store it as a character array instead? Your using an int, which is fine, but your really not wanting an int - you want each position in the int to represent words in a string, and you turn them on or off (1 or 0). Seems like storing them in a character array would make more sense.

How to present the nullable primitive type int in Java?

I am designing an entity class which has a field named "documentYear", which might have unsigned integer values such as 1999, 2006, etc. Meanwhile, this field might also be "unknown", that is, not sure which year the document is created.
Therefore, a nullable int type as in C# will be well suited. However, Java does not have a nullable feature as C# has.
I have two options but I don't like them both:
Use java.lang.Integer instead of the primitive type int;
Use -1 to present the "unknown" value
Does anyone have better options or ideas?
Update: My entity class will have tens of thousands of instances; therefore the overhead of java.lang.Integer might be too heavy for overall performance of the system.
Using the Integer class here is probably what you want to do. The overhead associated with the object is most likely (though not necessarily) trivial to your applications overall responsiveness and performance.
You're going to have to either ditch the primitive type or use some arbitrary int value as your "invalid year".
A negative value is actually a good choice since there is little chance of having a valid year that would cause an integer overflow and there is no valid negative year.
Tens of thousands of instances of Integer is not a lot. Consider expending a few hundred kilobytes rather than optimise prematurely. It's a small price to pay for correctness.
Beware of using sentinel values like null or 0. This basically amounts to lying, since 0 is not a year, and null is not an integer. A common source of bugs, especially if you at some point are not the only maintainer of the software.
Consider using a type-safe null like Option, sometimes known as Maybe. Popular in languages like Scala and Haskell, this is like a container that has one or zero elements. Your field would have the type Option<Integer>, which advertises the optional nature of your year field to the type system and forces other code to deal with possibly missing years.
Here's a library that includes the Option type.
Here's how you would call your code if you were using it:
partyLikeIts.setDocumentYear(Option.some(1999));
Option<Integer> y = doc.getDocumentYear();
if (y.isSome())
// This doc has a year
else
// This doc has no year
for (Integer year: y) {
// This code only executed if the document has a year.
}
Another option is to have an associated boolean flag that indicates whether or not your year value is valid. This flag being false would mean the year is "unknown." This means you have to check one primitive (boolean) to know if you have a value, and if you do, check another primitive (integer).
Sentinel values often result in fragile code, so it's worth making the effort to avoid the sentinel value unless you are very sure that it will never be a use case.
You can use a regular int, but use a value such as Integer.MAX_VALUE or Integer.MIN_VALUE which are defined constants as your invalid date. It is also more obvious that -1 or a low negative value that it is invalid, it will certainly not look like a 4 digit date that we are used to seeing.
If you have an integer and are concerned that an arbitrary value for null might be confused with a real value, you could use long instead. It is more efficient than using an Integer and Long.MIN_VALUE is no where near any valid int value.
For completeness, another option (definitely not the most efficient), is to use a wrapper class Year.
class Year {
public int year;
public Year(int year) { this.year = year; }
}
Year documentYear = null;
documentYear = new Year(2013);
Or, if it is more semantic, or you want multiple types of nullable ints (Other than Years), you can imitate C# Nullable primitives like so:
class Int {
public int value;
public Int(int value) { this.value = value; }
#Override
public String toString() { return value; }
}
Using the int primitive vs the Integer type is a perfect example of premature optimization.
If you do the math:
int = N(4)
Integer = N(16)
So for 10,000 ints it'll cost 40,000 bytes or 40k. For 10,000 ints it'll cost 160,000 bytes or 160K. If you consider the amount of memory required to process images/photos/video data that's practically negligible.
My suggestion is, quit wasting time prematurely optimizing based on variable types and look for a good data structure that'll make it easy to process all that data. Regardless of that you do, unless you define 10K primitive variables individually, it's going to end up on the heap anyway.
What's wrong with java.lang.Integer? It's a reasonable solution, unless you're storing very large amounts of this value maybe.
If you wanted to use primitives, a -1 value would be a good solution as well. The only other option you have is using a separate boolean flag, like someone already suggested. Choose your poison :)
PS: damn you, I was trying to get away with a little white lie on the objects vs structs. My point was that it uses more memory, similar to the boolean flag method, although syntactically the nullable type is is nicer of course. Also, I wasn't sure someone with a Java background would know what I meant with a struct.
java.lang.Integer is reasonable for this case. And it already implemented Serializable, so you can save just only the year field down to the HDD and load it back.
Another option might be to use a special value internally (-1 or Integer.MIN_VALUE or similar), but expose the integer as two methods:
hasValue() {
return (internalValue != -1);
}
getValue() {
if (internalValue == -1) {
throw new IllegalStateException(
"Check hasValue() before calling getValue().");
}
return internalValue;
}
If you're going to save memory, I would suggest packing several years in a single int. Thus 0 is nil. Then you can make assumptions in order to optimize. If you are working only with the current dates, like years 1970—2014, you can subtract 1969 from all of them and get into 1—55 range. Such values can be coded with only 6 bits. So you can divide your int which is always 32 bit, into 4 zones, with a year in there. This way you can pack 4 years in the range 1970—2226 into a single int. The more narrow your range is, like only 2000—2014 (4 bits), the more years you can pack in a single int.
You could use the #Nullable annotation if using java 7

Categories

Resources