Your First Java Programs

Things To Do Before Class

Things To Do After Class

Review

Read! The following terms may be helpful: source code, compile, JIT (Just in Time compiler), interpreter, byte code, machine language.

In the previous lesson you installed a recent version of Java, and you installed an editor called Notepad++. You then set up Notepad++ to allow you to compile and execute Java programs. If you followed through all of the notes and readings, you tested your environment with a test program.

You should have also read through sections 1.1 to 1.4 in your textbook and done all of the interactive practice exercises.

You also went through a brief introduction to programming and the Java language and should have a bit of an idea about what programming is, and perhaps even know the names of some other programming languages.

Introduction to Creating Programs

When you write code, you're generally using a high-level language. Java is a high-level language, and so are languages like Python, C/C++, Ruby, and Turing. High-level languages are English-like and can be read by other programmers.

Prior to the invention of high-level languages, developers had to code in lower-level languages. For example, in the beginning, we only had machine language. Machine language is basically just binary code, or a series of 1's and 0's, or even hexadecimal code (digits from 0 to 9, along with the letters from A to F). A machine language is the native language of a particular platform. A platform consists of the combination of an operating system and hardware. For example, the PC platform is a combination of an IBM-type PC configuration with Microsoft Windows installed. The Mac platform is an Apple-type computer configuration with Mac OS installed. The machine language for a PC machine is different from the machine language for a Mac machine. If you wanted to write a program that worked for both Mac and PC, you would have to write it in two different machine languages.

Eventually, assembly languages were developed to help make programming easier. Assembly consisted of abbreviations for specific types of operations (such as ADD for addition or MOV to move data from one memory location to another). This was still very low-level programming: a command to add two numbers involved several statements to move and copy digits to and from memory registers (locations in memory). Assembly was not like machine language in that it was similar between different platforms, however a machine did not "speak" assembly so it couldn't run assembly programs. Instead, the developer would have to take their finished assembly code and assemble the code into machine code using an Assembler program. This machine code could then be read and executed by the platform on which the code was compiled. For example, if you compiled the code on a PC, it would only run on a PC, and if you compiled the code on a Mac, it would only run on a Mac. Even though you still had to compile a program for different platforms, it was still much easier than writing the program more than once in different machine languages.

a flow chart showing Assembly Code
                         pointing to a box that says Assembler, which points to Machine Code
Assembly code is written by the developer. The developer then uses an Assembler program to convert the Assembly code into Machine Code (machine language)
.model small
.data
 opr1 dw 1234h
 opr2 dw 0002h
 result dw 01 dup(?),\'$\'
.code
        mov ax,@data
        mov ds,ax
        mov ax,opr1
        mov bx,opr2
        clc
        add ax,bx
        mov di,offset result
        mov [di], ax

        mov ah,09h
        mov dx,offset result
        int 21h

        mov ah,4ch
        int 21h
        end
Some sample Assembly code that adds 2 numbers together.

You can clearly understand now how high-level languages are much easier to read and learn! However, high-level language code is also not understood by a machine - remember, a machine only understands machine code. Therefore, there needs to be a way to convert your high-level source code that you write into machine language. This is the job of the compiler.

A compiler is a special program that reads in source code and converts it into machine code/language. There are hundreds of languages you could program with, so each language has to come with its own set of compilers. As with Assembly, the compiler only translates source code into a specific kind of machine code. So if you compile a program on a PC, it will only run on a PC and you'd have to use different compilers to make a version that runs on Mac, Linux, etc.

a flow chart showing Source Code
                         pointing to a box that says Compiler, which points to Machine Code
A developer writes source code, which then needs to be compiled into Machine Code (machine language) using a Compiler program.

A compiler does more than translates source code into machine language. It also checks your code's syntax. Syntax refers to the grammar and spelling of the programming language. For example, it ensures you have all the right punctuation and symbols and that you haven't spelled any words wrong. If you have any syntax errors in your code, the compiler will list them all for you, and it will not compile the source code into machine code. You then have to fix your syntax errors and try the compiler again. You repeat this process until the compiler finds no syntax errors, in which case it will translate your source code into machine language.

Larger and more complex programs also use a program called a linker that allows the developer to add other libraries to their program. A library is a collection of code that is already written and can be used in any other program. For example, if you want your program to use a credit card validation service that someone else wrote, you obtain that library and add it to your program. This is often done with programs that use operating system components, such as the standard set of file open/save dialog boxes. The linker takes the library (or libraries) and adds them to the machine code for your program and creates an executable file that can be run on the computer.

a flow chart showing Source Code
                         pointing to a box that says Compiler, which points to Machine Code,
                         and then both machine code and a box that says Libraries e.g. .DLL both
                         point to a box that says Linker, Linker points to Executable
A developer writes source code, which then needs to be compiled into Machine Code (machine language) using a Compiler program. The developer can then add existing libraries to the program using a Linker, which creates an executable.

So how does this work for Java? One of the features you learned about Java in the previous lesson is that it's platform independent. This means it can run on any platform, regardless of where it was compiled! How does this work?

Java source code is written and compiled just like a regular language, except that it isn't compiled into machine code: it's compiled into bytecode. Bytecode is "not quite machine code" - it can be run on any machine, as long as that machine has an interpreter. An interpreter takes a line of bytecode, interprets it into machine code, and then executes that machine code. Then it reads and interprets the next line of bytecode and executes it, then the next, etc until it either runs out of bytecode (your program has finished) or a run-time error occurs (you'll learn more about runtime errors later in the course). A run-time error causes the program to stop working, or "crash".

How does this work on different platforms? An interpreter is part of a computer's Java Virtual Machine or JVM. A JVM is needed on any machine that wants to run Java programs. So if you write and compile a Java program on a Linux machine, you can then run that program on a PC as long as that PC has a JVM. The JVM's interpreter can read the bytecode and interpret it into the PC's native machine language.

a flow chart showing Java Source 
                         Code .JAVA compiled by the Java compiler into Java Bytecode .CLASS
                         which then goes through a Java Interpreter, which shows output
                         Hello, World! on a computer screen
Java source code is compiled into Java bytecode, which is then executed using an interpreter program.

This is why Java is often called and interpreted language: because the bytecode is interpreted as it's executed rather than a compiled language, where all the code is compiled into one big block of machine language and then executed. Think of an interpreted language like an interpreter that is listening to someone speak and interpreting that language into another language as it's being spoken (similar to what you often see at international news conferences or when someone is interpreting sign language for someone else). A compiled language would be similar to someone listening to the whole speech and recording it, and then sitting down and interpreting the entire speech and then reciting it in a different language, and giving you that audio file so you can listen to the interpreted version.

When you write Java source code, this code is saved in a file with the .java file extension. That is then compiled by the compiler program javac.exe (which is in your Java/JDK/bin folder, although you created a macro to that in Notepad++ to make things easier).

We write or code Java source code in an editor or an IDE (Integrated Development Environment). In this beginner course, we will use very simple editors, (either Notepad++ or IntelliJ IDEA, depending on what version of Java you're using).

A successful compilation creates a bytecode file with the same name as your source code file, except it has the .class extension instead of .java. You then execute the bytecode file using the java.exe interpreter program (also in your Java/JDK/bin folder, and for which you also set up a macro in Notepad++).

With all of this in mind, we can summarize the creation of a java application into these steps:

  1. Type the source code in an editor (such as Notepad++ or IntelliJ).
  2. Compile the source code into a class file using the Java compiler.
  3. If you are notified of any syntax errors, fix them and repeat step 2.
  4. Run the Java class file using the Java interpreter.

Writing your First Program

Everything you write in Java must be part of a class. A class is like a building block or a Lego brick: you can use classes to build larger programs just as you can use blocks/bricks to create larger things like a ship or a castle. Just as there are many types of blocks or Lego bricks to use for your creations, there are already hundreds of classes available with the Java language. Programmers use these classes to build their own, more complex classes. Then we use those classes to build even larger, more complex applications. You might use some blocks or bricks to create the Hogwarts Castle, and then use another set of blocks or bricks to build the Forbidden Forest. Then you could use your Hogwarts Castle and Forbidden Forest builds along with other builds to create the entire world of Harry Potter! We do the same thing with Java classes: We build things, and then use those things to build bigger things!

In this course, we will start off by writing simple programs that are contained in a single class file. Later we will move on to object-oriented programs, which use more than one class file. When we create a basic program in Java, it's defined as a class. Everything you create in Java is part of a class. When you learn object-oriented programming, you will create classes that model or represent real-life objects. For now, the classes we are writing are main classes or hollow classes. This means that these classes are programs, and not classes that define objects in an object-oriented program.

Try your first program in your chosen editor/IDE:

Important!
These instructions assume you've gone through all of the Installation and Setup Instructions, including setting up macro items in Notepad++ to compile and execute Java programs.

If it's not already running, run Notepad++.

In the File menu, select New.

You should see something similar to the image below:

notepad++ screen with a blank tab open
A new program in Notepad++: my example says "new 3" but yours probably says "new 1"

Each new file you create is displayed in its own tab, so you can have several files open at once. Each tab will display the file name, except for new, unsaved files which will just say "new x" where "x" is a sequential number. Yours probably says "new 1" but notice in the screen shot mine says "new 3" because before I took this screen shot, I created 2 other new files before this one (I use Notepad++ for lots of other things besides Java).

On the first line, type "public class MyFirstProgram {".

Press enter a few times to add a couple of blank lines.

We need to close our block of code that defines/contains our program, so add a closing brace ( } ) on line 4.

Saving your File

Before you can do anything else, you should save your source file that you just created.

  • A Java program's source code file must have the same name as its class. Therefore, in this example, you must call your file "MyFirstProgram.java". Click the Save button (the third button on the button bar) or choose Save from the File menu.
    • Make sure you save your file in the folder for today's session in the prog10082 folder. DO NOT simply store all your Java programs in one folder!
    • In Notepad++, you must make sure you include the .java file extension, otherwise you won't get syntax highlighting.
  • If you like, you can use your preferred file manager to browse to your programs folder and see that your MyFirstProgram.java file is there.

Staring a new Project in IntelliJ IDEA

When you use an IDE like IntelliJ, you're working with a project rather than a single file. The difference is a bit difficult to get into if you've never programmed before, but think of a Java project as the set of files that make up the application, which might also include data files and images. A project-based IDE like IntelliJ makes it easier to manage the many files that make up a single project.

Each project you create goes inside its own directory/folder. For example, if you create a project called "MyFirstProject", and you store it in your prog10082/projects folder, your project files will be located in the directory prog10082/projects/MyFirstProject directory.

If you don't already have one open, create a new project. If you can't recall how, you can review your notes from the lesson where you installed IntelliJ.

When you first encounter a new project in IntelliJ IDEA, you'll see an empty area of the screen and a Projects Window on the left side (if you don't see the projects window, it's probably collapsed. You should see a little sideways tab on the left side below the menu bars that says "Projects" - click that to expand the projects window. If you don't see any of those things, go to the View menu and choose Tool Windows > Project.

open the projects window
If the Projects Window isn't open, click its tab or press Alt-1 on your keyboard.
the projects window
The Projects Window is on the left of the screen.

In the projects window, you'll see nodes representing the structure of your project. This is the logical structure of your project, not necessarily the physical structure of your project (the phyisical structure are the actual files and directories, but the logical structure shows how your project components are related to each other).

Inside your project, you'll see a node called "src". "src" is short for "source" or "source code". In the SRC node is where all of the .java files will go (the ones that you write yourself).

Once you create your first class and run it, you'll see another node appear, and we'll go over that later.

To start programming, we need to add a new class to our project. Right-click on the SRC node and select New > Java Class.

A dialog appears asking you for the name of your class.

enter the name of your class
Entering the name and type of class you want to create.

The name of the class is both the actual file name, and also the name of this particular building block (you'll see it appear later in the class header). The name of your class has to follow certain rules that we'll look at later. For now, type in "MyFirstProgram" (without the quotes).

The type of class for now should just be set to "Class". We'll learn about other types of building blocks in your second semester course (but if you're curious and want to look ahead, feel free to examine the other options and do a web search for those terms!)

Once you've typed in the MyFirstProgram class name and made sure "Class" is selected, press the OK button.

You should now see a file open in the main editor window of your screen. You should also notice that, in your Projects window, a MyFirstProgram node has been added to your SRC node.

we've created a new class
You should see the new source code file open in your editor window, and see it's entry in the SRC node of the Projects window.

Important: File Names and Renaming Classes

If you go and look at the actual files in your project, you'll notice that you now have a file called MyFirstProgram.java. A Java program's source code file must have the same name as its class. It must match upper- and lower-case letters and not have any extra spaces. If they're not exactly the same, the program won't work.

Luckily, IntelliJ handles this for you, but keep in mind that if you ever rename a class, you must make sure the file name is also changed. In IntelliJ, you can easily do this by right-clicking your class and selecting Refactor > Rename. Then enter the new name and press the REFACTOR button.

Spacing

In a few lessons we'll learn about spacing and indentation. Make sure you add a few blank lines between the opening brace { and closing brace }

Examining the Class Header

What is the block of code public class MyFirstProgram {} that we now have in our new file? Let's examine each piece in detail. Don't worry if you don't grasp everything right away: some of these things will take a few weeks to fully understand, especially if you've never programmed before.

We now have the framework for a Java program. All of your programs for this course are going to start in pretty much the same way, you'll just give them different class names each time.

Now, let's add some code that actually does something!

Every program must have a starting point. In Java, the starting point of any program is the main() method. A "method" is a block of code that performs a task. The word "main" is the special name for the Java method that starts a program, so almost all of your programs in this course will have the main() method. Notice that when I type "main() method", I put empty brackets/parentheses after the word "main". This is how you know I'm referring to a method and not something else like a program name or a variable name.

The main() method always looks the same in every program. It looks like this:

public static void main(String[] args) {
    // code that executes goes here
}

Notice that it has its own set of matching braces. This is another block of code. Everything that your main() method does will be contained inside those braces. Also notice there are a lot more of those Java keywords in that main() method header, such as "public", "static", and "void", plus this funny thing "String[] args" inside the parentheses. You'll learn a little bit about what all those things mean later, and we'll explore them in more detail as we go through the course. Don't worry if they don't all make sense today, they don't have to. Just make sure you memorize the main() method header for now (it helps to type it out every single time you make a new program).

Add the main() method to your program. It should go inside the class block, between lines 1 and 4. Also, anything inside a block should always be indented with one tab. This means that when you're done, your screen should look similar to the image below:

the first program with the empty main() method in the
                             Notepad++ editor, there are line numbers along the left side
A class, with a main() method. Your editor/IDE might look slightly different, but the code should look the same meaning the words and symbols; the colours might be different). This class doesn't do anything, yet.

So now we have a program called MyFirstProgram, and our program has a main() method to start with. Now we should put some code in the main() method that actually does something!

Whenever you learn a new language, the first thing you're taught is how to make a program that says "Hello, World!" so let's do that!

  1. Go to the blank space in your code inside the main() method, between the main() method's opening and closing braces, which defines the main() method block.
  2. Your cursor should be indented inside the main() method block. Most editors/IDEs usually add the correct indent for you, so press the END key on your keyboard and it should put the cursor where it belongs. If it doesn't, just use TAB to indent one level inside the main() method block.
  3. Type the following statement to display "Hello, World!" on the screen:
    System.out.println("Hello, World!");
    • Remember that Java is case sensitive, so be sure to use an upper-case "S" on the word "System".
    • System.out refers to your system's default output device, which is always your monitor/screen.
    • println() is another method that is part of the Java language. It accepts an argument inside the brackets. It will display that argument on System.out (your monitor/screen).
    • "Hello, World!" has to be inside double-quotes. We call this a literal. This means that we literally want the exact value Hello, World! sent to the println() method.
  4. Now you have a working program! It should look like the one below:
    the first program we've been working on with the
                                     print line (println) statement added inside the main method block;
                                     important for later: the tab's icon is red instead of the normal blue,
                                     and the title bar, which shows the absolute path to the file you're 
                                     editing, contains an asterisk * in front of the file path
    The finished program. Your editor/IDE might look a bit different.
  5. We can now save the program, and then compile it and run it!

    If you haven't already, save your program. You can tell if you need to save your program because the icon in the file's tab will be red instead of blue, and the title bar will include an asterisk * in front of the file path/name. You can see this in the previous image.

    Compile the program by using the Compile Java macro you created when you installed and setup Java and Notepad++: go to the Macro menu and select "Compile Java" or use the shortcut Ctrl_Shift_C. You whould see a screen similar to that shown in the image below.

    the console window has opened in the bottom
                                         half of the screen and shows successful compiliation as process finished
                                         exit code 0 - the exact text can be found in the installation/setup notes
                                         where you tested your new macros
    Compiling a source code file.

    IntelliJ is a bit more advanced. It actually checks the code for syntax errors as you type. When you make an error, it will mark it with red squiggly underlines and margin markers.

    there are several indications of an
                                         error in your code as described in the figure caption
    There are several indications of an error in your code: the class node and project node have read underlines, there is a red mark where the missing semi-colon should be, an error marker in the right-margin (which you can hover over to see the error message), etc.

    Even so, you should still BUILD your application to catch other errors that might not appear automatically. "Build" is just another word for compile. Building or compiling your source code (.java) creates the bytecode file (.class):

    • Under the menu bar, locate the button with the little green hammer (the BUILD button) and click it. Watch the status bar at the bottom of the screen: it will tell you when it's finished building. This builds/compiles your class and creates the bytecode file.
    • You'll now notice an extra node in your project window called "out". If you expand this, you'll see a few more sub-nodes, and eventually all the way down you'll see your MyFirstProgram.class file.
  6. If you get any errors, go back to your source code and fix any problems, then try to compile again.

Once you successfully compile a program with no errors, you can run it:

Run the program by using the Macro > Execute Java menu option or the shortcut Ctrl-Shift-E.

In the bottom of the editor window, you should see your program's output, just like the example below:

output in console window of a successful execution,
                                 exact text can be seen in the installation notes when you set up the
                                 macros; the output Hello, World! is included
Successfully running a Java program

There are several ways to run a class/program in IntelliJ IDEA:

  • Right-click the class node in your SRC node and select "Run MyFirstProgram.main().
  • On the left margin of the editor window is an area called the "gutter". In the gutter, you'll see tiny green arrows at the class header and main() method header. Clicking either of those and selecting "Run MyFirstProgram.main() will run your program.
  • If the green RUN button in the button bar is enabled, you can click that to run your program.
different ways to run a program
                                 as described in the caption
There are several ways to run your program. If you prefer keyboard shortcuts, use Ctrl-Shift-F10 or Shift-F10. You might also have to hold down the FN (function) key if you're on a laptop.

You'll see the output and results of your run in the Run window at the bottom of the screen.

results of running a program -
                                 shows the code and the successful run message
Successfully running a Java program
Important!
When your compile is successful, a bytecode file is created. Recall from a previous lesson that this is the file you can run using the Java interpreter. A bytecode file has a .class extension.

Browse to your programs folder where your source code is saved, and you'll see that you now also have a MyFirstProgram.class file.

When you make changes to a program, it must be re-compiled! Your bytecode file is the previous version, so when you make changes to your source code, you must recompile it so that the bytecode file also contains those changes.

Note

Things you need to remember:

  • The name of the class file must match the name of the class used in the source code. For example, if you're source code begins with the statement class MyFirstProgam { then your Java source file must be called MyFirstProgram.java. Even MyFirstProgram.java would not work because the capitalization doesn't match.
  • You should store your course work in folders for each course. For this class you should have a folder called PROG10082. You should keep your Java programs organized to they're easy to find later. I recommend having a folder for each session, so today's programs would go in the PROG10082/sessionW-C folder, where W is the week number and C is the class number (e.g. Session 2.1).
  • Once you compile your source code successfully, a bytecode file is created. This file has a .CLASS extension. If you compile your source code and it contains syntax errors, the bytecode file will not be created. You will need to examine your source code, find and fix the errors, and then recompile your program.

In your textbook, examine Figure 1.6 on page 16 and Figure 1.8 on page 17. These demonstrate the process of creating source code, compiling, fixing syntax errors, and running a bytecode file.

Now let's examine this program piece by piece (it helps to read Chapter 1.7 first, if you haven't already done so):

public class MyFirstProgram {

    public static void main(String[] args) {

        System.out.println("Hello, World!");
    }
}

Line 5 is a print statement. The words "System.out" are referring to the console or screen on your computer. "println()" (pronounced "print line") is a method. As mentioned previously, methods are blocks of code that perform a task. The println() method will print something, but you have to tell it what to print. To give it a value to print or display, you place that value inside the brackets; in this case we've given println() the value "Hello World!". We say that "Hello World!" is an argument. Many methods require arguments, but not all do.

The println() method can work with the screen, files, and other output destinations. By using the syntax "System.out.println()", we are invoking the println() method on the System.out object. We already mentioned that System.out is referring to the console screen, so in this example, println() is being invoked or executed on the console screen.

The statement on line 5 ends with a semi-colon (;) character. All executing statements in Java must end with such a line terminator. This is how the compiler knows where the end of the statement is. Java doesn't care about whitespace. If you wanted, you could write:

public class  MyFirstProgram{ public static 
void main(String[] args){	System.out.println("Hello World!");}}

or you could write:

public class  MyFirstProgram
{
  public static void main(String[] args) 
  {
    System
    .out.
    println
    ("Hello World!")
    ;
  }
}

Neither version is appropriate, professional, or acceptable in most programming environments, but both will compile and run just fine. In the second example, the print statement takes up 5 lines, but Java knows where it ends because of the semi-colon.

Note

Code Listing 1.1 on page 11 of your textbook has a program similar to the one we just worked on. In Listing 1.1, Line 3 shows a line comment. A line comment is a statement that is ignored by the compiler. Programmers use comments to document their code: what the program is doing, what a certain set of statements are for, who wrote and modified the program, when it was written, etc. You'll learn more about comments and documentation later in this session, and in Chapter 1.7.

Modifying Your Program

Let's try some other kinds of print statements:

Change the literal value "Hello, World!" inside the println statement in line 5 to "Java is fun.":

public class MyFirstProgram {

    public static void main(String[] args) {

        System.out.println("Java is fun.");
    }
}

What do you think the output will be? Save this program and try running it using the java command. What output do you actually get for output?

Important!
When you make changes to your source code, remember to save the file. Then, you must recompile your code!! Otherwise, the class file (the bytecode that will be interpreted and executed) will not contain your changes! Use a tool such as My Computer to browse to the folder for today's session and check the times on the class file before you compile, then check again after. You'll notice that the class file has been updated.

What happens if you delete the semi-colon from the end of the println() statement? What do you see when you compile the program?

Every executable statement in Java must end with a semi-colon! This is because Java doesn't pay attention to whitespace: you can type a statement over multiple lines, so you need to tell Java when the statement ends by using the semi-colon.

Try each one of these print statements - replace your current println statement with each of these, one at a time:
System.out.println("123");
System.out.println(123);
System.out.println(2 + 3);
System.out.println("2" + "3");

What happens if you change the println statement to
System.out.println(hello);
and then compile the program?

Be sure that if you want to print a String, that you enclose it in double-quotes!

Important!

Literals
Literals are actual values in your code. For example, the values "Hello, World!", 123, "123", 2, and "2" are all literals.

Numeric Literals are numberic values in your code. String Literals are values that are enclosed inside the double-quotes (e.g. "Hello, World!"). Even if the string literal contains numbers, it's still a string literal, because the value is enclosed in double-quotes.

Try this:

Edit your println statements: use the print() method instead of println(). For example:

public class MyFirstProgram {

    public static void main(String[] args) {

        System.out.print("Hello");
        System.out.print("World");
    }
}

What is the difference between the println() method and the print() method?

What do you think would be the output of the following program:

public class MyFirstProgram {

    public static void main(String[] args) {

        System.out.print("Unga");
        System.out.println("Bunga");
        System.out.print("Meow");
	}
}

Try it and see!

Delete lines 5 to 7 (the three print statements) and add a single println() statement that prints the string "Hello\nWorld\nSup?"

public class MyFirstProgram {

    public static void main(String[] args) {

        System.out.print("Hello\nWorld\nSup?");
	}
}

What is the \n for? This is called an escape sequence, and is mentioned in Table 2.6 on page 64 of your text.

How would you display the following:

Hello, my name is "Sydney"! Your current path is d:\Java

Exercise

Try this program (the instructions are in the code).

Documenting your Code

One last piece of the puzzle is your program comments or program documentation. No matter how experiences a programmer you are, it can be difficult to read pages of code, whether you wrote them yourself or not. Programmers make their programs more readable by adding comments to their code. Comments describe what a statement or group of statements is doing; it also allows coders to leave notes or reminders to themselves or other programmers about what possible bugs might exist in the code or what pieces of the code need to be finished or modified. Each language has its own way of writing comments. In Java, there are two ways to add comments to your code.

Single-line comments start with the // characters (two forward slashes). The double-slashes tell the Java compiler to ignore everything between the slashes and the end of the line on which the slashes appear. For example:

public class MyFirstProgram {

    public static void main(String[] args) {

        // this is a comment
        System.out.println("I love commenting code.");
	}
}

The compiler will ignore line 5, but it will process line 6 normally.

Single-line comments can also appear at the end of the line:

public class MyFirstProgram {

    public static void main(String[] args) {

        System.out.println("Sydney");  // that's one of my cats
        System.out.println("Arti");    // that's another one of my cats
	}
}

In the above example, the println() statements on line 5 and 6 will be processed normally. Everything after the double-slashes is ignored until the end-of-line is reached.

Note that the println() in the next example will not execute because it is after the double-slashes on the same line:

public class MyFirstProgram {

    public static void main(String[] args) {

        // print something			System.out.println("This won't print.");
	}
}

The second style of commenting are multi-line comments. Multi-line comments are useful when you want to write comments that take up more than one line. To write multi-line comments, you start the comment with the /* characters, write your lines of comments, and then close the comments with the */ characters. For example:

public class MyFirstProgram {

    public static void main(String[] args) {

        /*  
         This is a long comment that takes up
         multiple lines.  If this was a real program, this would be
         a great way to describe a complicated chunk of code.
         Unfortunately it's just an example, so I have nothing
         much else interesting to say.
        */
        System.out.println("Java is fun.");
	}
}

Of course, you can also make multiple lines of comments by using double-slashes. The following is equivalent to the example above:

public class MyFirstProgram {

    public static void main(String[] args) {

        // This is a long comment that takes up
        // multiple lines.  If this was a real program, this would be
        // a great way to describe a complicated chunk of code.
        // Unfortunately it's just an example, so I have nothing
        // much else interesting to say.
        System.out.println("Java is fun.");
	}
}
Important!
Industry standards for Java state that you must always place a blank line above a single-line comment or multi-line comment block.

Whether you use many lines with // or you use the /* ... */ characters for multi-line comments is a matter of preference. Some find it easier to type // many times than to type /* and /*.

Exercises

For practice, try Programming Exercise From the Book (the last item in Chapter 1) 1.3 to 1.6. If you need more practice, you can also try 1.7 to 1.10 (advanced students should try 1.11 to 1.13).

More Practice questions:

1. Create a program that displays a list of your three favourite foods, one food per line. Example:

Sydney's Favourite Foods:
Chicken
Deli Turkey
Scrambled Eggs

2. What is the minimum number of statements you could use in the main() method to produce the output from question 1?

3. Create a program called Tree that creates the following output:
   *
  ***
 *****
*******
   #
   #

Challenge Exercise: If you're not new to programming, try this exercise!

Create a "Mad-Lib". A Mad-Lib is where you ask someone for a series of different words, and then you create a story out of them. When I was a kid, my sister and I would play these all the time, and sometimes we'd use made-up stories or existing stories (We didn't have video games back then, and there weren't many TV channels. In those days, kids generally played by doing creative activities or playing outside.)

For example, here is some sample program interaction with user inputs:

An animal: cat
A colour: purple
Something that is purple: plums
An action or verb: write Java code

In this example, the user entered "cat", then "purple", then "plums", and then "write Java code". Notice the 3rd prompt used the user's second input!

Here is an example of the output my version of the program produces:

Mary had a little cat,
It's fleece as purple as plums,
And everywhere that Mary went,
The cat was sure to write Java code.

That's a mad-lib! Your program can ask for as many inputs as you think you need, for whatever story you like. You can make up a story or use an existing story (or a nursery rhyme like I used), or even song lyrics. Have fun with it.

[solutions]