|
1.2.2
Integers
An
integer is a number that is in the range of ±232 (- 4294967295
though to 4294967295). Assume we want to set the variable "a"
to the number 1. The syntax is the following:
int a = 1;
1.2.3
Arithmetic operators
The
number types in Java would be worthless if you could not use the
arithmetic rules on them. Assume that we have the variables "a"
and "b" where we have store the numbers 4 and 2:
int a = 4;
int b = 2;
int c;
We have
also declared the variable "c" here, where we will put or
store the results of the calculations. Note the syntax we are using
in order to store the information in "a" and "b".
We have first declared and then stored the number in the same statement.
This is a shortcut but it is practically the same as:
int a;
a = 4;
int b;
b = 2;
int c;
Now we
want to do an operation and store the result in the variable "c".
The arithmetic operations work in the following way (note that "*"
is the multiplication operator):
//The number 6 will be stored in "c"
c = a + b;
//The number 2 will be stored in "c"
c = a - b;
//The number 8 will be stored in "c"
c = a * b;
//The number 2 will be stored in "c"
c = a / b;
The two
slashes "//" indicates that the text that follows is a comment.
Let us assume that we now have a more complex mathematical formula
that we want to calculate:
The
syntax for the formula above can be written with parenthesis like
this:
c = ((a + b) / (a - b)) * a + 1;
Assume
that we now want to operate "b" on "a" and store
the result in "a". You can write:
//add "b" to "a"
a = a + b;
//subtract "b" from "a"
a = a - b;
//multiply "a" with "b"
a = a * b;
//divide "a" with "b"
a = a / b;
You will
get the same result if you write:
//add "b" to "a"
a += b;
//subtract "b" from "a"
a -= b;
//multiply "a" with "b"
a *= b;
//divide "a" with "b"
a /= b;
Let us
say that you want to increase or decrease "a" with 1. Then
there are many ways to do this:
increase "a" with 1 decrease "a" with 1
a = a + 1; a = a - 1;
a += 1; a -= 1;
a++; a--;
The
later method is called postincrementation (++) and postdecrementation
(--) and we will use this very often. There is also something called
preincrementation and predecrementation but we will not look at
that here since you will manage well by just using postincrementation
and postdecrementation.
1.2.4
Double and Float
There
are two types of floating point numbers in Java: double and float.
Double uses 64 bits to represent the number and have double the
precision as float that only uses 32 bits. Floating point numbers
work in the same way as integers when operating on the arithmetic
operators. They can be declared in the following way:
double PI = 3.141592654;
float PI = 3.141592654;
1.2.5
Bytes
Bytes
are whole numbers between 0 and 255. The arithmetic operators work
with these in the same way as integers, but with the difference
that a byte cannot be negative or bigger than 255.
1.2.6
Converting between integers and floating point numbers
Let
us say you have two integers "x" and "y" and
that you will be using these to draw a point on the screen later
on. Assume also that we have two floating point numbers "a"
and "b". They have the values:
float a = 7.5;
float b = 1.0;
We will
now draw the sum as an x-coordinate and the difference as a y-coordinate.
Since these numbers are floating point numbers then one may not set
the variables "x" and "y" to go directly to these
values. A special conversion is needed:
//"x" will contain 9 because
//8.5 is rounded to 9
int x = (int)(a + b);
//"y" will containt 7 because
//6.5 is rounded to 7.
int y = (int)(a - b);
This
is called type casting. The floating point numbers are converted
to integers. Observe that the variables "a" and "b"
are not converted to integers during the conversion process. A variables
type cannot change once it has been declared. We can also convert
the other way:
a = (float) (x + y);
The sum
is calculated, converted and the result is stored in the variable
"a". Later
I will be reviewing other uses for this.
1.3
Methods , classes
and references
Note
that my review of object oriented programming is adapted to the
practical use that I see in it, therefore I will not write about
strict object oriented theory.
1.3.1
Methods
A method
is a bit of Java code that is executed only when called (in other
languages they are the equivalent to functions). It may also contain
variable declarations which are only valid within the method. These
variables are therefore called local variables. A method is defined
by the method header and two brackets "}{":
public void myMethod()
{
}
The word
public indicates that the method can be called by other classes,
void indicates that the method does not return a value when
it has finished the execution and "myMethod" is the name
of the method. You can put variables within the parenthesis () that
must be delivered by the user when calling the method in order for
it to work. This particular function do not happen to have any variables.
Another example :
public int yourMethod(int a, int b)
{
a+=b;
return a;
}
If the
method returns anything then "return" must always
be specified. In this particular case the method will return an integer
int which is the sum of the variables "a" and "b".
The function is called like this:
//We declare the "result" variable
int result;
//"result" will contain
//the number 3 after the call
result = yourMethod(1,2);
Another
example:
private byte anotherMethod(int a)
{
return ((byte) a);
}
Private
indicates that method may only be used within the class where it has
been defined. In the return part you can also have calculations even
if it is not so beautiful but this gives a more compact code
(less code). In this example we type cast the integer "a"
to a byte and return it. The method is called like this:
//"a" will contain the number 41
byte a = anotherMethod(1234217);
This is
by the way the same as:
byte a;
a = anotherMethod(1234217);
When
you convert a 32 bit integer to a byte then only the last 8 bits
in the number will be left (the 8 last bits in 1234217 has the value
41). Please note that if you do not specify a returnation object
then the method is called a constructor. It must have the
same name as the class and it will be called when you create an
object of the class. A constructor must allways be declared as public:
public myklass(int a)
{
a++
}
1.3.2
Classes and Objects
A class
may be seen as a representation that may contain many types of variables,
methods and even other classes. Classes are representations for
objects. The object is the product of the class and normally
one works with the object. Assume that we have a car and its blueprint.
If we look at the relation in views of object oriented programming
then the blueprint is the class and the car is the object. The classes
are normally located on the hard drive or the server and they are
loaded when you are going to create an object. You create an object
by reserving primary memory for it. This is called allocating
memory. In a Java program, you always have at least one class.
In strict object oriented theory, it is only the methods in a class
that may work with the variables contained in the same class. However,
in practice, this is not always followed. The following is a class
definition of "car":
public class Car {
//The variable "v" contains the speed in km/h
public int v;
public void drive()
{
//start with 10 km/h
v=10;
}
public void stop()
{
v=0;
}
public void faster(int vincreace)
{
v+=vincreace;
}
public void slowDown(int vdecrease)
{
v-=vdecrease;
if (v<0) v=0;
}
}
| Car |
| v |
| drive() |
| stop() |
| faster() |
| slowDown() |
|
The example
above is a class definition. The cells below "Car" describes
what variables (in blue) and what methods (in cyan) that are in the
class.
1.3.3
References and allocating objects (the new command)
You
communicate with an object with references (a reference is
equivalent to pointers in C++). Let us say that we want to create
an object to work with. We take the "blueprint" we have
defined in the last section and create a reference like this:
Car onecar;
The reference
"onecar" does not point anywhere at the moment so you cannot
work with it. Now we allocate a bit of memory to the object "onecar"
which will use the class "Car" as the blueprint. At the
same time that we do this we set the reference "onecar"
to point at the object.
onecar = new Car();
Now we
can reach the instance of the class "Car" with "onecar"
(an instance is another word for object):
onecar.drive();
onecar.faster(10);
onecar.slowDown(10);
onecar.stop();
By calling
the methods above we manipulate the variable "v" that represents
the speed inside the "Car" object. We can create all the
instances we want of the class Car:
Car volvo = new Car();
Car ford = new Car();
volvo.drive();
ford.drive();
//increse speed by 10 km/h
volvo.faster(10);
//increate speed by 10 km/h
volvo.faster(10);
//increase speed med 30 km/h
ford.faster(30);
//decrease speed with 20 km/h
ford.saktaner(20);
Which
car do you think will have the highest speed after these calls? Note
that the variable "v" in the "volvo" object does
not change when you call the "ford" objects speed methods.
Both objects are completely independent and they each have their copy
of "v".
1.4
Other important elements in Java
I will
briefly outline the remaining things necessary before we can begin
programming programs.
1.4.1
Strings
The
built-in string class String is, according to me, one of Java language's
most important classes because it exists in nearly all the Java
programs. A string can be defined in the following way:
String myfirstname = new String("Anibal");
String myfirstname = "Anibal";
The form
above follows the general rule for creating new objects (see
section 1.3.3). The other way and also the most
used is that you directly set the variable to the text value. This
can only be done with the String class. This is a trick that the compilator
recognizes in order to simplify the use of the String, because of
its extensive use. When you have defined a string you can do a lot
with it. Among other things, you can merge strings by using the plus
operator "+".
String myfirstname = "Anibal";
String myfamilyname = "Wainstein";
String myfullname = myfirstname + myfamilyname;
The string
"myfullname" will contain "AnibalWainstein". It
does not look right so we will add a blank space between the first
name and the family name:
myfullname = myfirstname + " " + myfamilyname;
Now you
will obtain the right content, "Anibal Wainstein".
As we said before, a String is an object that also includes methods
which could help you handle strings. A String-method that we will
use a lot is indexOf() which you can use to find out if a part of
a phrase contains another phrase or word:
int index = myfullname.indexOf("stein");
Here we
declare an integer where the method indexOf() will store the result
of the string search. The result will be 11 because the phrase "stein"
begins at the eleventh position in the String. If "stein"
did not exist in the string then the result would have been -1 which
means that the search did not find the phrase. Another String method
that we will use a great dealis substring() which can be used to fetch
a phrase from a string:
String firstname = myfullname.substring(0,6);
The
variable "firstname" will contain the string "Anibal"
which was fetched from "myfullname". Note that we have
specified the start index 0 ("A") and the end index 6
(the blankspace " ") for the string which will be fetched.
The end index 6 is exclusive, which means that the letter in the
sixth position (the blankspace " ") will not be included.
| A |
n |
i |
b |
a |
l |
|
W |
a |
i |
n |
s |
t |
e |
i |
n |
| 0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
1.4.2
Logical operators (Boolean variables)
A
boolean variable contains the values "true" or "false".
It can be declared as follow:
boolean isfine = true;
or
boolean isfine = false;
There
are also operators that work with boolean variables. One of them is
the AND operator (&&). It works as follows. Assume that we
have two boolean variables "a" and "b":
boolean a = true;
boolean b = false;
boolean result = a && b;
The variable
"result" is only true if "a" is true and
"b" is true (In this example the result is false). Another
important operator is the OR operator (||):
boolean result = a || b;
Here "result"
is true if and only if one of the variables "a" or "b"
are true.
An
operator that generates (returns) a boolean result is the "equals"
operator (=
=). Assume that we have two integers :
int x = 100;
int y = 101;
boolean result = (a == b);
The variable
"result2 is true if and only if "x" has the exact same
number as "b" or the reverse. The "equals" operator
is actually one of several comparison operators such as "less
than" (<), "greater than" (>), "greater
or equal to" (>=) and "less or equal to" (<=).
1.4.3
IF-statements
An
"if" statement is one of the fundamental commands in Java.
With the if-statement you can test a boolean statement and then
execute different program code depending if it is true or not (with
the ELSE-statement):
if(a > b)
{
String r = "A is greater than B";
}
If you
want to execute other code if the statement is not true then you can
add ELSE:
if(a > b)
{
String r = "A is greater than B";
}
else
{
String r = "A is not greater than B";
}
1.4.4
FOR loops
A for
loop consists of a bit of code where the "for" command
states how many times the code should be executed. It is defined
in the following way:
for (init; condition; incrementation)
{
code that will be executed
}
The type
of loop that will used about 90% of the time in this course is:
for (int i=0; i<5; i++)
{
code that will be executed
}
What will
happen here is that the loop will count to four and store the subsequent
values in the variable "i". The condition "i<5"
states that "i" must be less than 5, that is, "i"
is not allowed to receive greater values than 4. The expression "i++"
will increase "i" until we reach 4. You can also count down
in for-loops:
for (int i=5; i>0; i--)
{
code that will be executed
}
The variable
"i" will start with 5 and count down to 1. The expression
"i++" decreases "i" with 1 each time, but the
condition "i>0" makes sure that "i" never reaches
0.
1.4.5
WHILE loops
The
while loop works in a different way. It executes code as long as
an expression is true:
while (condition)
{
code that will be executed
}
The same
functionality in the for loop that we had in the last section can
be done with a while loop:
int i = 0;
while (i<4)
{
i++;
}
Note that
here we cannot write "i<5" because the incrementation
happens after the comparison. The expression above will count
from 0 to 4 with "i". The decrementation example in the
last section can be done like this:
int i = 5;
while (i>0)
{
i--;
}
That
is it for now! In the next chapter you will learn how to program
and compile your first applet.
Copyright
© 1999-2005 Mandomartis Software Company
|