Thursday 6 November 2014

Java Basics Lesson 2: Operators



OPERATORS

An operator is just a way of testing a conditional statement.  To break this down even further an example would be like:

5 < 6.... (the integer 5 is less than the integer 6). The less than sign is the operator!

Okay, pretty simple. We have more operators in Java which make coding a conditional statements very simple.

Other conditionals in Java can test other things. Here are a few:

< less than
> greater than
= equal to
<= less than and equal to
>= greater than and equal to
!= not equal to


++ increment integer by one
-- decrement integer by one
&& AND
|| OR

We generally use operators in programming to test a condition. If a person is a girl or a boy, if your pet at home is a cat or a dog... all of these things can be tested in programming through conditional statements.

How we do this is: (example show how to test what stage of a boys life he is in (String stageofperson))

if (boy_age > 12 && < 18)  //if the boy's age is greater than 12 AND less than 18 he is a teenager
{
   stageofperson = "Teenager";
}
elseif (boy_age >= 18 && < 70) //if the boy's age is greater than or equal to 18 but less than 70 = adult.
{
  stageofperson = "Adult"
}
elseif (boy_age < 12)
{
  stateofperson = "Child"
}
else
{
  stateofperson = "Pensioner"
}


WOW okay thats looks long but actually its not.  We are checking through an if statement to see what stage of the person of life is in. Child if he is less than 12. 13 and above to 18 makes him a teeenager and 18 and over but less than 70 makes him an adult. If none of those match he must be older than 70 which makes him a pensioner.  Seems like a long convoluted way but it actually makes for simple and easy programming and simple to explain here. In real life coding practice we would use a SWITCH statement for the above code. This I will blog next but for the purpose of understanding conditional operators this serves it purpose.

Another example would be this in a WHILE loop. We will to WHILE loops soon...

while (name != "Jenny")
{
   //increment the student number
  student++;

}

Well  hope this has helped. Operators are used in every single program you will make. You will know them soon enough. Do not be daunted by anything here.... it will all come together quickly and soon.




No comments:

Post a Comment