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.
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.
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 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.
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.
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:
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.
If it's not already running, run Notepad++.
In the File menu, select New.
You should see something similar to the image below:
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.
Before you can do anything else, you should save your source file that you just created.
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.
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.
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.
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.
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 }
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:
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!
System.out.println("Hello, World!");
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.
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.
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):
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:
There are several ways to run a class/program in IntelliJ IDEA:
You'll see the output and results of your run in the Run window at the bottom of the screen.
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.
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.
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.
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?
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!
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.
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:\JavaTry this program (the instructions are in the 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."); } }
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 /*.
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.