Friday, December 21, 2012

Consider if 2 objects are equal....

Demo Code Project: OverridingEquals.zip

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

What do you consider equal?

Read on...

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


Consider the example above.

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

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

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

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

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

overriding equals(Object)

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

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

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

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

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

...which looks like...



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

Here is the definition of the class called Asteroid2:



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

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

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

Here's the code:






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

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

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

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

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

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


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

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

One last thing...

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


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

see also:

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

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


member access operator (.)

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

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

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

playerOne.fight()


Monday, September 24, 2012

Modulo %

Download the code

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


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

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


Generating a random number

also see Using the Random class to generate a random int

The Math class contains a static method for random number generation.

To generate a single random int between 0.0 and 1.0 you can use the following:

int number = (int)(Math.random() * 10);


This method returns a value from 0.0 to 0.9. A whole number, from 0 to 9, can be produced by multiplying the result by 10.

Note that casting has been used to convert the return value, which is a double, to int.

And remember, static class methods may be called without creating an instance of the class.

Where many random numbers with a larger range are required, see java.util.Random such as below:

In this example we are going to generate random numbers between 1 and 100:


The statement rand.nextInt(100) + 1 gets the next random number in the range of 1 - 100 inclusive. Need a large number? Adjust to suit.


Sunday, September 16, 2012

Casting


DOWNLOAD CODE PROJECT: Casting

Casting can be used to convert an object of one class type to another, within an inheritance hierarchy.

For instance, all Java objects inherit from the Object class. A class called Player may be implicitly cast into the type Object, as below:

Object o = New Player();

However, the following statement will not compile:

Player P = o;

This is because a Player object is always an instance of Object whereas an Object is not always an instance of Player (An Object is alllll kinds of things).

We need to tell the compiler that o is an instance of Player, as below:

Player P = (Player) o;

This is called explicit casting - or down casting. Note that the type we are casting to is included in the parentheses.

The Animal family
Consider a family of classes where Animal is the superclass and it has sub classes of Mammal and Fish. In this scenario, Animal is the generalisation and Mammal & Fish are the specialisation.



We could, for instance, create an ArrayList to store all types of Animal, as below:

ArrayList<Animal> animalList = new ArrayList<Animal>();

and to that list we could add any type of animal:

animalList.add(New Mammal());
animalList.add(New Fish());

When the Mammal & Fish object types are added to the ArrayList, they have been implicitly cast as Animal. This means that they may only be used in the context of Animal - only state and behaviour belonging to Animal will be accessible from theses objects (even though we can see their actual type, on the screen in front of us).

If we wish to use these objects as their specialised type, we must first discover their run time instance type and then use explicit casting - down casting, to convert.

Consider the following inheritance hierarchy:



(NOTE: The diagram shows the hierarchy incorrectly - Mammal and Fish should be swapped :P)

There are now 7 types of Animal and we have instantiated each type into the ArrayList, as below:

ArrayList<Animal> animalList = new ArrayList<Animal>();
animalList.add(New Animal());
animalList.add(New Mammal());
animalList.add(New Fish());
animalList.add(New Bass());
animalList.add(New Snapper());
animalList.add(New Wombat());
animalList.add(New Kangaroo());


Let's say we want to search the list for certain types of Animal - remember, currently the compiler sees them all as the generalised type - Animal, because that is the type of the ArrayList. 

We could look for specific types, such as Bass. Or we could look for types of specialised type - for instance, finding all types of Fish.

Getting the specific type - equals
In the example below, a loop is used to traverse the list of Animal, looking for objects of the specialised type Bass. 

The equals() comparison method is used on each object to evaluate whether it's run time class is equal to Bass.


Note the statement:


The getClass() method returns the run time class of the object. The equals() method then compares that type to the type mentioned in the parentheses. In this case, Bass.

In the next statement, if the evaluation is true (if the currentAnimal object was found to be of type Bass), the Animal object (currentAnimal) is explicitly cast to an object of type Bass (bass).



The bass object now has the context of Bass, meaning that it may access all state & behaviour of Bass, as well as Fish, as well as Animal.

Getting types of specialised type: instanceof operator
In the example below, a loop is used to traverse the list of Animal, looking for any objects which are types of Fish. Remember, Fish, as well as being a subclass of Animal, is also a superclass of Bass and Snapper.

The instanceof operator is used on each object to evaluate whether it's run time instance type is equal to Fish.



Note the statement:


The instanceof operator determines if the currentAnimal object is an instance of Fish, regardless of whether it's specific type if Bass or Snapper. This means that all objects of type Fish, Bass and Snapper will be discovered using this method.

In the next statement, if the evaluation is true (if the currentAnimal object was found to be an instance of Fish), the Animal object (currentAnimal) is explicitly cast to an object of type Fish (f).



The f object now has the context of Fish, meaning that it may access all state & behaviour of Fish, as well as Animal.


Saturday, September 15, 2012

Sunday, September 9, 2012

Concatenating adjacent numbers

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

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


Wednesday, September 5, 2012

Method Overloading


You may have many methods with the same name in a class. This is known as method overloading. 

The rule is that each parameter list must be different. This applies to constructors as well.

doFoo(int param1, int param2)
doFoo(String param1, int param2)
Correct: Same name, unique parameter list.

doFoo(int param1, int param2)
doFoo(int param1, int param2)
Incorrect: Same name, same parameter list.

Comparing int using the equality operator


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

The equals operator returns True or False (boolean).


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

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

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


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

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

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

Comparing String using the .equals method


Two String objects may be compared for equality by using the .equals function.

The equals method returns True or False (boolean).


String one = "Apples";
String two = "Oranges";

if (one.equals(two)) {
System.out.println("The strings match.");
}
else {

System.out.println("The strings DO NOT match.");
}



In this example, the equals method would return false, causing the statement "The strings DO NOT match" to be printed to screen.

The .equals function is available in all objects and Strings.

If you need to compare two primitive types such as int, read here....


Sunday, August 19, 2012

Your Sunday Cat


Customising Eclipse - Changing font size / appearance

Having trouble reading the code editor? You can customise the appearance (good for tired eyes!).


To customise the font appearance in Eclipse:
(Note: These screenshots have been created on a Mac)

Step 1
Locate Preferences
  • Mac: Eclipse > Preferences
  • PC: File > Preferences (from memory)

Locate the preferences menu

Step 2
  1. Go to General > Appearance > Colors and Fonts
  2. Select Java Editor Text Font from the list
  3. Click Change
  4. Select your desired settings and click OK


Changing font appearance settings




Customising Eclipse - Content Assist feature

Content Assist is a feature in Eclipse that provides context sensitive information about what you are typing. It can be particularly helpful for reminding you of the name of fields and methods.

By default, Content Assist is set to trigger when you type the period (.) character. This is useful, however in this guide I will show you how to get it to trigger at the beginning of a statement as well.

To customise how Content Assist works in Eclipse:

Step 1
Locate Preferences

  • Mac: Eclipse > Preferences
  • PC: File > Preferences (from memory)


Locate the Preferences in Eclipse

Step 2
Select Java > Content Assist
In the Auto Activation settings:
  1. set Auto activation delay to 0
  2. set Auto activation triggers for Java to a single space followed by a comma (,), followed by a period (.). (by clearing the textbox & typing)



Content Assist settings in Preferences



Changing the Auto activation triggers for Java


Step 3

Apply > OK

Try it

  1. type a single space in your code file to see that Content Assist pops up immediately
  2. type a character to see that Content Assist filters the list to names starting with that character
  3. use the arrow keys to move through the list and hit enter to insert the name
  4. place a period after the inserted name to see that Content Assist pops up immediately
Type a space at the beginning of a statement to activate Content Assist.


Type a period after a name to activate Content Assist.


Thursday, August 9, 2012

Naming a package


"Naming a Package (The Java™ Tutorials > Learning the Java Language > Packages)" ( http://bit.ly/N7Y70U )

Tuesday, August 7, 2012

equals


"Java: ==, .equals(), compareTo(), and compare()" ( http://bit.ly/Nygeae )

"Java Practices -> Implementing equals" ( http://bit.ly/MZN7Tb )

"Object equality - JavaWorld" ( http://bit.ly/MZNpJC )

FlowLayout


"FlowLayout (The Java™ Tutorials > Creating a GUI With JFC/Swing > Laying Out Components Within a Container)" ( http://bit.ly/MZHggI )

Tuesday, July 31, 2012

Wednesday, July 25, 2012

Tuesday, July 17, 2012

Black Box testing

Testing the functionality provided by the application, rather than the internals of the application.

"Black-box testing - Wikipedia, the free encyclopedia" ( http://bit.ly/NRhj0u )

"Black Box and White Box Testing for Application Blocks" ( http://bit.ly/Ny47wM )

Whitebox testing

Testing the internals of an application, rather than testing the functionality provided by the application.

"White-box testing - Wikipedia, the free encyclopedia" ( http://bit.ly/NRgZ1A )

"Black Box and White Box Testing for Application Blocks" ( http://bit.ly/Ny47wM )

Coupling & Cohesion


Tight coupling: With such high inter-dependancy,  a change in one class causes a ripple effect of changes in other classes.

Cohesion: Where modules/classes perform tasks that have much in common.

"oop - Coupling and cohesion - Stack Overflow" ( http://bit.ly/NxYv5C )

"Strive for low coupling and high cohesion What does that even mean" ( http://bit.ly/NxYzlM )

"Coupling (computer programming) - Wikipedia, the free encyclopedia" ( http://bit.ly/NQM6KS )

"Cohesion (computer science) - Wikipedia, the free encyclopedia" ( http://bit.ly/NxY9fb )

Monday, June 11, 2012

File class

The Scanner & PrintWriter classes can read from & write to text files, respectively.

Each of these classes contains a constructor that accepts a File object.

The File class belongs to the java.io library (io stands for Input Output).

The example below declares a File object that references the io library directly. Notice that a String containing a filepath/filename is passed to the file's constructor. This File object called file, is then passed to the constructor of the Scanner object. In essence we are saying, read from this file at this location.


The next example declares a File object using a shorter declaration. The library reference has been done via an imports statement at the top of the code (not shown). Once again a String filepath/filename has been passed to the constructor. The file object is then passed to the constructor of the PrintWriter object. In short, we are saying, write (print) to this file at this location.


"File (Java)" ( http://bit.ly/JWg0sp )

"java.io (Java Platform SE 6)" ( http://bit.ly/JWhUcw )

String trim()

DOWNLOAD THE CODE: TrimmingWhitespace

The Java Character class defines whitespace as one of a few different types of characters, including the space character & a carriage return character.

The String class contains a trim() function which removes leading & trailing (at the beginning and at the end) whitespace.

For example, if we are reading a text file using Scanner, with a semi-colon as the delimiter, we only want to read the meaningful part of the string. Carriage returns should be discarded.

For our examples, we will use the following text file nums.txt. See screenshot below:



The code example below reads nums.txt, inside of a while loop.The semi-colon is used as the Scanner's delimiter. Each token in the string ends with a semi-colon and the next begins immediately after the semi-colon. This means that any carriage return characters may be included in the token. This is not ideal and will produce the following result:


Here is the output:


Note that the carriage return separating the lines between the tokens "five" and "six" has been read and rendered.

Using trim()
In the example below, we will trim() each token so that any whitespace such as carriage return characters are discarded.


Here is the output:




Sunday, June 3, 2012

Scope

A variable may only be referenced from within the region where it is declared.

"Variable Scope : Variable Scope « Language « Java Tutorial" ( http://bit.ly/KHplZ5 )

the double data type

A double is a numeric data type. Suitable for storing floating point (decimal) numbers such as weight, length, etc. Any kind of number with a "point something' in it such as 7.6, 10.5, 1.2, etc.

Where a double has not been assigned a value, by default it's value is 0.0d.

The format for declaring a double variable is:

   Type identifier;

Where the Type is double and the identifier is weight:

   double weight;

...and where a value of 100.50 has been assigned:

   double weight = 100.50;


You can declare a double in one statement and assign it a value in another statement:

   double weight;
   // other statements...
   weight = 100.50;



See also:

"Primitive Data Types (The Java™ Tutorials > Learning the Java Language > Language Basics)" ( http://bit.ly/xesQuj )
"Java For Complete Beginners - Double variables" ( http://bit.ly/ZzYTJ9 )

if then else statements

DOWNLOAD THE CODE: UsingIfThenElse.zip

<<< back to if statements

In the previous post on if statements, we saw how we could use an if statement to detect if a condition was true and then execute statements accordingly. An if-then-else statement allows us to branch off in multiple directions.

The example below determines if the user has entered an age that is equal to or greater than 18. If this condition evaluates to true, the user receives the message "You are 18 or over". If the age is anything else, the user receives the message "You are less than 18".



Here's the output:




In the next example, we have multiple if's to determine the entered age:


Note that each if section is contained within curly braces.

Here is the output:





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

if statements


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

Format:

if (expression) {
   'Statements.
}

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

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

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


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

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

Here is the output:




Evaluating multiple expressions in an if statement

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


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





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




Here's a cat...







The concatenation operator

DOWNLOAD THE CODE: ConcatPkg

The concatenation operator is the addition symbol +.

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


Here's the output:


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

Saturday, June 2, 2012

Escape Sequences

From "Characters (The Java™ Tutorials > Learning the Java Language > Numbers and Strings)" ( http://bit.ly/LUgCyw )


Switch

CODE DOWNLOAD: UsingSwitch.zip


A Switch can be used to evaluate a number of numeric types such as byte, short, char & int.

Let's say you want to check the value of a single variable and based on this value, one of many things may happen.

In the example below, the user enters a number. This number is then checked by the switch. The first case to match, executes a statement - in this case, printing a message to let the user know what the entered value was.


If the user entered a value not listed in the cases, the default section executes. It is good practice to always include a default case in your switch.

Notice that the final statement in each case is break. This causes the switch to stop checking down the list.

We can also execute a common statement for multiple cases, as in the example below:


Of course, we could use a number of if then else statements to achieve the same result, however, as we are only checking the value of a single variable, the switch is a more elegant and readable solution (subjective).

Here's a cat:




"The switch Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)" ( http://bit.ly/y2TVYE )

int data type



An int is a numeric data type

An int is a whole number between -2,147,483,648 and 2,147,484,647 (a pretty big number). The number cannot contain a floating point (no decimal).

Where an int has not been assigned a value, by default it's value is 0.


The format for declaring an int variable is:

   Type identifier;

Where the Type is int and the identifier is maxDamage:


   int maxDamage;

...and where a value of 100 has been assigned:

   int maxDamage = 100;


You can declare an int in one statement and assign it a value in another statement:

   int maxDamage;
   // other statements...
   maxDamage = 100;



See also:

"Java For Complete Beginners - Variables: the int type" ( http://bit.ly/ZA1aE8 )