BBC (Brian's Boot Camp)

Not to be confused with the British Broadcasting Corporation, the BBC will focus on Brian's fast paced journey of the mastery of the Java programming language.

Tuesday, February 15, 2005

Of ints and bits

To clarify the "which data type to use when" issue, here are some rules of thumb (or rule of thumbs). See the comment to your previous post for a more full bodied explanation of why.

1) Use doubles for floating point numbers
2) Use ints for whole numbers.
3) Rarely use float, and almost never use short, byte, char, etc.
4) When using division, divide by doubles, even if you're dividing two ints. If integer division is used, the remainder will be truncated. Unless this is desired, use doubles (i.e. int1 / (int2 * (1.0)), or int1 / (double) int2).
5) You can always cast your answer to whatever result data type you need (the above example uses a cast).

Casting in a nutshell -- consider the following:

int a = 10.0 / 2.0;

You know this answer will be 5 even, but you'll get a "loss of precision" compiler error because double division requires a double result. Here's how to get around that error:

int a = (int) (10.0 / 2.0);

This casts the result to an int (truncating any remainder were there one). A cast is a way of taking the safety off of the type checking. You're telling the compiler that you explicitly acknowledge the fact that you are narrowing the data type.

The above is an explicit cast. Implicit casts happen without warning or compiler errors:

double d = 10 / 2;

The above result is normally an integer, but you're implicitly casting it to a double. Since this is a widening of data type, and no precision will be lost, an explicit cast is not needed.

4 Comments:

Blogger Brian T. Grant said...

Hahaha. "double d". That's a good one.

5:37 PM  
Blogger Sten said...

As in the bra size, or the VI command to delete a single line?

8:53 PM  
Blogger Brian T. Grant said...

Oh, definitely the vi command.

4:17 AM  
Blogger Brian T. Grant said...

Speaking of vi, I bothered to read vim's manpage and get the syntax highlighting working. Anybody know how to have it turned on by default?

12:52 PM  

Post a Comment

<< Home