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)