Pages

Sunday, June 10, 2012

Maths


In this lesson we are going to learn the basic arithmetic operations we can do in Java.

Symbol Operation
+ Adition
- Subtraction
* Multiplication
/ Division
% Remainder

Examples:
a = 5 + 3; //a = 8
b = a - 3; //b = 5
c = b * 2; //c = 10
d = c / 2; //d = 5
e = d % 2; //e = 1

Unary operations:

Symbol Operation
++ Increments a value by one
-- Decrements a value by one

For those one, the variable can be before or following the symbol, but the operation will be different. Here is an example:
int a = 0;
a++; // a = 1
++a; // a = 2
System.out.println(a++); // print 3
System.out.println(++a); // print 4 but a = 3. The instruction prints without changing the value of the variable.

Another form of this use is the following:
int a = 0;
a = +1; //it increments the value of the variable "a".

Logical Operations:

Symbol Operation
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
&& Conditional AND
|| Conditional OR
! Inverts the value of a boolean

Examples:
int a = 5, b = 3;
return (a == b); //return false
return (a != b); //return true
return (a > b); //return true
return (a >= b); //return true
return (a < b); //return false
return (a <= b); //return false
return ((a == b) && (a != b)); //return false
return ((a == b) || (a != b)); //return true
return !(a == b); //return true

Bitwise and bit shift operations:

Symbol Operations
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR

Examples:
int a = 2; // binary value: a = 00000000 00000000 00000000 00000010
a = ~a; // a = -3, binary value: a = 11111111 11111111 11111111 11111101
a = a << 2; // a = -12, binary value: a = 11111111 11111111 11111111 11110111
a = a >> 2; // a = -3 binary value: a = 11111111 11111111 11111111 11111101
a = a >>> 2; // a = 1073741823 binary value: a = 01111111 11111111 11111111 11111111
a = a & 2; // a = 2 binary value: a = 00000000 00000000 00000000 00000010
a = a ^ 2; // a = 0 binary value: a = 00000000 00000000 00000000 00000000
a = a | 2; // a = 2 binary value: a = 00000000 00000000 00000000 00000010

No comments:

Post a Comment