Monday, 29 August 2011

Time Off

Posts resume on Thursday, where we'll be writing a palindrome recognizing program using recursion.

Thursday, 25 August 2011

Java: Recursion

This is by far the hardest concept to use for me, even if the idea seems straightforward.

Methods, in addition to being able to call other methods and variables, can call themselves, which makes for interesting ways to solve problems, often resulting in much more concise code.

public int sumOf( int n ) {
    if ( n == 0 ) return 0;
    else {
        return ( n + sumOf( n - 1 ) );

This method returns the sum of every number from 0 up to the parameter provided. To illustrate this, use n = 2. The steps it goes through are as follows:

sumOf( 2 );              //Step 1
Parameter (2) is not 0, so return 2 + sumOf( 1 )

sumOf( 1 );            // Step 2
Parameter (1) is not 0, so return 1 + sumOf( 0 )

sumOf( 0 );            //Step 3
Parameter is 0, return 0

Place Step 3 into Step 2, result of Step 2 is 1 + 0 = 1
Place Step 2 into Step 1, result of Step 1 is 2 + 1 = 3

As we see, with every call we make not containing our base case (In this case, n == 0), the next step is required to fill in the blank. This is referred to as the call chain, and it exists whenever a function calls any other function, though it helps visualize recursion more than standard calls.

Recursion can be effectively used as a compressed for of iteration, as the above code is equivalent to

public int sumOf( n ) {
    int sum = 0;
    while ( n > 0 ) {

        sum = sum + n;
        n = n - 1;
    return sum;

When you get recursion down, it can be faster to code than by the iterative process above, as well as being more compact, although it takes more resources to run, which is a fairly large issue with larger programs.

Play around with it, and try to get a feel for what it does. No Java post on Monday, I'll be off for a couple of days.

Monday, 22 August 2011

Java: Method Parameters

When we want to call a function, but want the result to be based on input, we use parameters. An example we've already seen of this is in System.out.println(), with the desired text being the parameter, and what gets printed out.

To have this functionality inside a method you create, you need to place the type, and give a name to, a variable inside the brackets right after the name.

public int doubleNumber(int parameter) {
return 2*parameter;

In here, you need to call the function doubleNumber with some value in it, named parameter. Inside the function you can do whatever you want with the variable. Simple. To place in multiple parameters, we just separate them by a comma.

public int multiply(int a, int b) {
return a*b;

Short update, next time: Recursion

Thursday, 18 August 2011

Java: Methods, Returning Values and the Void type

In Java, a method is a series of statements separate from everything else in the program, given it's own name. This allows it to be referenced later. We used methods (or functions) in earlier examples for ease. It allowed us to perform actions without having to think about the internal working of the method, so in this way, it shares similarities with the concept of abstraction.

public void greet() {

System.out.println("Hi, there!");
System.out.println("How are you today?");


In the above example, we have a method named "greet", and the brackets immediately proceeding show that it takes no parameters (More on that next time, basically input to change how the function works). Preceding the name is "public void", public stating who can use the function (encapsulation), and the type of the returned value, which we'll talk about shortly.

The body of the method simply prints out 2 lines of text, which can now be printed out more simply by calling this method.


Since the method needs to be part of a class object (Java being an object oriented language), the object which it's a part of must be created, and then the method can only be called as a function of the object, as shown above.

On top of being an abstraction to hold a group of statements, methods are used to compute values, and return a value in place of that method. Assuming we had a method, "calculateHeight" as part of the object exampleObject, we could have:

int i = exampleObject.calculateHeight();

Then, stored in i is the value gained through the function. To have a method return a value, or a string, we need to state the type it returns when declaring it, and have a return statement at the end of it.

public int calculateHeight(){

//Do stuff...
return someInt;

If someInt is not calculated, or is not an integer type, your compiler will freak out and throw some errors at you, so always test and double check. Another difference to the previous method is instead of void, we have int. This is the type of the return value, but as in the previous method, a return value isn't always needed, so instead of creating a different method type for this case, or forcing the user to simply return 0 all the time, as some other languages do, there is just the void type. Nothingness.

Monday, 15 August 2011

Java: Encapsulation and Abstraction

Abstraction, briefly mentioned before, is the way we capture the important aspects of something while ignoring the unique details between individual things. A chair, as opposed to a red cushioned mahogany etc etc. This is important to help people understand complex systems, as well as communicate and reason about them. Without abstraction, the level of detail required to understand systems is enormous, leaving people to be unable to build the object mentally.

Close to the idea of abstraction is encapsulation, a mechanism meant to ensure objects have a definitive inside and outside. The insides are protected from the outside, preventing any arbitrary changes to them. Once encapsulation is in place, the only way to access the abstract object is via some interface visible to the outside, keeping the actual workings of the inside hidden from view. They're not needed to make use of the abstraction.

Defining and making use of these 2 concepts is basically the main point of programming, especially with an Object Oriented language like Java.

Interested in reading ahead? I'm using "Developing Java Software" by Winder and Roberts, Third Edition.
Questions or concerns? Feel free to post a comment, I'm learning this freshly, so I might well have not explained something fully, or explained it completely wrong, feedback appreciated.

Thursday, 11 August 2011

Java: Simple Programs

Okay, now we have an IDE, let's write a program with the knowledge we have.

For our first example, let's have the program ask for the dimensions of a cuboid, and then give a message displaying its volume.

import java.util.logging.Level;
import java.util.logging.Logger;

//The above "imports" tell the program what external files are being used. Your IDE should
//automatically let you know what you need up there if you use a common function from one.

public class Dimensions {
//The name of this class should be the name of the file you are working with

    static BufferedReader br = new BufferedReader(new InputStreamReader(;
    static String input = null;
    public static String getInputStr() throws IOException {
    input = br .readLine();
    return input;

//The above block of code was what we used for the input. Go back a couple of posts to refresh

    public static void main(String[] argv) throws IOException{
    //this is the main function that's called when the program is run. It must always be
    //public static void main and take an array of Strings as the argument. the "throws IOException"
    //is only there because of the input function above also requiring it.

    int height;
    int width;
    int depth;
    int volume;

    System.out.println( "Please enter the height of the cubeoid " );
    height = Integer.parseInt(  getInputStr() );   //Integer.parseInt is required, since input given is 
                                                                             //in string format and cannot simply be read as an int
    System.out.println( "Please enter the width of the cuboid: " );
    width = Integer.parseInt ( getInputStr() );

    System.out.println( "Please enter the depth of the cuboid: " );
    depth = Integer.parseInt( getInputStr() );

    volume = height * width * depth;                    //This simply calculates the volume. The entirety of
                                                                             //the reason for this program is in 1 line, everything
                                                                             //else is data collection and presentation. This is
                                                                             //more or less typical.

    System.out.println( "The volume of the cuboid is: " + volume );


For our final example, let's try a program that prints out the Nth Fibonacci number.

//required imports

public class Fibonacci { //Our main class

    static BufferedReader br = new BufferedReader(new InputStreamReader(;
    static String input = null;
    public static String getInputStr() throws IOException {
    input = br .readLine();
    return input;
    }  //Input functionality

    public static void main(String[] argv) throws IOException { //Main function

        System.out.println( "Which number of the Fibonacci sequence do you want?" );

        int seqNum = Integer.parseInt( getInputStr() );
        int currVal = 1;
        int prevVal = 0;

        for (int i = 1; i < seqNum ; i++ ) {   //This for loop means "For every integer, i, starting from 1, up until
                                                              //before seqNum (incrementing by 1), perform the following :
           currVal += prevVal;                    //Current value in the sequence is the previous 2 values, so
                                                              //current value (before change) + previous value (before change)
                                                              //gives the 2 sequential values before the value we want to store into        
                                                              //current value
           prevVal = currVal - prevVal;       //New current value - old previous value = new previous value

        System.out.println(currVal);            //And bam, answer.


Monday, 8 August 2011

Picking an IDE

Now that we have some basics down, we want to start writing programs, as opposed to just snippets of code. For this, we need an IDE, an integrated development environment, which basically acts as spell check for code. There's many out there all with different pros and cons, with the top 2 contenders being Eclipse and NetBeans. Many people like Eclipse, it's a sort of catch-all and can be used for many languages, but I personally use NetBeans, the choice is yours. Google them both, try them out. See which one you like.

There's too much variance between IDEs and too many tweaks, so suffice to say, pick your own, and it'll probably not matter much in the end anyway. Next time, we'll begin writing a few simple programs using our IDE.

Thursday, 4 August 2011

Java: Input Statements

Second update, as promised! We've already looked at the output command, but certainly you'd like some interactivity with your program? What use is a program without a user? So we have input commands.

These are, however, more awkward to use than the output commands, so bear with it.

    static BufferedReader br = new BufferedReader(new InputStreamReader(;
    static String input = null;

    //The above 2 lines create the string to store the input into, as well as the buffered reader to 
    //actually read the input. Don't worry too much about the mechanics of this yet.

    public static String getInputStr() throws IOException {

        input = br .readLine();
        return input;


   // The above, from "public static..." to the closing curly brace is a function to more easily get the 
   // input later on in the code. We'll talk more about functions later, but for now, just know that
   // with this, we can type "getInputStr()" at a later point, and we will be given whatever's typed
   // into the standard input (keyboard).

With this bit of functionality, we can write a short program to take a user's name, then give a greeting to him or her.

System.out.println( "Please enter your name: " );
System.out.println( "Hello, " + getInputStr() + "! \nHow are you today?" );

This gives the output:

Please enter your name:
heddin (This is where I placed my input)
Hello, heddin!
How are you today?

Java: Output Statements

There are 2 ways to output a statement in Java, with only a slight difference between them.
Take the following example:

int i = 0;                             // This initializes the variable "i" to 0
while ( i < 6 ) {                  // While loop beginning, loops as long as i is less than 6 

        System.out.print(i);  // System.out.print() is the output command. Note that this doesn't
                                         // automatically end line, as we will see in the output.
         i += 1;                    // Make sure to have this line to affect the conditional variable.
                                       // Otherwise, the loop will never end. "i += 1" is the same as
                                       // i = i + 1, just incrementing the variable by 1
 }                                     // End loop.

The above code returns the output: 012345
Having no separator between each printed number, whitespace of any kind (Space, tab or newline) makes it look like this. Luckily, there's another way to print things that automatically places an end of line character at the end of each passed string;

int i = 0;
while ( i < 6 ) { 

    i += 1;

The output of the above is:


But what if we want a new line in the middle of a string? The newline character is "\n", a tab is "\t" and a space is simply a space. If you wanted to separate the above output by spaces instead of newlines, you would have to concatenate the strings.

System.out.print( i + " " );