Tuesday, 21 August 2007

Operators and Assignments (Part 14)

Mathematical Functions - cont
Let’s try out an example now in order to make sure that we know how to use the contents of the Math class.

Type out the following program, which will calculate the radius of a circle in feet and inches, given that it has an area of 100 square feet.

public class MathCalculation{
public static void main(String[ ] args){
double radius = 0.0;
double circleArea = 100.0;
int feet = 0; int inches = 0;
radius = Math.sqrt(circleArea/Math.PI);
// Get the feet as a whole number
feet = (int)Math.floor(radius);
// Calculate the number of inches
inches = (int)Math.round(12.0 * (radius – feet));
System.out.println(“The radius of a circle with area “ + circleArea + “ square feet is\n” + feet + “ feet “ + inches + “ inches”);
}
}

Save the program as MathCalculation.java, compile and run it. You should get the following output:

The radius of a circle with area 100 square feet is
5 feet 8 inches

The first calculation we need, after defining the variables uses the sqrt( ) method to calculate the radius.

Since the area of a circle, with radius r, is given by the formula pir², the radius must be sqrt(area/pi), and we specify the argument to the sqrt( ) method as the expression circleArea/Math.PI. The result is in feet as double value. To get the number of the whole feet we use the floor( ) method. Note that cast to int is necessary, otherwise you will get an error from the compiler.

Lastly we get the number of inches by subtracting the value of whole feet from the original radius, multiplying the fraction of foot by 12 to get the equivalent inches, and then rounding the result to the nearest integer using the round( ) method.

Note how we output the result. We did encounter the System.out.println in our “Hello World” application, but we didn’t explain exactly how it works, so let’s do it now. System is the name of a standard class that contains variables and methods for supporting simple keyboard input and character output to the display. It is contained in the package java.lang so it is always accessible just by using the simple class name, System.

The object out represents the standard output stream – your display screen, and is data member of the class System. This member is referenced by using the class name System separated from the member name out by a period – System.out . The bit at the rightmost end, println(…. ), calls the println( ) method of the object out. This method outputs the text string that appears between the parentheses to your display.

You might be wondering what is the + operator doing here, it’s not arithmetic we are doing, is it? No, but the plus has a special effect when used with character strings: it joins them together (concatenation). Neither circleArea, feet or inches are of type String, but they are all converted to a character string to be compatible with “The radius of a circle with area “.

Exercise 3 – 6 Using math functions
Create an application that gets a random number between 0 and 1000, finds the square root of the number, the log of the number, the sin, cos, and tan of the number and prints them (with suitable text) to the screen. To generate the random number, use the Random class in the java.util package. If your not sure of how these are generated, look up this class and it’s methods in the online documentation.

Monday, 20 August 2007

Operators and Assignments (Part 13)

Mathematical Functions
Sooner or later you are likely to need mathematical functions in your programs, even if it’s only obtaining an absolute value or calculating a square root. Java provides a range of methods that support such functions as part of the standard library stored in the package java.lang, all these are available in your program automatically.

The methods that support various additional mathematical functions are implemented in the class Math, so to reference a particular method you need to write Math and a period in front of the method name. For example, to use sqrt( ) which calculates the square root of whatever you place between parentheses, you should write Math.sqrt(aNumber).

The class Math includes a range of numerical functions. Some of the important ones are listed below in the table:

Method Function
abs(arg) Calculates absolute value of the argument
max(arg1, arg2) Returns the larger of the two argument
min(arg1, arg2) Returns the smaller of the two arguments
ceil(arg) Returns the smallest integer that is greater than or equal to the argument
floor(arg) Returns the largest integer that is less than or equal to the argument
round(arg) Calculates the nearest integer to the argument value

The mathematical functions available in the class Math are:
Method Function
sqrt(arg) Calculates the square root of the argument
pow(arg1, arg2) Calculates the first argument raised to the power of the second argument
exp(arg) Calculates e raised to the power of the argument
log(arg) Calculates the natural logarithm (base e) of the argument
random( ) Returns a pseudorandom number between 0.0 and 1.0

The Math class also defines double values for e and pi, which you can access as Math.E and Math.PI respectively. To find out more about the Math class and the methods it provides please refer to Java Documentation.

Sunday, 19 August 2007

Operators and Assignments (Part 12)

Explicit Casting
It might be that the default way of treating the expressions listed above is not what you want. For example, consider the following Code,

double result;
int two = 2, eleven = 11;
result = 5.5 + eleven/two;


the result variable has a value of 10.5 (because the as both eleven and two are ints, the result of the division is rounded to an int). However, if you wanted the term 11/2 to produce the value 5.5 so the overall result would be 11.0, then you can do this using an explicit cast as follows:

result = 5.5 + (double)eleven/two;

This causes the value stored in eleven to be converted to double before the divide operation takes place and the operand two is also converted to double before the divide is executed. Hence the value of result will be 11.0.

This can (and must or compiler will complain) also go the other way where a large datatype is “squeezed” into a smaller datatype. Consider the next example:

long bigValue = 99.98765L;
int squeezedValue = (int)(bigValue);


without the (int) typecast in the second line, the compiler will flag an error. Variables can automatically be promoted to a longer form though without the need of explicit casting.
Consider the sequence of basic types,

byte --> short --> int --> long --> float --> double

an automatic conversion will be made as long as it is upwards through the sequence, that is from left to right. If you want to go in the opposite direction then you must use an explicit cast. Make sure that you don’t lose information when you do so.

Saturday, 18 August 2007

Operators and Assignments (Part 11)

Strings - cont

Extracting Substrings
The String class includes a method, substring(), that will extract a substring from a string. There are two versions of this. The first one,

public String substring(int beginIndex)

returns a new string that is a substring of this string., the substring begins with the character at the specified index and extends to the end of this string. The second one,

public String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. For example,

"smiles".substring(1, 5) returns "mile"

Exercise 3 – 5
For this exercise you are required to segment the following string:
“We Love our Java Course”
and display it as follows:

We
Love
our
Java
Course

You should make use of both indexOf() and substring() methods. Use the online documentation to help with this exercise. Although we won’t cover loops until later in this section, you may need to use a While loop. This has the syntax of :

while (condition is true) {
// CodeText that needs to iterate goes here
}

Friday, 17 August 2007

Operators and Assignments (Part 10)

Strings - cont

Searching for Substrings
There are two methods available in the class String, that will search a string, indexof() and lastIndexOf(). They both have four different versions to provide a range of possibilities.

Method - Description
indexOf(int ch) - Returns the index within this string of the first occurrence of the specified character ch. If the character, ch doesn’t occur, -1 is returned.

indexOf(int ch, int index) - Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. If the value of the index is outside the legal limits for the String object, -1 is returned.

indexOf(String str) - Returns the index within this string of the first occurrence of the specified substring str. If it does not occur as a substring, -1 is returned.

indexOf(String str, int index) - Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If the value of the index is outside the legal limits for the String object, -1 is returned.

lastIndexOf(int ch) - Returns the index within this string of the last occurrence of the specified character. If the character, ch doesn’t occur, -1 is returned.

lastIndexOf(int ch, int index) - Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. If index is negative -1 is returned. If the character does not occur at or before the index then –1 is returned.

lastIndexOf(String str) - Returns the index within this string of the rightmost occurrence of the specified substring. If it does not occur as a substring, -1 is returned.

lastIndexOf(String str, int index) - Returns the index within this string of the last occurrence of the specified substring. The returned index indicates the start of the substring. If it does not occur as a substring starting at index or earlier, -1 is returned.

Thursday, 16 August 2007

Operators and Assignments (Part 9)

Strings - cont

Sequencing Strings
When you have a collection of names and you want to place them in order, testing for equality is not going to work. What you need is a method compareTo() which is defined in the class String.

The method is called as follows:
string1.compareTo(string2);

It returns an integer which is negative if the string object is less than the argument passed, zero if they are both equal and positive integer if the string object is greater than the argument passed.

Strings are compared by comparing individual corresponding characters, starting with the first character in each string, until two corresponding characters are found to be different or the last character in the shorter string is reached. Individual characters are compared by comparing their numeric values, so two characters are equal if the numeric value of the UniCodeText character are equal. For example, if string1 has the value “anil” and string2 has value “anirudh”, then the expression,
string1.compareTo(string2);
will return a negative value as a result of comparing the fourth characters in the strings.

Exercise 3 – 3 Comparing Strings

Create at least 2 variables of type String (call them name1, name2) and then store the names Rover and Citroen in that order. Now rearrange them so that they will be stored in an alphabetical order (in other words, name1 will contain Citroen). Finally display them on the screen in the new order.

Exercise 3 – 4 Comparing 2 strings using parameters

Now adapt the last exercise to take in parameters from the command line (the String args[] part of main) so that you can compare any two strings when you run the application. This exercise is a little difficult at this point as it uses arrays. Arrays are covered in a later section. For now, use the online documentation to help you solve the exercise

Wednesday, 15 August 2007

Operators and Assignments (Part 8)

Strings - cont

Comparing Strings
To compare variables of the basic types for equality you use the = = operator (Two equals signs in a row). This does not apply to String objects (or any other objects). The expression,
string1 == string2
will check whether the two string variables refer to the same string. This expression will have the value of false if string1 and string2 reference separate strings, regardless of whether the strings happen to be the same.

Let’s demonstrate this with an example:
public class CompareStrings{
public static void main(String[] args){
String string1 = “The Java ”;
String string2 = “course”;
String string3 = “The Java ”;
if (string1 == string3){
// Now test for identity
System.out.println(“string1 and string3 point to the same string: ” + string1);
} else {
System.out.println(“string1 and string3 do not point to the same string”);
}
string3 = string1 + string2;
string1 += string2;
// Display the contents of the strings
System.out.println(“string3 is now: ” + string3);
System.out.println(“string1 is now: ” + string1);
if (string1 == string3){
// Now test for identity
System.out.println(“string1 and string3 point to the string: ” + string1);
} else {
System.out.println(“string1 and string3 do not point to the same string”);
}
}
}

You can use the method equals(), defined in the String class to check whether the strings that string1 and string3 reference are equal or not. If you want to compare two strings ignoring the case, you can use equalsIgnoreCase(). Both equals() and equalsIgnoreCase() return a boolean. To compare string1 to string2, you would do it as follows:
string1.equals(string2);

Exercise 3 – 2 Comparing strings with equals()

· change the CodeText above so you do the string comparison with the equals() method rather than the == operator.

Tuesday, 14 August 2007

Operators and Assignments (Part 7)

Strings

String Objects

A String variable an object of the class String. You declare a String variable in much the same way as you define a variable of one of the primitive types. You can initialize it in the declaration:
String myString = “My string”;

You can store another string in a String variable, once you have declared it:
myString = “Another string”;

Notice that although it is a class, you do not need to use the “new” keyword to create instantiate an object.

String Operations

There are many kinds of operations that can be performed on strings, string concatenation, string comparison, searching strings for characters, searching for sub-strings, etc.

String Concatenation
You have already used this operation to join strings together. The + operator is used to achieve this. For example,
myString = “This string 1 ” + “This is string 2”

If either of the arguments are String objects, then all other arguments will be converted to String objects.

Monday, 13 August 2007

Operators and Assignments (Part 6)

Relational and Conditional Operators

A relational operator compares two values and determines the relationship between them. The table below summarizes Java's relational operators:
Operator Name Use Return true if
> Greater than x > y x is greater than y
>= Greater or equals x >= y x is greater than or equal to y
<>
<= Less than or equals x <= y x is less than or equal to y
== Equals x == y x and y are equal
!= Not equals x != y x and y are not equal

Relational operators often are used with the conditional operators to construct more complex decision-making expressions. One such operator is &&, which performs the boolean and operation. For example, you can use two different relational operators along with && to determine if both relationships are true. The following line of CodeText uses this technique to determine if the value of x lies between 10 and 15,
if (x >= 10 && x <= 15)
In this instances, the second operand to a conditional operator is not evaluated if x = 5, because it does not matter whether the second condition is true or not as && only returns true when both conditions evaluate to true. In order for both operands to be evaluated regardless of the statement outcome, use another boolean and operator &. The operator & is similar to && if both of its operands are of boolean type. However, & always evaluates both of its operands and returns true if both are true.

The table below summarizes Java's conditional operators:
Operator (long name) Use Return true if
& (logical AND) x & y x and y are both true,
always evaluates x and y
&& (conditional AND) x && y x and y are both true,

conditionally evaluates op2
if x is true
(logical OR) x y either x or y is true,

always evaluates x and y
(conditional OR) x y either x or y is true,

conditionally evaluates op2
! (NOT) !x x is false

Sunday, 12 August 2007

Operators and Assignments (Part 5)

Shortcut assignment and Pre – Postfixes

There also are two shortcut arithmetic operators, ++ which increments its operand by 1, and -- which decrements its operand by 1. There are two versions of this, prefix and postfix. Both the prefix and postfix versions of this operator increment the operand by 1. So why are there two different versions? Because each version evaluates a different value: x++ evaluates to the value of the operand before the increment operation, and ++x evaluates the value of the operand after the increment operation.

You use the basic assignment operator, = , to assign one value to another. Java also provides several short cut assignment operators that allow you to perform an arithmetic or logical operation and an assignment operation all with one operator. Suppose you wanted to add a number to a variable and assign the result back into the variable, like this:
x = x + 7;
You can shorten this statement using the short cut operator +=.
x += 7;
The two previous lines of CodeText are equivalent.

The table shows the shortcut assignment operators and their lengthy equivalents:

Operator Use Equivalent to
+= x += y x = x + y
–= x –= y x = x – y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y

Exercise 3 – 1 evaluate the prefix and postfix operators

· Type in the following Code and compile it. Before you run the application, answer the questions that are in the comments. Now run the Code and see if your answers match the output.

public class Shortcut{
public static void main(String args[]){
int x = 10;
int y = 0;
// x will equal 10
System.out.println("X = " + x);
x+=2;
// question (1) what will x equal?
System.out.println("X = " + x);
y = x++;
// question (2) now what will y equal?
System.out.println("Y = " + y);
// question (3) but what is x now?
System.out.println("X = " + x);
y = ++x;
// question (4) what do you think y is now?
System.out.println("Y = " + y);
// question (5) how about x now?
System.out.println("X = " + x);
}
}

Saturday, 11 August 2007

Operators and Assignments (Part 4)

Operators

It's useful to divide Java's operators into these categories: arithmetic, relational and conditional, bitwise and logical, and assignment. These are discussed in the following sections.

Arithmetic Operators

The Java language supports various arithmetic operators for all floating-point and integer numbers. These include + (addition), - (subtraction), * (multiplication), / (division), and % (modulo).

The precedence that applies when an expression using these operators is evaluated is same as you learned in school. Multiplication and division are executed before any addition or subtraction operations.

For example,
15 – 2*5 + 20/5
will produce the value 9, since it is equivalent to 15 – 10 + 4.

If you want to change the sequence of operations then you can use parentheses. Expressions within parentheses are always evaluated first, starting with the innermost when they are nested.

For example,
(15 – 2) * (5 + 20) / 5
will produce 65.

Friday, 10 August 2007

Operators and Assignments (Part 3)

Variable Initialization

All variables in Java have to be initialized before you can use them in your Code. When an object is created, instance variables are automatically initialized when the storage is allocated. These instance variables are initialized to either 0 or null (booleans are initialized to false).

Local variables, on the other hand, have to be explicitly declared. Consider the following Code snippet:

public void computeSum(){
int x = 100;
int y;
int z;
// this will cause an error during compilation
z = y + x;
}

Thursday, 9 August 2007

Operators and Assignments (Part 2)

Variables and Scope

You have seen two ways that variables can be described: variables of primitive type or variables of reference type. You have also seen two places variables can be declared: inside a method (a method is an object-oriented term which refers to a function or subroutine such as main() ) or outside a method but within a class definition. Variables can also be defined as method parameters or constructor parameters.

Variables defined inside a method are called local variables, but are sometimes referred to as automatic, temporary, or stack variables.

Variables defined outside a method are created when the object is constructed using the keyword new xxxx(). There are two possible kinds of variables. The first kind is a class variable which is declared using the static keyword. This is done when the class is loaded. Class variables continue to exist for as long as the class exists. The second kind is an instance variable which is declared without the static keyword. Instance variables continue to exist for as long as the object is referenced. Instance variables are sometimes referred to as member variables, as they are members of the class. The static variable will be discussed later in this course in greater detail.

Method parameter variables define arguments passed in a method call. Each time the method is called, a new variable is created and lasts only until the method is exited.

Local variables are created when execution enters the method, and are destroyed when the method is exited. This is why local variables are sometimes referred to as “temporary or automatic” variables. Variables that are defined within a member function are local to that member function, so you can use the same variable name in several member functions to refer to different variables.

For example:
class AllCar {
// this is an instance variable of AllCar
int chassiNumber;

int findType(){
// this is a local variable
int carType;
// both chassiNumber and carType are accessible
return 1;
}

int changeType(){
// another local variable although it has the
// same name as in the findType() method
int carType;
/* the scope of carType is limited to the body of the method it’s declared in. Both chassiNumber (an instance variable of the AllCar class) and carType (a variable local to this method) are accessible here */
}
}

Wednesday, 8 August 2007

Operators and Assignments (Part 1)

This section discusses operators and expressions and teaches different controls structures that govern the path of execution or flow.

Section Objectives

Understand the difference between local and instance variables

Describe how instance variables are initialized

Understand and use operators in Java

Distinguish between legal and illegal assignments of primitive types

Use boolean expressions in control constructs

Recognise type compatibility and casting types to others

Use if, switch, for, while, do constructions and use break and continue flow structures within a program

Tuesday, 7 August 2007

Java Language Fundamentals (Part 10)

Self Test Questions

· What are the 3 types of comments in Java?

· What is the standard naming convention for variables? Methods? Classes? Constants?

· What are the legal identifiers?

· How big is a:
Char
Byte
Short
Int
Long
Float
Double

· What does 36.789F mean?

· Write a simple class which models an aircraft.

Monday, 6 August 2007

Java Language Fundamentals (Part 9)

Objects and Classes - cont

Now, you can create a new type by basing it on your class. The variables within the class and the final constant are called members and can be referenced by a variable which has been declared on the new type.
For example:

TheCar myCar;

Using this declaration, you can reference the variables by using dot (.) notation. Again, using the car example:

myCar.topSpeed = 127;
myCar.lowSpeed = 25;

The myCar variable which is based on the TheCar class is declared not on the data itself, but rather a reference to the data. You can (if you like) think of the variable myCar as a pointer to the class TheCar. This is because the declaration of myCar doesn’t actually allocate memory space for that object.

Before you can actually use this reference variable (myCar) you have to instantiate it using the keyword new. This will allocate space for the three integers used to form TheCar. This reference (myCar) now becomes an object.

To finish the example:
class TheCar{
int topSpeed;
int lowSpeed;
final int MAX_SPEED = 200;
}
public class OurCar{
public static void main(String args[]){
TheCar myCar;
myCar = new TheCar();
myCar.topSpeed = 127;
myCar.lowSpeed = 25;
System.out.println("top speed = " + myCar.topSpeed);
System.out.println("low speed = " + myCar.lowSpeed);
System.out.println("max speed = " + myCar.MAX_SPEED);
}
}

Exercise 2 – 1 using a class variable
· Use the above material to create an application called BigPet which will print 5 different attributes (features) of the concept of a pet (number of legs, tail, weight, name, colour) Use a class called AllPets to hold the member variables. Then use println to send the string “My pets name is Binky and he has 8 legs. He is black and weighs 0.89 kg”

Sunday, 5 August 2007

Java Language Fundamentals (Part 8)

Objects and Classes

Although we won’t launch into Object-Oriented theory now, we’ll quickly cover the basic idea of classes and objects.

A class is like a blueprint or template. An Object is a tangible item, something you could touch or see. The common example is a house. You have a blueprint of a house, but you don’t live in the blueprint. You have to construct a house object to live in. A Method is like a function or procedure. You use methods to do things with an object.

For example, if you wanted to model the concept of a car, you might like to (amongst others) declare these variables to hold some important data about cars in general. So you might declare:
int topSpeed;
int lowSpeed;
final int MAX_SPEED = 200;

Then if you wanted to make 2 cars, you would have to type:

int topSpeed1, topSpeed2;
int lowSpeed1, lowSpeed2;
final int MAX_SPEED = 200;

As you can see, this would be very impractical for lot’s of cars! A better idea is to create a class.

For example:
class TheCar{int topSpeed;int lowSpeed;final int MAX_SPEED = 200;}

Saturday, 4 August 2007

Java Language Fundamentals (Part 7)

Language Fundamentals


Data Types - cont

Integrals & floats

The following table gives the length of integrals and floats






























Name or TypeLength
byte8 bits
short16 bits
int32 bits
long64 bits
float32 bits
double64 bits

Note! Floating
point literals are double unless explicitly
declared as type float


The following is an example of a various declarations


public class
ExampleDeclarations{


public static
void main(String args[]){


int
topSpeed = 150;


float
gear1Change = 25.09F;


double
gear2Change = 48.98;


boolean
goFast = true;


char
myCharacter = ‘R’;


String
errorMessage = “You made a boo boo!”;


}


}



Friday, 3 August 2007

Java Language Fundamentals (Part 6)

Single characters are represented using a char type. A char literal must be enclosed by single quotes (‘ ‘) whilst a String type (which is not a primitive class but is used to represent a collection of characters) us double quotes to delimit (“ “). A sequence of character data is called a string and is implemented in the Java environment by the String class (a member of the java.lang package). You will need to use character strings in most of your programs, if only to output error messages. Strings You have already been making extensive use of string constants for output. Every time you used the println() method, you used a string constant as the argument. A string constant is a sequence of characters between double quotes:

String myString = “This is a string!”;

Some characters can’t be entered explicitly from the keyboard to be included in a string constant. For example you can’t include a double quote because it is used to indicate where a string constant begins and ends. You can’t also use a new line character by pressing Enter key, as this will move the cursor to a new line. For this reason you must use an escape sequence to specify those characters. Shown below is a list of escape characters that you can use to define control characters:

\’ Single quote \t Tab
\” Double quote \n New line
\r Carriage return \\ Backslash
\u???? Replace Unicode with Hexadecimal


If for example, you want to print the following string on the screen,

“He’s brilliant in Java”
He can just about do anything.
then you can write it as follows:

“\”He\’s brilliant in Java\”\n\tHe can just about do anything.”

Thursday, 2 August 2007

Java Language Fundamentals (Part 5)

Java Language Fundamentals

Data Types - continued

The range of values stored by each type is always the same, regardless of what kind of computer you’re using. Therefore your program will execute in the same way on computers that may be quite different. In contrast the format and size of primitive data types of other languages may depend on the platform on which a program is running.

Declaring a variable is exactly same as it is in C. For example:

int value; long bigValue;

float value; double bigValue;

char letter; boolean check;

You can also initialize them at the same time you declare them. For example:
int value = 10; long bigValue = 99999999L;
float value = 1.28E12F; double bigValue = 1.56E-35;
char letter = ‘a’; boolean check = true;

Note: All integer values of type long must have an L appended to them to differentiate them from other integer constants. Same with the float variables, they must have F or a D appended to them.

Booleans
Booleans have two states – true and false. In other languages, a boolean can also have the value of 0 or 1 to signify true or false, but in Java, the only valid values are the literals “true” and “false”. For example:
// declares the variable truth as a boolean and assigns a value
boolean truth = true;

Wednesday, 1 August 2007

Java Language Fundamentals (Part 4)

Java Language Fundamentals (Part 4)


Data Types


All variables in the Java language must have a data type. A variable's data type determines the values that the variable can contain and the operations that can be performed on it. For example, the declaration


int value

declares that

value
is an integer (
int
).

There are two major categories of data types in the Java language: primitive and reference. The following table lists, by keyword, all of the primitive data types supported by Java:


















































Data Type



Description



Integral type




byte



Values from –128 to +127



short



Values from –32768 to +32767



int



Values from –21474883648 to +2147483647



long



Values from –9223372036854775808 to
+9223372036854775807



Floating type




float



Values from –3.4E38 to +3.4E38



double



Values from –1.7E308 to +1.7E308



textual




char


logical



Stores single character (16-bit Unicode character)



boolean



Can have one of two values (true or false)


Saturday, 28 July 2007

Java Language Fundamentals (Part 3)

Java Language Fundamentals (Part 3)


Java Keywords


The following is a list of keywords in the Java language











































































abstract



do



implements



private



throw



boolean



double



import



protected



throws



break



else



instanceof



public



transient



byte



extends



int



return



true



case



false



interface



short



try



catch



final



long



static



void



char



finally



native



super



volatile



class



float



new



switch



while



continue



for



null



synchronized




default



if



package



this



Friday, 27 July 2007

Java Language Fundamentals (Part 2)

Java Language Fundamentals (Part 2)


Identifiers


Identifiers are the blocks of a programming language - that is, they are the entities (values and data) that act or are acted upon. An identifier can be any length, but it must start with a letter, an underscore or a dollar sign. The rest of the identifier can include any characters except for those that are used as operators, e.g. +, -, * and others. There is one more restriction, you can’t use keywords in Java as a variable name. Valid identifiers are:



  • Identifier

  • UserName

  • User_Name

  • _Sys_name

  • $changeName


Java uses 16 bit Unicode rather than 8 bit ASCII text, so a letter has a considerably wider definition than just a to z or A to Z.


As mentioned before, an identifier can’t be a keyword, but it can contain a keyword as part of it’s name. For example:

importText()
is valid even though import is a keyword.

Tuesday, 24 July 2007

Java Language Fundamentals (Part 1)

Java Language Fundamentals (Part 1)



Comments and Code Conventions


There are 3 types of comments allowed in the Java language:



     // comment on one line

     /* comment on one or more lines */

     /** comment which can be used in the javadoc tool to produce HTML documents */

Always document your code!!!!! I’ll say it again, ALWAYS DOCUMENT YOUR CODE!!! Well documented code is easy for other developers to modify at a later date. In fact you could be that developer, who has to change the undocumented code that you produced a year earlier and can’t remember what all of those 1000 lines of code does.

Do not put obvious comments in. if you have one line of code in a class that prints a string, don’t write “this class prints a string”. On the other hand, if you have a complex class that contains 150 lines of code, comment liberally.

Whitespace (tabs, newlines, etc.) in Java is ignored. A line of code is terminated with a semicolon(;) even if that line happens to span several lines on your screen. A block of code is a collection of statements bounded by opening and closing braces. For example:


     {
topSpeed = 120;
lowSpeed = 35;
}

You can increase readability by using meaningful class, variable, and method names. Avoid using names like “d1” – rather use something like “firstDate”. The Java convention for identifiers are:

Class identifiers – a noun with the first letter of each word capitalized – for example: class MyCat

Variables – a noun with the first letter of the first word lowercase and each subsequent word capitalized – for example: int topSpeed;

Methods – a verb with the same naming convention as variables – for example: public void DropCat()

Interfaces – capitalized like class names

Constants (finals) – all letters capitalized. For example:

Final int MAX_SPEED = 200;

Also, the use of indentation is invaluable. Consider the following code snippet:

while (counter < 0){
for (loopCounter = 0; loopCounter < 11; loopCounter++){
System.out.println(“this is difficult to read”);
}
System.out.println(“think how this looks with another 100 lines!”);
}

or this code snippet:

While (counter < 0){


For (loopCounter = 0; loopCounter < 11; loopCounter++){

System.out.println(“this is better”);
}

System.out.println(“this shows the inner loop better”);
}


Monday, 23 July 2007

Java Language Fundamentals (intro)

Language Fundamentals



Nuts and Bolts

This section covers the basic components of the Java Language. It will include variables, keywords, primitive types and class types.


Section Objectives


  • Use comments and learn the Java coding convention
  • Recognize the difference between valid and invalid identifiers
  • Recognize Keywords
  • List the eight primitive types
  • Define literal values for numeric and text types
  • Be able to discuss the terms class, object, member variable, and reference variable
  • Create a simple class
  • Declare variables of type class
  • Use the new keyword to construct an object
  • Describe default initialization
  • Access member variables using dot notation
  • Understand the consequences of assigning variables of class type

Sunday, 15 July 2007

Java Fundamentals (part 9)

Exercises and Self Test Questions


Exercise 1 - 3 Using the API Documentation



  • Find the println method description in the System class


Exercise 1 - 4 Create another simple Java application



  • Create an application that prints the following 3 strings on separate lines: “Why am I doing this” , “I must be mad”, “Java is .....”
  • Compile and run the program


The Menu Applet



  1. Create an applet called MyMenu that displays the following text in the applet:

    1. Print first string
    2. Print second string
    3. And now print the third string



  • Now create a simple html file that will display the applet. Make the applet size 300 by 400
  • Use Appletviewer to display the applet
  • Now use your desired internet browser to display the
    applet

Self Test Question



  1. Is Java compiled or interpreted? Why?
  2. If you create an application on an Apple Macintosh machine, can you run the same program on a Sun Solaris platform? Why?
  3. What does the term “Garbage Collection” mean?
  4. What does the class loader do? What about the bytecode verifier?
  5. What is wrong with this code snippet?

    Public class BadClass{
    Public void main(string args){


    }
    }


  6. What language does Java resemble most closely?

Saturday, 14 July 2007

Java Fundamentals (part 8)

Using the Java API Online Documentation



The main source of information as to the various classes, fields, and methods available in the Java language is detailed in the Application Programming Interface (API) documents. These HTML files are arranged hierarchically, so that the home page lists all the packages as hyperlinks. If you select a link, the classes contained in that package are listed. Selecting a class then brings up a description of the class, it’s fields and methods, and links to related classes, methods and fields.

Figure 2 – The Java API Online Documentation




The main sections of a class document are:


  • The class hierarchy


  • A description of the class and it’s general purpose


  • A list of it’s member variables (fields)


  • A list of it’s constructors


  • A list of it’s methods


  • A detailed list of it’s variables with a description


  • A detailed list of it’s constructors with a description


  • A detailed list of it’s methods with a description


Unfortunately, there aren’t many examples available to demonstrate the syntax. There are general examples available in a separate folder on your hard drive.

Friday, 13 July 2007

Java Fundamentals (part 7)

Dissection of the “Hello World” Applet



If you refer back to the HelloWorld.java file you can see that the code starts off with two import statements. By importing classes or packages, a class can more easily refer to classes in other packages. For example if you do not want to import the packages then you have to add the highlighted bits shown below to your HelloWorld.java file:

public class HelloWorld extends java.applet.Applet{
public void paint(java.awt.Graphics g){
g.drawString("Hello world!", 50, 25);
}
}


This might not seem much extra to write at the moment, but believe me when your code is more than 500 lines it is going to be so much easier to just import the packages rather than to include the whole path in your code.

Besides importing individual classes, you can also import entire packages. Here's an example:

import java.applet.*;
import java.awt.*;


Note: You might have noticed that the “Hello World” application example from the previous lesson uses the System class without any fix, and yet does not import the System class. The reason is that the System class is part of the java.lang package, and everything in the java.lang package is automatically imported into every Java program.

There is no overhead involved with importing entire packages so there isn’t any real reason not to!

Lets now move onto the class definition. Every applet must define a subclass of the Applet class. In the "Hello World" applet, this subclass is called HelloWorld. Applets inherit a great deal of functionality from the Applet class, ranging from communication with the browser to the ability to sent a graphical user interface (GUI). The extends keyword indicates that HelloWorld is a subclass of the class whose name follows Applet. If the term subclass means nothing to you don’t panic, you'll learn about it soon.

The HelloWorld applet implements just one method, the paint method. Every applet must implement at least one of the following methods: init, start or paint. Unlike Java applications, applets do not need to implement a main method. We will go into the details of init, start and other methods bit later in the course.



Returning to the above code snippet, the Graphics object passed into the paint method resents the applet's onscreen drawing context. The first argument to the Graphics drawString method is the string to draw onscreen. The second and third arguments are the (x,y) position of the lower left corner of the text onscreen. This applet draws the string "Hello world!" starting at location (50,25). The applet's coordinate system starts at (0,0), which is at the upper left corner of the applet's display area.

Thursday, 12 July 2007

Java Fundamentals (part 6)

Dissection of the “Hello World” Application - continued



Exercise 1 - 2: The “Hello World” Applet


Create a text file named HelloWorld.java with the code shown below:


import java.applet.Applet;


import java.awt.Graphics;


public class HelloWorld extends Applet {


    public void paint(Graphics g) {


            g.drawString("Hello world!", 50, 25);


    }


}

Compile the source file with the Java compiler and as before it should create a HelloWorld.class file in the same directory.


Note: Java compiler in the JDK will compile both applications and applets.


An applet is not executed in the same way as an application. You must embed an applet in a web page before it can be run. You can then execute it either in a Java-enabled web browser such as Explorer and Firefox, or you can execute it using the appletviewer provided by JDK.


This means that you should at least know some basic HTML to accomplish this. In this course we are only going to cover enough HTML so we can run over applets. If you would like to learn more advanced HTML then you should get a proper HTML book.


Basic HTML


When you define a web page as an HTML document, it is stored in a file with the extension .html. A HTML document consists a number of elements, and each element is identified by tags. The document will begin with <HTML> and end with </HTML>, these are tags, and each element in an HTML document will be enclosed between a similar pair of tags between angle brackets. Here is an example of an HTML document consisting of a title and some other text:


          <HTML>


          <HEAD>


          <TITLE>My
First Web Page</TITLE>


          </HEAD>


          <BODY>


          You can write
anything you want.


          </BODY>


          </HTML>


The text enclosed by the <TITLE> element tags will be displayed as the window title when the page is being viewed. Other element tags can appear within the <BODY> element, and they include tags for headings, lists, tables, links to other pages and Java applets. You can find a comprehensive list of available HTML tags in any HTML book.


For many element tag pairs, you can specify an element attribute in the starting tag which defines additional or qualifying data about the element. This is how a Java applet is identified in an <APPLET> tag.


Now we know enough to put our HelloWorld applet on a web page so lets continue where we left it.
Using a text editor, create a file named Hello.html in the same directory that contains

HelloWorld.class
. This HTML file should contain the following text:


          <HTML>


          <HEAD>


          <TITLE> A
Simple Program </TITLE>


          </HEAD>


          <BODY>

Here is the output of my program:


          style='background:silver;mso-highlight:silver'><APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>


          </APPLET>


          </BODY>


          </HTML>

Lets look at the shaded line above, the applet to be executed is HelloWorld.class. The file containing the bytecodes for the applet is specified as an attribute in the <APPLET> tag. The other two attributes define the width and height of the region on the screen that will be used by the applet when it executes. These are compulsory.


To run the applet, you need to load the HTML file into an application that can run Java applets. This application might be a Java-compatible browser or another Java applet viewing program, such as the Applet Viewer provided in the JDK. You can invoke the JDK appletviewer from the DOS command prompt as follows:


          appletviewer Hello.html

Java Fundamentals (part 5)

Dissection of the “Hello World” Application



First we start with the comments as HelloWorldAppc.java starts with the comments. The Java language supports three kinds of comments:


/* text */

The compiler ignores everything from /* to*/ .


/** documentation */

This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The JDK javadoc tool uses doc comments when preparing automatically generated documentation.


// text

The compiler ignores everything from // to the end of the line.


Now lets look at the class definition, in the Java language the simplest form of a class definition is


class MyClass{
.
.
}

The keyword class begins the class definition for a class named MyName. The variables and methods of the class are enclosed by the curly brackets that begin and end the class definition block. The "Hello World" application has no variables and has a single method named main.


Every Java application must contain a main method whose signature looks like this:



public static void main(String[] args)

The method signature for the main method contains three modifiers:


public indicates that the main method can be called by any object.



static indicates that main method is a class method.



void indicates that the main method doesn't return any value.



All this will be explained in detail later in the course so don’t worry much about it now.



The main method in the Java language is similar to the main function in C and C++. When the Java interpreter executes an application, it starts by calling the class's main method. The main method then calls all the other methods required to run your application.



If you try to invoke the Java interpreter on a class that does not have a main method, the interpreter refuses to compile your program and displays an error message similar to this:


In class NoMain: void main(String argv[ ]) is not defined


As you can see from the following code snippet, the main method accepts a single argument: an array of elements of type String.




public static void main(String[]
args
)



This array is the mechanism through which the runtime system passes information to your application. Each String in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it.




The program has one line of code which performs an action. This action is to print the string of text “Hello World!” to the screen. This code is




System.out.println(“Hello World!”);



System is a class which is available by default. It has a method called println that prints the string and appends a carriage return. The semicolon at the end terminates the line.

Wednesday, 11 July 2007

Java Fundamentals (part 4)

Simple Application & Applet


Before we get into nuts and bolts of the Java language lets create a simple Java application and an applet to see how really easy it is to develop applications and applets. We will first type the code, compile it and then run it. Don’t worry about what each line of the code does at the moment it will all be explained in a moment, first just concentrate on how to compile and run the Java Program.


Exercise 1 - 1The “Hello World” Application


Using a plain text editor, create a file named HelloWorldAppc.java with the following Java code:



/* *
* The HelloWorldAppc class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldAppc {
    public static void main(String[] args){
//Display the string
System.out.println("Hello World!");
}

Java source code is always stored in files with the extension .java


Be aware that Java is case sensitive. In other words, Graphics is not the same as graphics!


Compile the file using Java compiler that comes with JDK, you would do this by typing the following command at your MSDOS command prompt (windows) :


javac HelloWorldAppc.java


If the compilation succeeds, the compiler creates a file named HelloWorldAppc.class in the same directory (folder) as the Java source file. This class file contains the Java bytecodes, which are platform-independent codes interpreted by the Java runtime system. If the compilation fails, make sure you typed in and named the program exactly as shown above, using the capitalization shown.


Run the program using the Java interpreter, to accomplish this enter the following command:


java HelloWorldAppc


You should see "Hello World!" displayed at your command line

Tuesday, 10 July 2007

Java Fundamentals (part 3)

Code security



Java enforces it’s code security through the JVM. As mentioned before, Java source files are compiled (converted into a set of bytecodes) and stored in a .class file.



At runtime, the bytecodes are loaded, checked and run in the JVM interpreter. This interpreter has two functions: to execute code and make calls to the underlying hardware. Generally, whilst the bytecode is first interpreted, a portion of the bytecode is compiled to native machine code and stored in memory. If the program is run, say immediately again, the computer can use the machine code. This allows Java to run nearly as fast as C or C++.



The Java Runtime Environment (jre) runs the code compiled for the JVM and performs three main tasks:



Loads the code – performed by the class loader



Verifies the code – performed by the bytecode verifier



Executes the code – performed by the runtime interpreter



The class loader loads all of the classes needed for the program execution. The class loader also separates the classes from the local file system from those imported from other sources. This security feature limits any “Trojan horse” applications (applications which look like standard applications such as a login box but really does something sinister, like stealing your username and password!) because local classes are always loaded first.


The class loader deals with the memory layout of the program. This protects against unauthorized access into restricted areas of code.



The bytecode verifier tests the format of the code and checks for illegal code – code that creates pointers, attempts to change object types, or violates object access rights. The verifier actually passes the code through four times to ensure that the code adheres to the JVM specification and does not violate system integrity.


Figure 1 - The JVM


clip_001 image

Monday, 9 July 2007

Java Fundamentals (part 2)

Java 1.2 Fundamentals


The Java Platform


The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other, hardware-based platforms. The Java Platform has two components:


The Java Virtual Machine (JVM)


The Java Application Program Interface (Java API)


You have already been introduced to the JVM, it’s the base for the Java Platform. The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets. Some of the important features provided by the APIs are shown below:


Security – both low-level and high-level, including electronic signatures, public/private key management and access control.


Java Database Connectivity (JDBC) - provides uniform access to a wide range of relational databases. Networking - URLs, TCP and UDP sockets, and IP addresses.


Object serialization – Allows lightweight persistence and communication via Remote Method Invocation (RMI).


Internationalization – Help for writing programs that can be localized for users worldwide. Programs can automatically adapt to specific locales and be displayed in the appropriate language.


Garbage Collection


In many programming languages, memory is allocated dynamically at runtime with the developer responsible for deallocating this memory. If the developer neglects this somewhat difficult exercise, a memory leak occurs. Eventually, the program will crash as there will be no more memory available.


This process of disposing or deallocating objects which require memory is called garbage collection. Garbage collection is automatic in Java, as Java provides a system-level thread to track memory allocation. The garbage collection process will deallocate memory in the background whilst the program is running. During idle cycles in the JVM, the garbage collection thread checks for and frees any memory that can be freed.

Sunday, 8 July 2007

Java Fundamentals (part 1)

This section is a general overview of programming with the Java language. It introduces the the Java Virtual Machine, Garbage Collection, Security Features, and starts you on your Java programming journey with the humble “HelloWorld” application



Section Objectives



  • Understand the key features of the Java Language

  • Understand about the Java Virtual Machine (JVM)

  • Describe how garbage collection works

  • Discuss the concepts of Classes, Packages, Applications and Applets

  • Write, compile, and run a simple application and applet

  • Use the online documentation to identify Java classes, fields, and methods


What Is Java


Java is a high-level programming language that lets you write programs that you can embed in the web pages (known as applets), as well as programs that you can run normally on any computer that supports Java (known as applications). You can also write programs that will run both as applets and applications.


The most important characteristic of Java is that it was designed from the beginning to be machine independent. Java programs will run without any change on any computer that supports Java.


The next most important feature of the Java is that it is object-oriented. The object-oriented approach to programming is also an implicit feature of all Java programs.


Apart from the above Java is also Robust, Secure, Multithreaded, Dynamic and Distributed. We will go into more depth into each of these as we progress through the course.


Java was created from a number of languages (the Java team took what they considered the best features) and left out some of the worst. For example, Java doesn’t allow you to work with pointers (although a pseudo-pointer can be used as we will discover later), it has automatic memory management or garbage collection, and because it is Object-Oriented, it is easier to visualize and model problems in a real world sense.


Other features of Java are:


Easy to learn: Although Java is a powerful object-oriented language, it is easy to learn, especially for programmers already familiar with C or C++.


Write less code means faster program development: Comparisons of program metrics (class counts, method counts, and so on) suggest that a program written in Java can be four times smaller than the same program in C++. Therefore your development time may be as much as twice as fast versus writing the same program in C++.


Write better code: The Java language itself encourages good coding practices, and its garbage collection helps you avoid memory leaks. Java's object orientation, its JavaBeans component architecture, and its wide-ranging, easily extendible API let you reuse other people's tested code and introduce fewer bugs.


Avoid platform dependencies with 100% Pure Java: By following the purity tips mentioned throughout this course and avoiding the use of libraries written in other languages, you can keep your program portable.


Write once, run anywhere: Because 100% Pure Java programs are compiled into machine-independent bytecodes, they run consistently on any Java platform.


Distribute software more easily: You can upgrade applets easily from a central server. Applets take advantage of the Java feature of allowing new classes to be loaded "on the fly," without recompiling the entire program.


Java is “easier” to learn than, say, C++ but is certainly more difficult than languages such as Basic. Nevertheless, after this course you will find working in Java easier than tying your shoelaces (well, almost!)

Saturday, 7 July 2007

A Java Course Introduction

Java 1.2 Introduction


Java is a write-once run-anywhere language. What this means in practice is that the Java code you create on a PC should run quite happily on a mainframe or Unix machine.

Java also is an Object Oriented programming language that can be used to create stand-alone programs or browser-compatible code (applets).


Learning Java, like any programming language, is a “doing” as well as reading activity. You will find many exercises and self test question throughout this booklet. It is strongly recommended that you attempt each exercise and question. Do not be tempted to skip over questions because they seem difficult. Each exercise has an answer (in fact in programming, there are usually several solutions.)


Course Overview


This course will first discuss the Java runtime environment
and the syntax of the Java programming language. It will then cover
Object-Oriented (OO) concepts as they apply to Java. As the course progresses,
advanced features of the Java platform are discussed.


Whilst Java is a platform independent language, the course was
created on a Microsoft operating environment. Screen shots will differ from
those obtained when working in another operating system such as Unix or
Macintosh. The code, however, remains the same. In other words, the contents of
this course is applicable to all Java operating system ports.


Course Objectives


Upon completion of this course module, you should be able to:



  • Describe key language features

  • Compile and run a Java application

  • Understand and use the online hypertext Java documentation

  • Describe language syntactic elements and constructs

  • Understand the object-oriented paradigm and use object-oriented features of the language

  • Understand and use exceptions

  • Develop a graphical user interface

  • Develop a program to take input from a GUI

  • Understand event handling

  • Read and write to files and other sources of data

  • Perform input/output (I/O) to all sources without the use of a GUI

  • Create applications and applets to access an Oracle database

  • Understand the basic concepts of JDBC

  • Understand the basics of multithreading

  • Develop multithreaded Java applications and applets