Showing posts with label Operators. Show all posts
Showing posts with label Operators. Show all posts

Tuesday, March 12, 2013

Java Math basics

Maths Operators

The maths operators in the figure below, probably look familiar.

The basic set of Java arithmetic operators is presented in the figure.

  • Multiplication

  • Division

  • Modulo

  • Addition

  • Subtraction

The operators have been split into two groups to indicate their ‘precedence’ - the order in which they are obeyed.

 

Order of precedence

Multiplication, division and modulo operations are carried out before addition and subtraction.

If a calculation contains operators of the same precedence, the calculation is performed from left to right.

int j;
    int n = 2;
    j = n + 5; // Set to to 7
    j = n * 2; // Set to 4
    j = 3 + 3 * 2; // Set to 9
    j = n * ( 5 + 2 ) * 2 // Set to 28
    j = 25 - 3 // Set to 22

We can use parenthesis (brackets) to group calculations and force them to be carried out in a particular order.

Wherever brackets are used, the items within them are calculated first.

For instance, the sum 10 + 20 multiplied by 100 produces the result 3000. It could be tempting to write that equation as follows:

     10 + 20 * 100

However, due to the order of precedence in which arithmetic operations are performed, the sum is performed as if it had been written 10 + ( 20 * 100 ) producing the result 2010.

Note: Spaces are only required on either side of an operator for easy readability.

Integer Division

The Integer data type is a whole-number numeric data type. Where integer division is being performed, only the integer part of the result is returned.

For instance, if you type 13 / 5 into a calculator, you will see the result is 2.6.
However, when you perform integer division in a programming language, such as Java, the result of the same calculation is 2 - only the integer (whole number) part is returned as the result.

Double Division

The double data type is a floating point numeric data type..

Where double division is performed, the result is returned as a floating point number. Once again, using the example of 15 / 5, the result returned from double division is 2.6.

The % operator (modulo)

This operator returns the remainder of division of one number by another number.

int examples

For instance, 10 / 2 has a remainder of 0. This is because 10 is divided by 2 exactly.

Another example, 15 / 2 has a remainder of 1. This is because, after division has taken place (15 can be divided 7 times), 1 is left over.

More examples:

    int x;
    x = 12 % 4; // Set to 0
    x = 12 % 3; // Set to 0
    x = 12 % 5; // Set to 2
    x = 50 % 7; // Set to 1
    x = 100 % 33; // Set to 1
    x = 100 % 5; // Set to 0
    x = 30 % 9; // Set to 3

Remember, the remainder of an integer division only returns the integer part of the result.
 
For instance, if you were to type 4 / 3 into a calculator, you would see the result is 1.3333333 etc. However, where this calculation is being performed as integer division in a programming language, such as java, only the integer part is returned - producing the result 1.

Using % to convert cents into dollars

Let’s say we want to convert an int amount of cents (577) into dollars and cents.
The algorithm is as follows:

inputs - numOfCents
outputs - numOfDollars, centsRemaining
processing tasks -
    • get numOfCents
    • numOfDollars = numOfCents / 100
    • centsRemaining = numOfCents % 100


Remember, integer division returns the integer part of the result, so the statement

    dollars = numOfCents / 100

will return 5, in this example.

Monday, February 25, 2013

Variable Syntax

Every variable has a (data) type and an identifier.

Variable declaration syntax (single line):

Type identifier = value;

      or (assignment statement in 2nd line):

Type identifier;
identifier = value;

Naming variables
There are rules and conventions around how Java variables are named.

A Java variable name:
  • should begin with a lowercase letter
  • can contain numbers
  • can contain an underscore
  • must be less than 255 characters long
  • must not contain spaces
  • must not begin with a number
  • if the name consists of more than word, capitalize the first letter of each word

Case sensitive
All names in Java are case sensitive. This means that a variable named numberOfClicks is different to a variable named numberofclicks.


Variable Declaration

When we create a variable in our program, we are said to be ‘Declaring a variable’. Variables are declared in methods. Methods are named blocks of code which perform a particular task. Variables may also be declared in the body of a class - that is, within the class declaration, but not within the body of a method.




When we declare a variable, we are telling the program to remember a value. Of course, there are many different types of data so we need to select the most appropriate variable type to store that value in.


The statement below is a variable declaration for some String data called myPassword. The value it is storing is “secret’.


String myPassword = “secret”;





Assigning values - The assignment operator

When we assign a value to a variable, we use the assignment operator - the equals (=) character. 

The assignment operator takes the value on the right and assigns it to the operand on the left side to form an assignment expression.


In the example below, the value “GateKeeper99” has been assigned to the String variable called myUserName.


String myUsername = “GateKeeper99”;


The assignment operator is also used to change the value being stored by the variable, as follows:


int numberOfUsers = 100;
numberOfUsers = 101;


We are also able to declare a variable in one statement and assign a value to it, in another statement.

As follows:


int xCoordinate;
xCoordinate = 500;


This technique is often used where we need to increase the scope of a variable.


Variable scope
A variable may only be referenced from within the region where it is declared. This means that if a variable is declared within a method, it is only accessible from within that method. Also, you cannot reference a variable before it is declared. If a variable is declared in the class body, this variable can be accessed from all methods in the class.




Variable lifetime

Variable lifetime refers to the length of time that a variable stores a value. Depending on the scope, a variable may have a lifetime that lasts for the time it takes a single block of code to execute, or for the entirety of program execution (more on that later).

Thursday, January 17, 2013

! operator (NOT)



The exclamation character is the NOT operator !
The NOT operator is used to evaluate an expression to true or false.


Here's the NOT operator using a simple if statement format:

if (!(condition1)) {
   doSomething();
}

Here's the NOT operator using a if-then-else statement format:



if (!(condition1)) {
   doSomething();
}

else {
   doSomethingElse();
}


The method doSomething() will only execute if the condition in the if statement evaluates to false.

Let's take a look at another, more concrete example:


if (!(respawnRemaining >= 1)) {
   gameOver();
}


The method gameOver() will only execute if respawnRemaining is NOT greater than or equal to 1.

In the following example, we use an if-then-else statement:



if (!(respawnRemaining >= 1)) {
   gameOver();
}

else {
   respawn();
}

If respawnRemaining is NOT greater than or equal to 1, the gameOver method will execute. If it is greater than or equals to 1, the respawn method will execute.



Also see
&& Operator (AND)
|| Operator (OR)


Tuesday, January 8, 2013

&& operator (AND)


A double ampersand is the logical AND operator &&

The AND operator is used to evaluate multiple expressions during decision making with if statements.


Here's the AND operator using a simple if statement format:

if (condition1 && condition2) {
   doSomething();
}

Here's the AND operator using a if-then-else statement format:


if (condition1 && condition2) {
   doSomething();
}
else {
   doSomethingElse();
}


The method doSomething() will only execute if both of the conditions in the if statement evaluate to true.

Let's take a look at another, more concrete example:


if (maxDamage > 100 && ammoCount == 0) {
   gameOver();
}


The method gameOver() will only execute if maxDamage is greater than 100 AND ammoCount is equal to 0. If either condition does not evaluate to true, the gameOver() method will not execute.

In the following example, we use an if-then-else statement:


if (maxDamage > 100 && ammoCount == 0) {
   gameOver();
}
else {
   continue();
}


If both conditions are true, the gameOver() method will execute. If both of the conditions are false, the continue() method will execute.

Also see
|| operator (OR)
! Operator (NOT)

|| operator (OR)



A double pipe is the logical OR operator ||

The OR operator is used to evaluate multiple expressions during decision making with if statements.


Here's the OR operator using a simple if statement format:

if (condition1 || condition2) {
   doSomething();
}

Here's the OR operator using a if-then-else statement format:


if (condition1 || condition2) {
   doSomething();
}
else {
   doSomethingElse();
}


The method doSomething() will only execute if one or both of the conditions in the if statement evaluate to true.

Let's take a look at another, more concrete example:


if (maxDamage > 100 || ammoCount == 0) {
   gameOver();
}


The method gameOver() will only execute if either maxDamage is greater than 100 (and or) OR ammoCount is equal to 0. If either condition does not evaluate to true, the gameOver() method will not execute.

In the following example, we use an if-then-else statement:


if (maxDamage > 100 || ammoCount == 0) {
   gameOver();
}
else {
   continue();
}

If either or both of the conditions are true, the gameOver() method will execute. If both of the conditions are false, the continue() method will execute.

Also see
&& Operator (AND)
! Operator (NOT)


Incrementing a number ++


Increment - increase a value.

The increment operator is a double plus ++

The increment operator increases the value to it's left by 1.

Example use with int:

int one = 10;
one ++;

In the first line, an int variable called one is declared and assigned a value of 10.

In the second line, the increment operator is applied to the variable called one to increment it's value.

The result is that the variable called one, now has a value of 11.



Example use with double:

double one = 12.55;
one ++;

In the first line, a double variable called one is declared and assigned a value of 12.55.

In the second line, the increment operator is applied to the variable called one to increment it's value.

The result is that the variable called one, now has a value of 13.55.

Note that where the increment operator is used with the double data type, the increment value is 1 significant number (the number on the left of the floating point is incremented).

See also Decrementing a number

Decrementing a number --


Decrement - decrease a value.

The decrement operator is a double minus --

The decrement operator decreases the value to it's left by 1.

Example use with int:

int one = 10;
one --;

In the first line, an int variable called one is declared and assigned a value of 10.

In the second line, the decrement operator is applied to the variable called one to decrement it's value.

The result is that the variable called one, now has a value of 9.



Example use with double:

double one = 12.55;
one --;

In the first line, a double variable called one is declared and assigned a value of 12.55.

In the second line, the decrement operator is applied to the variable called one to decrement it's value.

The result is that the variable called one, now has a value of 11.55.

Note that where the decrement operator is used with the double data type, the decrement value is 1 significant number (the number on the left of the floating point is decremented).

See also Incrementing a number


Friday, December 21, 2012

Consider if 2 objects are equal....

Demo Code Project: OverridingEquals.zip

Let's say you have the need to ensure that no 2 objects have the same contents - you want to check if one object is equal to another?

What do you consider equal?

Read on...

equals(Object)
The default implementation of the equals method, provided in all java objects (java.lang.Object) is to compare the memory location of one object, with another.


Consider the example above.

Two objects of type Asteroid1 have been instantiated using identical parameters - both a1 and a2 objects have the same contents. They do not, however, have the same memory location.

When the new operator is used, it causes the system to allocate memory space for the data and as such, a1 and a2 objects have unique memory locations.

When the equals method is used to compare the equality of these 2 objects, the equals method will return false - because each object has a different memory location.

If, for the purposes of your program, you consider that object equality is based on memory location only, the default implementation of the equals method is sufficient.

If however, you consider that object equality is based on the contents of objects themselves (more likely), read on...

overriding equals(Object)

All java objects (java.lang.Object) contain a default implementation of an equals method which compares the memory location of objects to determine equality. When writing your own libraries, you may find that this version of the method is not fit for your purpose. In this case, you can override the method and implement your own version of what you consider to be equality. It is usually the case that object equality relies on comparing the contents of the objects - not the memory locations.

When a class overrides a method, it is providing it's own version of a method that has already been provided by it's parent class (such as java.lang.Object).

You can override the equals method simply by providing your own, in your class. A couple of things to remember though:

The method signature must be the same as the one provided by java.lang.Object:

  • Public
  • Boolean return type
  • method name must be equals
  • takes a single parameter of Object type

...which looks like...



OK, now for the implementation. Our goal is to compare the contents of the object parameter with the contents of the current object.

Here is the definition of the class called Asteroid2:



Note that the equals method has been included in the method list.

The contents of this class are the values for the name, size and rotationRate fields. In our implementation of equals, we will write code which considers equality based upon the values of these fields.

Basically, if the current object has the same name as the parameter object and the current object has the same size as the parameter object and the current object has the same rotationRate as the parameter object, we will consider the current object and the parameter object to be equal.

Here's the code:






The first line ensures that the parameter object (aThat) being passed to the method is of the correct type - in this case Asteroid2. The instanceof operator (compares an object to a specified type) is used to determine the type. The method returns false immediately if this is not found to be true - after all, if the parameter object isn't of type Asteroid2 then it will never be equal to any instance of Asteroid2.

The second line then goes ahead and casts (converts) the parameter object to the type it is being compared to - in this case, Asteroid2. Once the cast has taken place, we can then treat the parameter object (aThat) as an instance of Asteroid2 (That) and call each of it's methods to begin determining equality.

The return statement uses the logical operator && to join together a number of expressions, relating to the fields on the objects, which will ultimately evaluate to true or false.

Once again...basically, if the current object has the same name as the parameter object and the current object has the same size as the parameter object and the current object has the same rotationRate as the parameter object, the method will return true.

Calling the equals method
Let's assume that we wish to add a new Asteroid2 object to an existing ArrayList of Asteroid2 objects but we want to make sure that an object with the same contents does not already exist in the ArrayList.

The example below uses a loop to compare the new Asteroid2 object with each object in the ArrayList:


Because the Asteroid2 class has overriden equals, we can be assured that only objects containing unique contents will be added to the ArrayList.

Incidentally, the ArrayList has a contains method which evaluates object equality in the same way - dispensing with the need for a loop. It simply calls the equals method on each object in the ArrayList - equality is based on whether the method has been overriden by the class in question (contents) or not (memory location).

One last thing...

We can also quickly return from the equals method by checking if the parameter object has the same memory location (and hence is the *same* object) as the current object.


When the equal to operator (==) is used on objects (reference types), the references (memory locations) are compared.

see also:

"Object (Java Platform SE 7 )" ( http://bit.ly/YrEmpk )

"Overriding and Hiding Methods (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)" ( http://bit.ly/Zn8eop )


member access operator (.)

In Java, the dot (.) is an operator called the member access operator.

This operator is used to separate the class/object name from a method name.

For instance, an object called playerOne that has a method called fight:

playerOne.fight()


Monday, September 24, 2012

Modulo %

Download the code

This operator returns the remainder of division of one number by another number.


Integer examples
For instance, 10 / 2 has a remainder of 0. This is because 10 is divided by 2, exactly.
Another example, 15 / 2 has a remainder of 1. This is because, after division has taken place (15 can be divided 7 times), 1 is left over.
More examples:

The remainder of an integer division only returns the integer part of the result.
For instance, if you were to type 4 / 3 into a calculator, you would see the result is 1.3333333 etc. However, where this calculation is being performed as integer division in a programming language, such as java, only the integer part is returned - producing the result 1.


Sunday, September 9, 2012

Concatenating adjacent numbers

 Where a + symbol has a String on one or either sides, the + symbol is used as the concatenation operator. But where a + symbol has a number on either side, the + symbol is used as the addition operator.

Need to concatenate 2 adjacent numbers? Return the String value of one of the numbers in the following way:


Wednesday, September 5, 2012

Comparing int using the equality operator


Two int values may be compared for equality by using the equals = = operator.

The equals operator returns True or False (boolean).


int one = "10";
int two = "10";

if (one == two) {
System.out.println("The int values are equal.");
}
else {

System.out.println("The int values are NOT equal.");
}


In this example, the equals operator would return true, causing the statement "The int values are equal" to be printed to screen.

The equals operator is used to test equality on all primitive types such as int.

If you need to compare two strings, read here....

Sunday, June 3, 2012

if statements


Is used for implementing selection algorithms. Executes a certain code section only if a condition is true.

Format:

if (expression) {
   'Statements.
}

The expression to be evaluated is placed within parenthesis. Curly braces are used to open a block, immediately after the expression. If the result of evaluating the expression is true, all statements within the curly braces will execute. If the expression returns false, the statements within the curly braces will be skipped.

An expression is a combination of literal values or variables, and operators.

In the example below, the user is asked to enter a number. The if statement determines if the number is less than (less than operator < ) 100 and prints a message to screen, if it is. It then goes on to ask the user to enter their name. The if statement determines if the name has a length (String length) of more than 5 characters and prints a message to screen if it does.


Note that the if statement opens a code block with curly braces.

To recap, if the user enters a number that is less than 100, they will get the message "The number you entered was less than 100" and if the user enters a name that has a length greater than 5, they will get a message saying "The length of your name is longer than 5 characters long".

Here is the output:




Evaluating multiple expressions in an if statement

We can use the logical AND operator && to evaluate multiple expressions.


In this example, if the user enters a number that is greater than 50 AND less than 100, they will get the message "The number you entered was greater than 50 AND less than 100" and if the user enters a name that has a length greater than 5 AND less than 20, they will get a message saying "The length of your name is longer than 5 characters long AND shorter than 20".





also see:
"The if-then and if-then-else Statements (The Java™ Tutorials > Learning the Java Language > Language Basics)" ( http://bit.ly/zflbUx )




Here's a cat...







The concatenation operator

DOWNLOAD THE CODE: ConcatPkg

The concatenation operator is the addition symbol +.

Concatenation is the act of joining multiple values together to form a single String.


Here's the output:


Note! The addition symbol is also used as the addition operator! If the addition symbol is placed between 2 numbers, it will treat the expression as an addition expression!

Sunday, May 27, 2012

While loop

DOWNLOAD THE CODE: usingWhileLoops.java.zip

While is a type of loop. Statements inside of the loop will continue to repeat while the loop condition is true.

The while loop is primed with a boolean expression/condition. When the condition becomes false, the loop will stop.

while (condition) {
    // statements to loop.
}


The example below uses a while loop to increment the value of the int variable num. On each pass of the loop, num has 100 added to it. The loop will continue to execute while the value of num is less than or equal to the value of the int variable maxnum.


The output:


The loop condition can be any expression that return a boolean value.


"Java For Complete Beginners - while loops" ( http://bit.ly/JGnAII )