Tuesday, March 27, 2012

Inheritence

When once class is derived / extended / inherited from another class, this relationship is said to be 'Inheritance'.

In Java, the extends keyword is used in the class declaration to implement inheritance.



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

"Is-a - Wikipedia, the free encyclopedia" ( http://bit.ly/JWeeX1 )

An example class diagram.



A handful of data types & variables

String
Any collection of keyboard characters.

Boolean
A true or false value.

Char
A single keyboard character.

int
A whole number between -2,147,483,648 and 2,147,484,647




Methods: Procedures & Functions

DOWNLOAD THE CODE: MethodsPkg

There are two types of methods:
  1. Procedure
  2. Function
All methods begin with a method signature which opens into a code block.

A method signature is a contract which specifies:

  • visibility (can it be seen externally?)
  • what type of data it will return
  • what it will do (the name)
  • which data, if any, it requires to perform it's task

visibility | return data type | method name | (parameters if any) {

}



Procedure
What it does: executes processing statements.

Example:



The method signature for a procedure always contains the keyword void (meaning nothing/empty). This is as opposed to a function, which always returns a value. Read on...


Function
What it does: executes processing statements and returns a value to the calling procedure.

Example:



The method signature for a function always contains a datatype to indicate the type of data that will be returned from the function.

The final statement in a function begins with the return keyword, followed by the data that will be returned. In this case, a String.

Methods may also require incoming values called parameters (sometimes called arguments) which are placed within the parenthesis following the method name.

Statement terminators: Semi-colon ;

;

The semi-colon character ends a statement. It separates statements just as the curly braces separate code blocks.



You do not add semi-colons to class declarations, method signatures, if staetment conditions, loop conditions or Switch conditions.

Code blocks: Curly braces

{...} encloses classes, methods and other blocks of Java code.

There is always one top set of curly braces that belong to the class declaration. Placing your cursor next to a semi-colon (in Eclipse) will cause the matching curly to be highlighted.



Example class showing curly braces used to create code blocks





Monday, March 19, 2012

Richard Stallman - What is free software?

CodePlay - The Computer Scientist

What is a Class? What is an object?

A class is a definition of all state/attributes & behavior belonging to an entity. The following figure is a UML class diagram for an entity called Player. The middle compartment lists each state/attribute of Player and the bottom compartment lists each behaviour of Player.

UML class diagrams are used to design classes. This design is then used to inform the code. It's like a blueprint for building a house.

Objects are created from classes - many objects may be created from a single class - in the same way as one blueprint can build many houses. The following figure is a UML object diagram showing the Player class along with 3 Player objects.

Notice that while each object has a strength and agility attribute, the values for these attributes are unique from object to object. From this diagram, we can see the state of each object.

The behaviours are not listed in the object diagram because all objects share the same behaviours.

"What Is a Class? (The Java™ Tutorials > Learning the Java Language > Object-Oriented Programming Concepts)" ( http://bit.ly/FUAjmF )

What is an object?

"What Is an Object? (The Java™ Tutorials > Learning the Java Language > Object-Oriented Programming Concepts)" ( http://bit.ly/zwj1iO )

Java naming conventions

Because...
  • 80% of the lifetime cost of a piece of software goes to maintenance.
  • Hardly any software is maintained for its whole life by the original author.
  • Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.

...we follow a set of naming conventions when defining names for:
  • packages
  • classes
  • interfaces
  • methods
  • variables
  • constants

Oracle docs http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367


Variables and Data Types

We use variables to store values in a program. Values can have be of different types - for example a value may be a String (any collection of keyboard characters) or a number such as an int.

Why would you want to store values? What kind of values?

Things like:

  • username
  • email address
  • age
  • URL
  • game stats
  • price


The format for declaring a variable is as follows:

Type identifier;

The format for assigning a value to a variable is as follows:

identifier = value;

The format for declaring a variable & assigning a value to it in one statement, is as follows:

Type identifier = value;

Here are some concrete examples:



http://www.functionx.com/java/Lesson02.htm

http://www.tutorialspoint.com/java/java_basic_datatypes.htm

Java reserved keywords

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

Java syntax cheat cheat

"Java Syntax Cheat Sheet" ( http://bit.ly/y7RduJ )

The Static keyword

The static keyword is a Java modifier which associates a class member or method with a class rather than an instance of a class.

For instance, the main method of a class is always static as there must be exactly one instance of the class containing main in order for the compiler to find it.

A class containing static members or methods does not require instantiation in order to use the static methods of the class.

Sunday, March 18, 2012

Scanner class - Part 1

DOWNLOAD THE CODE: Scanner.zip

The Scanner class has methods for reading a number of different types of data such as String, int, Double & Boolean.

By default, the Scanner class uses whitespace to delineate tokens (lines, words, phrases, values, etc).

We can use the Scanner class to read input from keyboard input or from txt files.

Use Scanner to read keyboard input
The example below uses the Scanner class to read keyboard input. Scanner contains several methods for reading different types of data. In this example, the next() & nextInt() methods are used to read the input String and the input int, respectively.


The output:




Using Scanner to read from a text file
The following shoppinglist.txt file contains a number of shopping items. Each item is followed by a number representing the quantity required.


Declare an instance of File and then declare an instance of the Scanner class. Pass the file instance to the scanner instance.

The Scanner class contains a number of Boolean functions to determine whether there is another token of a specified type. The example below uses a while loop in conjunction with the Scanner's hasNext() method of Scanner to determine if another token of any type exists.  In effect, the loop has been primed to 'continue looping while there are more tokens to read'. When there are no more toekn to read, the loop will stop.




The output: 



The final token in this example is the character 1.

By default, the Scanner's next() method is using the whitespace separating the characters in the file, to delineate is string. As such, any string separated by whitespace, is being read in each pass of the loop. The statement input.next() reads the next token in the file.

Let's change the code a little to get these values onto the same line.

The while loop body now looks like this:


The first call to next() reads in the name of the shopping item and is printed to screen via the print() method. The second call to next() is used to read in the quantity is appended to the next line via the println() method. 

The output now looks like this:


Read on to learn about using a nominated deliminator character with the Scanner class.



"Scanner (Java Platform SE 7 )" ( http://bit.ly/ABSuGl )


Simple tutorial using the Scanner class: "Java For Complete Beginners - user input" ( http://bit.ly/Lkr7uN )

"Scanning (The Java™ Tutorials > Essential Classes > Basic I/O)" ( http://bit.ly/LkD03X )

"File (Java Platform SE 7 )" ( http://bit.ly/Jxdc9T )

"The while and do-while Statements (The Java™ Tutorials > Learning the Java Language > Language Basics)" ( http://bit.ly/LkGjIm )

System.in.read()

The System.in.read() function returns an integer (whole number) representing the next character's unicode code. As such, it is suitable in situations where you only need to read the first byte of input.


Returns the 7-bit ASCII code of the next character.

The char data type

The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff'


"Primitive Data Types (The Java™ Tutorials > Learning the Java Language > Language Basics)" ( http://bit.ly/xesQuj )



The Java Tutorials

Great site to get you started

"Lesson: Language Basics (The Java™ Tutorials > Learning the Java Language)" ( http://bit.ly/FP6evY )

What is a String?

DOWNLOAD THE CODE: IntroToStringPkg.zip

A string is a collection of any keyboard characters such as "I love chocolate 100 times more than you !!!"

Where a String has not been assigned a value, by default it's value is null.

In the example below, 2 Strings are created (lines 1 and 2). 

The 3rd statement concatenates (joins) the 2 Strings together (using the addition character). 

The fourth statement returns the number of characters in the String called firstName, by calling the String length() function (all Strings have this function, it returns an int). 

The fifth line finds the first character of the String by calling the String charAt() function (all Strings have this function, returns the character at the specified position). 

The final statement concatenates all of the values together and prints to screen.



The output:


A variable, such as String, can be declared in one statement and assigned a value in another statement, as below:

String myString;
myString = "This is a String!"; 

...or it can be declared and assigned a value in a single statement:

String myString = "This is a String!";







Literal String values (the actual charcters) are always enclosed in double quotation marks. 


See also: "Strings (The Java™ Tutorials > Learning the Java Language > Numbers and Strings)" ( http://bit.ly/K4kbDz )

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

Here's a cat:



System.out.print(String)

DOWNLOAD THE CODE: PrintToConsolePkg

We can use a System.out.print(String) to display a prompt
such as "Input a number : "

If we want to make sure that the line is terminated we can use:

Screen shot:
and the output:


The Main method

A Java project many contain many packages and each package may contain many classes. There must be at least one class containing a main method.

The main method is a static method, belonging to the class, where program execution begins - it's the front door, so to speak. The main method begins the chain of events that load the program into memory, ready for use.

In the Java programming language, every application must contain a main method whose signature is:

public static void main(String[] args)


The main method can optionally take a String array as a parameter, as shown in the parenthesis.

(String[] args)


Java API specification

"Overview (Java Platform SE 7 )" ( http://bit.ly/xIonzZ )

Eclipse and Java for Total Beginners



From http://eclipsetutorial.sourceforge.net/totalbeginner.html

Companion document http://eclipsetutorial.sourceforge.net/Total_Beginner_Companion_Document.pdf

What is an IDE?

Download Eclipse IDE

For Windows
http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/galileo/R/eclipse-jee-galileo-win32.zip

For Mac
http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/indigo/SR2/eclipse-jee-indigo-SR2-macosx-cocoa.tar.gz

For full listing visit http://www.eclipse.org/downloads/

What is Java?

if-then-else statements

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

Finding a char in a String. Example

Finds the Char at position 0 of the string


Getting input: The Scanner class

"Scanner (Java Platform SE 7 )" ( http://bit.ly/ABSuGl )

Default value of primitive data types

From http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html


Primitive Data Types

"Primitive Data Types (The Java™ Tutorials > Learning the Java Language > Language Basics)" ( http://bit.ly/xesQuj )

Switch

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