Java FAQ: What are the rules about Java arithmetic (multiplication, division) involving mixed data types?
While working on a math problem in Java just a little while ago, I realized that I wasn’t comfortable with the Java mixed-type division rules. That is, I wondered if the result of this equation:
3 / 2
the same as the result of this equation:
3 / 2.0
or this equation:
3.0 / 2.0
Java math FAQ: How do I round a float or double to an integer in Java?
Math.round() to round a
double) to the nearest integer (
int) in Java.
You can see how this works in the examples that follow, where the result is shown in the comment after each line:
Scala FAQ: I need to compare two floating-point numbers in Scala, but as in some other programming languages, two floating-point numbers that should be equivalent may not be; how do I comparison floating-point numbers?
As in Java and many other languages, you solve this problem by creating a method that lets you specify the precision for your comparison. The following Scala “approximately equals” method demonstrates the approach:
Scala FAQ: How do I override the default numeric type that Scala assigns when I declare an
Double val or var field?
If you assign
1 to a variable, Scala assigns it the type
Scala FAQ: How do I convert between numeric types in Scala, such as from Int to Long, Int to Double, etc.?
Instead of using the “cast” approach in Java, use the
to* methods that are available on all of Scala’s numeric types. These methods can be demonstrated in the REPL (note that you need to hit the [Tab] key at the end of the first example):
Scala FAQ: How do I parse a number (
Float, etc.) from a
String in Scala?
to* methods that are available on a
String (courtesy of the Scala
As I get back into working with a MySQL database in a Java (Scala, actually) development project and also in adding functionality to Cato, I found these MySQL to Java data type mappings, via this link:
Scala FAQ: What are the Scala data types? How many bits do they use to store their data, and what is the range of those data types?
Courtesy of the excellent book, Programming in Scala, here is a list and description of the Scala data types, including bit sizes and data ranges:
Question: How do I convert a
String to an
int or a
Short answer: You want to use the
Here's an example Java program that shows how to convert a String to either an
int or a