1. int a = 4;
  2. double b = 4.5;
  3. int answer = a + b;

What value will answer have when this program runs? As it is an integer it can not hold 8.5, which is the answer. Maybe it will round up to 9? Or round down to 8? Or it may give us an error...

MyFirstProgram.java:20: possible loss of precision
found : double
required: int
int answer = a + b;

So why can Java not use a bit of brains and give us 9? The answer is that instances like these can lead to errors. What if we really needed to remember that .5? Java requires you to manually give it permission to loose precision, or the decimal places.

int answer = a + (int) b;

Here we are telling java to force the double to become a int. There by ignoring the decimal places. This is known as casting. You must always manually put a cast in when a variable needs to be demoted. What do we mean by demoted? Loosing precision! You get used to it, honest!

  1. int a = 4;
  2. int b = 4.5;
  3. double answer = a + b;

This code will compile and work as expected. But hang on, ints are not doubles so how can it work?!? It works because you can promote data types but not demote. So a int can be stored in a double but not visa versa. A int can be stored in a long but not visa versa.

Best rule of thumb is to stick with the same data type. If you do need to swap between them just make sure you know exactly why you are doing it! If not then don't! It does genuinly cause some odd problems.

next strings >>

 
Basics
Menu
Search