Sunday, August 5, 2012

Writing Your First Program

A fine tradition.
As we mentioned in the previous lesson, all Java programs need a little code to let the computer know where to start. This program shell looks like this when generated by Eclipse:
package packageName;

public class ClassName {

    /**
     * @param args
     */
    public static void main(String[] args) {
       // TODO Auto-generated method stub

    }

}

The line beginning with // is where you're going to put your code for now. // tells the computer to ignore the rest of the line. We call this a comment. Comments can be useful to you or other programmers that may read your code, because they can assist with understanding what the code does. You should use comments to make notes to yourself within your code. Comment will not change how the program works, so you can add or remove them at will. Java also treats everything between /** and */ as a comment, and it even runs between different lines.
To run a program in the Eclipse IDE, simply click the Run
button as shown, or press Alt+Shift+X and then press J.

Replace the line that says "// TODO Auto-generated method stub" with this:
        System.out.print("Hello world!");

Now, run the program. (Refer to the image to the right.)

It might ask you to save your file, and then will quickly run and put the text "Hello world!" in the console pane at the bottom of the Eclipse window. We will be using console output to display the results of our programs for most of this tutorial, as graphics can be much more difficult to set up and debug. (Don't worry, we'll explain graphical programs eventually, just not right now.) You've just written your first program! It's a very simple program, to be sure, but it's also an important step.

Now to explain what we've done. System.out.print() is a very useful method that we can use to send a bit of text to the console. Simply put what you want to display between the parenthesis, enclosed in quotes. There's also a similar method called System.out.println() that does almost the same thing, but it starts a new line of text in the console after it's done. Lastly, the semicolon at the end of the line is necessary to end the statement. Java programs consist of statements, and each statement requires a semicolon at the end of the line to end it.


End of Lesson Quiz

1. What does // do, and why is it useful?

[Show Answer]



2. Write code to put "This is console output." into the console.

[Show Answer]



3. The following code has an error. Copy the code into a program shell and run it. Fix the error.
System.out.println(This code doesn't work at all!);

[Show Answer]



4. The following code has an error. Copy the code into a program shell and run it. Fix the error.
System.out.print("Hello, ");
System.out.print("my name is Espoire!")

[Show Answer]



Next Lesson: Primitive Data Types

No comments:

Post a Comment