Learning How To Program [Part 2]

posted by on 6th May 2010, at 4:10am

You may remember that last month we started the discussion on how one can start programming. We went through a basic rundown of what programming is, looked at possible languages to work with, and built a template for learning that language. Right now we’re going to resume that process by building a resource list, setting up your environment and implementing our starter programs.

We will be covering Java in this article and as a result our resources will be plentiful. Java is currently widely used for teaching the basics of programming for those wanting to branch out into the Computing Science field. In accordance with the template established in the previous article, I have gathered some resources for learning Java:

  • BlueJ – Our code editor. It is a lightweight and simple to use editor with no extra features. This means that it focuses on the code entirely and eliminates the “Wizards” one would fine in other kitchen sink applications.
  • A Basic Java Tutorial – Here you will find simple examples of introductory Java code. This should be used as a guide for language syntax should you get stuck.
  • A Slightly More In Depth Tutorial – This tutorial from Sun is more advanced as it covers Object Oriented concepts. I suggest you look at language basics if you want to skip Objects at this time.
  • Java API Specification – The API specification has detailed documentation on every class and method that exists in Java. A case where it should be used is to inventory all the mathematical functions Java has available.
  • Stackoverflow – This is one of my favourite sites on the web. It’s essentially a giant help forum devoted to anything based on programming/development/computer science.
  • Google

Now that we have our resources, it’s time to set up our environment. I am going to assume that the majority of the reader base out there is using some variant of Windows for this tutorial. Let us begin.

The first step is to install the the Java Development Kit (JDK). If you’re running Mac OS X, you already have it, so you can skip this step. For other Windows based operating systems you can head over to Sun’s website and download the JDK here. After this is downloaded and installed, install BlueJ.

Upon installing BlueJ you will be greeted with the default project view from above. Once BlueJ is installed the setup is almost complete. This is partly why BlueJ was chosen: simplicity. The only thing left to do is to install our keyboard input library. We install a custom keyboard library since the built in console keyboard input is hard to use. I have compiled the library we are going to use into a JAR file. In order to install the library:

  1. Download the JAR file here.
  2. Place the JAR file in C:\BlueJ\lib\userlib (assuming you used the default install path).
  3. Restart BlueJ if it is running.

For those of you that are interested, you can see the source code for the library here (not needed for our purposes).

Now that our environment is set up it’s time to dive into the code. At this point I feel it’s important to say that this guide is meant to give you a jump start on writing actual code. We could spend a whole article discussing the merits and drawbacks of Java’s Object Oriented system but we won’t do that now. As a result of this in the coming code chunks there are a few places where you will have to take my word for granted as to what a certain piece of code does.

To get started select Project -> New Project and navigate to your preferred save location. Call your first project “HelloWorld” and hit “Create.” BlueJ will then create a new window which is your current workspace. Right click on any open area and choose “New Class…” Enter in “HelloWorld” for the name leaving Class Type as “Class.”

After this open the class it created for you by double clicking on it. The first thing that must be done is gutting the class. Remove everything in between public class HelloWorld { and the last } in the class. You should be left with:

/**
* My very first Java program.
*
* @author Shane A.
* @version May 4, 2010
*/
public class HelloWorld
{

}

This tells Java that we are creating a new class called “HelloWorld”. At this point it would be logical to discuss just exactly what a class is. In order to discuss what a class is we would have to discuss what an Object is and how that fits into the bigger picture of Object Oriented Programming (OOP). For now it is sufficient to think of an Object as a real world object. A square block is an object, a circular disk is an object, and you are an object. Following from this, think of a class as a set of blueprints in order to perform a set of actions on one of these objects.

Next we want to add a main method to the class. A method is a subroutine that is runnable from within the class. The main method is special as it is run automatically when the application is started. We add the method by putting public static void main() { inside of our class. By now you’ve probably noticed that there are repeated occurrences of curly braces (‘{‘ and ‘}‘), these are key to Java syntax. Any class or method must have their contents surrounded by curly braces.

This brings us to a class that looks like this:

/**
* My very first Java program.
*
* @author Shane A.
* @version May 4, 2010
*/
public class HelloWorld
{
public static void main()
{

}
}

Earlier I said that there are some times in this article in which you must take my word for granted; this is one of those times. The main method will run when the program begins. The method has to be declared as public static void in order to be run at the start of program execution. If you are interested in what each of those words means in terms of the current context you should read ahead in the Sun Java tutorial.

Each of the programs in this article will have the same start as we have just defined. From here we are able to specialize our program to do what we want, it’s also where the fun begins. All that remains to do in our first program is to make the console output “Hello World!”

In order to output text to the console Java provides us with two methods print() and println(). print() simply outputs the given argument while println() adds a line break at the end of the line. in order to output Hello World! we just call System.out.println(“Hello World!”); From this we learn a number of new things about Java. First, Strings (text) must be enclosed in quotation marks. Second, Java is case sensitive and simply writing system.out.println(“Hello World!”); would not work. Finally, all statements must end with a semi-colon (;). Using this new knowledge we’ve completed our first program!

/**
* My very first Java program.
*
* @author Shane A.
* @version May 4, 2010
*/
public class HelloWorld
{
public static void main()
{
System.out.println("Hello World!");
}
}

To run it simply press “Compile” at the top of your code window and then flip back to your BlueJ project window. In your project window right click the HelloWorld class and choose void main(). If your program runs successfully you should see something like this:

This concludes our first recommended program. For the rest I will include a brief description of what the program is expected to do and some non-related examples of the concepts. It will be your job to implement a working solution. I will include my solutions to the below problems but not until a week after this article has been released. This is to give you a chance to get your feet wet, play around, and make mistakes; then hopefully learn from them.

Here is the list of suggested projects:

Say Hello *

Description: Say Hello to the user instead of the World in general.
Hint: Read and store user input by using: String data = StdIn.readLine(); Output data using System.out.println() or System.out.print()

Fahrenheit to Celsius Converter *

Description: Convert user inputted Fahrenheit temperatures to Celsius.
Hint: Read and store input with: int numb = StdIn.readInt();. Use C = (5/9) * (F – 32).

Is a person young or old? *

Description: Use basic input techniques to get the users’ age and then tell them if they are old or young by using conditional operators.
Hint: if (a < b) will tell you if a is less than b. Conversely, if (a > b) will tell you if a > b. Check the Sun Java tutorial on conditionals.

The Change Machine *

Description: Request a decimal dollar amount. The program will then use a combination of output, operators, and conditionals to give the user their change in coin form.
Hint: This will require multiple levels of conditionals. The modulus operator can also be used.

Table of Values *

Description: Using your favourite quadratic equation build a table of values. This program will use output and a new concept: counting repetition.
Hint: Use a for loop. for (int i = 0; i < 10; i++) { (code here) } executes the code segment 10 times.

More Repetition (post-condition)*

Description: Automate the previous fahrenheit to celsius conversion.
Hint: Use a do…while loop. do { } while(condition); Use code from the previous input/output conversion problem.

More Repetition (pre-condition)*

Description: Automate the previous fahrenheit to celsius conversion.
Hint: Use a while loop. while (condition) { } Use code from the previous input/output conversion problem.

Reduce Code Repetition for Interfaces **

Description: Easily repeat sections of code at different places to build interfaces using functions. Generate ascii art and repeat it.
Hint: Use a public void function.

Reduce Code Repetition for Calculations **

Description: Easily repeat calculations by using function. Convert your fahrenheit to celsius conversion program to use a function.
Hint: Use a public double function.

Each of the above programs are going to be hard to do for a first time programmer. The ease of implementation is specified by the amount of asterisks beside the program name. The point of these exercises isn’t to create working code on the first run; the point is to attempt to get something working. I hope that instead of waiting a week for the solutions that you give each a try to the best of your ability and if you run into problems you use the above mentioned resources to try to solve them. The worst case scenario is that you can’t solve a problem, if that’s the case just send me a private message on the forums.

You can download the full source code here.


This article is filed under Tech. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.