“chapter 6: small java programs” bradley kjell (revised 6 ...source url: url: saylor url:

26
Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 1 of 26 “Chapter 6: Small Java Programs” Bradley Kjell (Revised 6/21/2010) Chapter Topics: Small example programs Names for source files and class files Syntax errors Bugs The Edit, Compile, and Run cycle Matching braces Neat indenting The previous chapter discussed the mechanics of creating and running a Java program. This chapter is an overview of Java using the example program from that chapter. QUESTION 1: (Review:) What role in Java programming does each of the following files play? Source code file Bytecode file

Upload: others

Post on 26-Feb-2020

9 views

Category:

Documents


0 download

TRANSCRIPT

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 1 of 26

“Chapter 6: Small Java Programs” Bradley Kjell (Revised 6/21/2010)

Chapter Topics:

• Small example programs • Names for source files and class files • Syntax errors • Bugs • The Edit, Compile, and Run cycle • Matching braces • Neat indenting

The previous chapter discussed the mechanics of creating and running a Java program. This chapter is an overview of Java using the example program from that chapter. QUESTION 1: (Review:) What role in Java programming does each of the following files play?

• Source code file • Bytecode file

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 2 of 26

Answer: • Source code file:

o a text file in the Java language created by a programmer with a text editor • Bytecode file:

o a file of machine language for the Java virtual machine created by a Java compiler

Example Source Program

Above is the source program (source file) from the previous chapter. The purpose of this program is to type the characters Hello World! on the monitor. The file must be named Hello.java to match the name of the class. On most computer systems, the upper and lower case characters of the file name are important. (So if the file is named hello.java with a small h it will not work). On all computers, upper and lower case inside the program are important. The first line

class  Hello   says that this source program defines a class called Hello. A class is a section of a program. (A better definition will come later on in these notes.) Small programs often consist of just one class. When the program is compiled, the compiler will make a file of bytecodes called Hello.class. QUESTION 2: Here is the first line of another Java program:

class  AddUpNumbers  

1. What should the source file be named? 2. What is the name of the bytecode file the compiler creates?

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 3 of 26

Answer: • What should the source file be named?

o AddUpNumbers.java • What is the name of the bytecode file the compiler creates?

o AddUpNumbers.class Identifiers and Reserved Words

Most classes contain many more lines than this one. Everything that makes up a class is placed between the first brace { and its matching last brace } . The name of the class (and therefore the name of the file) is up to you. In programming, the name for something like a class is called an identifier. An identifier consists of alphabetical characters and digits. The first character must be alphabetical, the remaining characters can be mixed alphabetic characters and digits (plus the two characters '_' and '$' underscore and dollar sign). No spaces are allowed inside the name. Chapter nine discusses this in more detail. Usually a class name starts with a capital letter, but this is not required. A source file should always end with .java  in lower case. A reserved word is a word like class that has a special meaning to the system. For example, class  means that a definition of a class immediately follows. You must use reserved words only for their intended purpose. (For example, you can't use the word class for any other purpose than defining a class.) QUESTION 3: Which of the following look like good identifiers? 1. ExcitingGame 2. Lady Luck 3. x32 4. lastChance 5. x/y

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 4 of 26

Answer: 1. ExcitingGame OK: mixed upper and lower case is allowed 2. Lady Luck BAD: no spaces allowed inside an identifier 3. x32 OK: identifiers must start with an alphabetical character, but the rest

can be digits. 4. lastChance OK: class names usually start with a capital, but identifiers

don't have to. 5. x/y BAD: the slash is not allowed inside an identifier

Between the Braces

The small Java programs in this chapter all look like this:

class  Hello  {  }  

Everything that a program does is described between the first brace and the final brace of a class. To start with, we will have only one class per source code file, but in later chapters there may be several classes per source code file. The example program writes Hello World! to the monitor. It looks like a lot of program for such a little task! But, usually, programs are much longer and the details you see here help to keep them organized. The line

public  static  void  main  (  String[]  args  )   shows where the program starts running. The word main means that this is the main method — where the Java virtual machine starts running the program. The main method must start with this line, and all of its parts must be present. Wherever there is one space it is OK to have any number of spaces. The spaces surrounding the

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 5 of 26

parentheses in the third line are not required. The fifth line shows parentheses not surrounded by spaces (but you could put them in). QUESTION 4: Is the following acceptable?

public        static  void  main(String[]    args  )      

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 6 of 26

Answer: public        static  void  main(String[]    args  )  

The Java compiler would accept the line. But it looks sloppy to human eyes. println()  

There are rules about where spaces may be used, and optional style rules about how to make a program look nice. Rather than look at a list of rules, look at some Java programs and pick up the rules by example. The main method of this program consists of a single statement:

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

This statement writes the characters inside the quotation marks to the monitor of the computer system. (The quotation marks are not written.) A statement in a programming language is a command for the computer to do something. It is like a sentence of the language. A statement in Java is followed by a semicolon. Methods are built out of statements. The statements in a method are placed between braces  { and  }  as in this example. The part "Hello  World!" is called a string. A string is a sequence of characters. This program writes a string to the monitor and then stops. QUESTION 5: (Review: ) Say that the file Hello.java contains the example program. The file is contained in the subdirectory C:\Temp on the hard disk. In order to run it, what two things must be done?

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 7 of 26

Answer: (1) The program must be compiled into bytecode with the Java compiler, then (2) run using the Java interpreter. Review of Running a Java Program Copy and paste the example program into a text editor (like Notepad or Crimson), and then save it to a file called Hello.java in the current directory. (Microsoft calls "directories" by the name "folders".) To run the program, check that the default directory of the command interpreter contains the source file. Do this by using the command DIR  *.java  to list the files in the directory. One of the files should be Hello.java. To see all the files, just type the command DIR.

If you don't see the source file, use the Change Directory command CD to get to the correct subdirectory. To compile the source file (thereby producing a file of bytecodes) enter the command javac  Hello.java. Finally, to run it, enter the command java  Hello.

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 8 of 26

QUESTION 6: ▪ What is the command that runs the Java compiler? ▪ What is the command that runs the Java interpreter?

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 9 of 26

Answer: • What is the command that runs the Java compiler?

o javac • What is the command that runs the Java interpreter?

o Java Syntax Errors It is likely that you will do something wrong. Here is the sample program with a deliberate error:

QUESTION 7: What is the error? (Don't spend much time looking; it is really small.)

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 10 of 26

Answer: The reserved word "class" has been changed to "Class" with a capital "C". A Capital Mistake The reserved word "class" has been changed to "Class" with a capital "C". This is called a syntax error. A syntax error is a "grammatical error" in using the programming language. Here is what happens when the mistaken program is compiled: The compiler tried to translate the source code into bytecode but got confused when it got to a capital "C" it did not expect. The error message is not very clear. They never are. But at least it shows where the compiler got confused. The compiler did not create a new bytecode file because it stopped translating when it got to the error.

QUESTION 8: To fix this error and run the program what must you do?

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 11 of 26

Answer: To fix the error, use a text editor to fix the source file. Fixing Errors

Usually you will have two windows open on your computer: one for a text editor (such as Notepad or Crimson) and one for the command interpreter. To fix the syntax error, change the "C" to a "c" and save the file. Now use javac  to compile the source file, and if there are no errors, use java to run it. QUESTION 9: If you forget to save the file after making the change, and then enter the command javac  Hello.java, what will happen?

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 12 of 26

Answer: You would compile the old, uncorrected version of the source file on hard disk and get the same error message. When you use a text editor you change the source program that is in main memory. If you don't save your changes, the file on disk does not change. The compiler javac  uses the file that is currently on the hard disk. This is a common mistake. Edit, Compile, Run Cycle Until your program runs correctly:

1. Edit the program (the source file). 2. Save the program to the hard disk with the "Save" or "Save As" command of the

editor. 3. Compile the program with the javac command. 4. If there are syntax errors, go back to step 1. 5. Run the program with the java command. 6. If there are bugs, go back to step 1. 7. When it runs correctly, quit.

This is called the "edit-compile-and-run" cycle. Expect to go through it many times per program. A Java development environment like Eclipse or BlueJ is more sophisticated, but you still go through the same fundamental cycle. QUESTION 10: If a source program compiles correctly in step 3, does that mean that it will run correctly?

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 13 of 26

Answer: No. Bugs

Just because a program compiles and runs does not mean that it is correct. For example, say that your assignment is to create a program that writes "Hello World!" on the computer monitor. But you write the above program. When a program compiles without any syntax errors, but does not perform as expected when it runs, the program is said to have a bug. QUESTION 11: ▪ Will this program compile without syntax errors? ▪ Will this program run? ▪ Does the program meet the assignment?

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 14 of 26

Answer: • Will this program compile without syntax errors?

o Yes. • Will this program run?

o Yes. • Does the program meet the assignment?

o No — it has a bug. Longer Example Program

Usually bugs are much more difficult to find than the one in this program. The longer a program is, the more bugs it is likely to have, and the more difficult it is to find them. It is a good idea to practice with short programs where syntax errors and bugs are more easily seen before moving on to longer programs. Above is a somewhat longer example program. The program is much like the "Hello World!" program but the main method has more statements inside of it. Create this program with a text editor, compile and run it. Save the program in a file called Emily.java. The compiler will create a bytecode file called Emily.class. QUESTION 12: What does this program write to the monitor when it is run?

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 15 of 26

Answer: Each System.out.println  statement writes out the characters inside the quote marks:

A  bird  came  down  the  walk  He  did  not  know  I  saw;  He  bit  an  angle-­‐worm  in  halves  And  ate  the  fellow,  raw.  

 Another Example

Now say that your assignment is to create a program that writes the following to the computer monitor:

On  a  withered  branch  A  crow  has  just  alighted:  Nightfall  in  autumn.

Above is the program that is to perform this task, but with some blank boxes for you to fill in. The extra lines between program statements don't hurt. Blank lines often make a program easier to read. QUESTION 13: Fill in the blanks of the program.

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 16 of 26

Answer: The completed program is given below: Finished Program Here is the completed program. Be sure that you put the quote marks where they belong. If you forget just one of them, the compiler will become confused and will not translate your program!

If you have been creating the example programs and compiling and running them, you may have noticed that spaces and new lines in the program are not critical. (However, you can't put spaces in the middle of a word, and spaces inside the quote marks do matter.) For example, the following version of the program will compile correctly and will do exactly the same thing as the original version when it is run:

The compiler does not "see" the two dimensional layout of the program. It regards the program as a stream of characters, one following the other.

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 17 of 26

However, humans are sensitive to the layout of text, and it is important to be neat and consistent when you create a source file. Although the second version of the program runs correctly, it is much harder for a person to understand. QUESTION 14: If there were a slight mistake in the poorly laid-out program, would it be easy to find?

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 18 of 26

Answer: No. Everything is so confused, a slight mistake is easily overlooked. Comments

A comment is a note written to a human reader of a program. A comment starts with the two characters // (slash slash). Those characters and everything that follows them on that one line are ignored by the java compiler. The program compiles and runs exactly the same as before. The green color in the above program was added by hand. However, most program editors (such as Crimson and Notepad++) are smart enough to recognize comments and will display them in color. Of course, the text file contains only the characters you have entered. QUESTION 15: Are comments included in the bytecode translation of a Java program?

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 19 of 26

Answer: No. Remember, the compiler completely ignores them. Comments are just for humans. Many Comments

Comments can be placed after a program statement to explain what it does, as here. As with all comments, the // and everything after it on that line are ignored by the compiler. The program statement in the start of the line is not affected by the comment. QUESTION 16: Would you ever want to write an entire paragraph of comments?

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 20 of 26

Answer: Yes. Many-line Comments

Often you want to write a comment that spans several lines, as above. With this style of comment, everything between the two characters /* and the two chracters */  are ignored by the compiler. The  /  and the * must not have any character between them. There can be many lines of comments between the /* pair and the */ pair. The /* and the */  can start and stop anywhere on a line. Everything between the pair is a comment ignored by the compiler.

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 21 of 26

QUESTION 17: Is the following correct?

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 22 of 26

Answer: Yes, although it is ugly and not commonly done. Commenting Out Code

Comments are useful for debugging. For example, the above program has a syntax error. Let's say that you are having problems finding the error. One way to narrow down the problem is to remove some of the code from consideration by turning it into a comment. Compile and run the program. If the modified program works as expected, the error must be in the commented section. Gradually decrease the commented section until you find the error. QUESTION 18: Why would you ever want to use comments to help a person understand your program?

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 23 of 26

Answer: The person might be you. Comments are often notes to yourself about what something is, or why you did something the way you did. Braces

Examine the program. For every left brace

{ there is a right brace

} that matches. Usually there will be sets of matching braces inside other sets of matching braces. The first brace in a class (a left brace) will match the last brace in that class (a right brace). A brace can match just one other brace. Use indenting to show how the braces match (and thereby show the logic of the program). Look at the example. Increase the indenting by two spaces for statements inside a left and right brace. If another pair of braces is nested within those braces, increase the indenting for the statements they contain by another two spaces. Line up the braces vertically. There are many styles of laying out a program. If you are reading a printed text book in addition to these notes, it may use a different style. QUESTION 19: Mentally circle the matching braces in the above program.

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 24 of 26

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 25 of 26

Answer: The matching braces are indicated in color, below: Matching Pairs

Notice that in addition to pairs of braces that match, there are pairs of parentheses (), and pairs of brackets [] that match. Large programs will have many of these matching pairs, which are used to group sections of the program together. Format your program as you write it. This helps you see the logic you are creating, and is a tremendous help in programming. Text editors intended for program creation (called program editors) and more sophisticated programming environments always have ways to show matching braces. This is really valuable. You should definitely learn to use this feature with whatever editor or environment you are using. QUESTION 20: If a program is missing just one brace, will it compile?

Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 Source URL: http://chortle.ccsu.edu/java5/Notes/chap06/ch06_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.1.1 © Bradley Kjell Saylor.org Used by permission. Page 26 of 26

Answer: No. But if you have been neat, it is easy to find where the missing brace should go. End of the Chapter Brace yourself! you have reached the end of the chapter. You may wish to review the following. Click on a subject that interests you to go to where it was discussed.

• Hello World example program. • methods and classes. • Syntax Errors. • Edit, compile, and run cycle. • Program bugs. • Importance of spaces and newlines in programs. • Comments • Multiline Comments • Matching braces.

The next chapter will discuss a way to run the programs in these notes without actually typing them in, and discusses details of using Notepad.