Lesson 3 – Basic Operators

Ok in the last lesson we learnt how to declare and assign values to various primitive types. Let’s now look at some more operations this time using the int primitive type.

Downloads

To get started you can use the basic starter project and follow the steps to compile the code examples for the lesson.

Setup

  1. Create a new package called: com.codenerve.beginner.lesson3
  2. Create a new class file called: BasicOperators.java with a main method

If you need help with this, please go back and look at the previous lessons

Adding

Within the main method of your class add the following lines of code:

You’ll notice I’ve done a few things different here.

Firstly, I’ve created two variables of type int on the one line, called a and b and assigned values to them. This one line syntax is simply a handy shorthand for creating and assigning my variables. You could also create these one two lines as seen before in the previous lesson.

Secondly, you should also notice that I have decided to set up these variables inside the main method. Doing this means they are local variables, not fields. Which means they are only available inside the main method and not to other methods. For the purposes of this lesson, this is fine.

Next, add the following code:

This is the simple add (+) operator which guess what adds two int’s together. Lastly, we use the System class which Java provides for us to print the output.

You can run the code at each stage in this lesson to view the results of each operator.

Subtracting

Multiplication

Division

Modulus

Increment

The ++ operation will add 1 to the current value of int a. This is useful for keeping a count.

Decrement

The — operation will subtract 1 to the current value of int a.  This is helpful for maintaining a countdown.

Some more slightly complex calculations

Watch out!

Dividing a primitive by zero causes the program to exit with a nasty error:

Have a look at the exception:

Exception in thread “main” java.lang.ArithmeticException: / by zero

at com.codenerve.beginner.lesson3.BasicOperators.main(BasicOperators.java:63)

Ok, now that we’ve learnt how to use ints the next lesson will focus on Strings.

Next: Strings

Menu