Friday, September 7, 2012

9/7/12 Integers

In java, there are multiple ways you can store data on the computer. These are called data types.This week, we have learned about 4 different data types. These data types are integers, doubles, chars, and strings. All of these data types are used to store different kinds of data, like you can store numbers in doubles, but you can not store words in them. Today, I will explain how to create and edit integers in java.

An integer can hold an integer, or a number that has no fractional part. In java, to create an integer you type
"int A;" where A can be whatever you want to call the integer. This will make a new integer, and to give integer A a value, you would type "A = ?;" where ? represents what you want A to equal. As an example, lets say I wanted to create a new integer, call it N, and make N be equal to 5. I would type:
int N;
N = 5;
It is that easy to define an integer. If you want to, you could also type "int N = 5;", and it would create an integer N where N is equal to 5. Now that you know all about how to create an integer, you may be wondering "why is it useful to create an integer?". It is useful to create an integer because you can change what number the integer holds within your code.

Now that you know how to create an integer, you can add, subtract, multiply, or divide to change the value of that integer. I will show you how to change the value of the integer N that I said was 5 earlier in this post.
N = N + 5; (will increase the value of N by 5)
N = N * 5; (will multiply N by 5)
N = N - 5; (will  decrease  the value of N by 5)
N = N / 5; (will divide N by 5)
There is one error that could arise from editing the value of an integer. If you have N, and you divide it by 2, the answer is two and a half. Two and a half is not an integer, so your code will not work if you try to make an integer become a number that is not one. There is a way to fix this problem. If instead of typing "N = N/2;", you type "N = (int) N/2;", N will be truncated down to 2, which is an integer. This works because by typing "(int)", you are telling the computer to give you the answer as an integer. This is all I have to tell you about integers and java, so hopefully you now know how to create and edit integers in java.

*Note: you may have noticed that at the end of each line of code, I put a semicolon. In java, you do this to signify the end of a command.

No comments:

Post a Comment