Java Lesson 02 – Numbers

Learning about numbers

In the previous lession you learned about the Object type String used to contain text. In this lession you will learn about the various object types that can hold numbers.

We will start with creating a new project. Calls this project Lesson 2. After that create a Main class again, just like in the previous lesson. If you forgot how to do that look it up in Lesson 1.

The most used types for numbers are Integer and Double. Lets start with Integers. An Integer is most often refered to as an int. Integers are always whole numbers with no decimals.

Try the following example:

As you can see in the example above an int can be converted to a double, but a double cant be converted to an int.

Basic Calculations

Lets start with some basic calculations answers are down below, but try solving them yourself first before looking at the answers.

Some basic math first. Remember it is * / before + –

Answers SelectShow

Next some calculations with round brackets. Calculations inside round brackets go first.

Answers SelectShow

When calculating with double and ints make sure to watch out what you are calculating with, because ints are whole numbers and always rounded downwards. Again, guess what the answer will be and figure out why that is.

Answers SelectShow

Now you might be wonder what the use of integers are and why not just use doubles for everything. For 1 integers take up less space in your memory and for al lot of calculations double just isnt necessary as you will see in coming Lessons. For now its just important that you know the difference between the two.

Assignment

You have 3 numbers 8, 3, 2 you can choose yourself whether you use them as a double or integer. You can use each number only once and you need to use them all.

Try get the following results:1) 9.0
2) 3
3) 2
4) 12.0
5) 7
6) 1.0
7) 4
8) 5

Answers SelectShow

Download

The examples and the solutions to the Assignment you can download here