Small Java Programs

Site: Saylor Academy
Course: CS101: Introduction to Computer Science I (2019.A.01)
Book: Small Java Programs
Printed by: Guest user
Date: Monday, September 25, 2023, 1:56 AM

Description

This chapter discusses naming and coding conventions as well as reserved words in Java. When you go through this chapter, you'll get some hands-on experience with writing in Java.

1. Small Java Programs

The previous chapter discussed the mechanics of creating and running a Java program. This chapter is an overview of Java using the previous example program.

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


Question 1:

(Review:) What is the role of each of the following files?

  • Source code file
  • Bytecode file


Source: Bradley Kjell, http://programmedlessons.org/Java9/chap06/ch06_01.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 3.0 License.

2. Example Source Program


Answer:

  • Source code file:
    • a text file created by a programmer that contains a Java program
  • Bytecode file:
    • a file created by a Java compiler that contains machine language for the Java virtual machine

Example Source Program

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


Above is the source program (source file) from chapter 5 The program types the characters Hello World! on the monitor.

The file must be named Hello.java to match the name of the class, Hello 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 a Java program are important.

A programming language where upper and lower case make a difference is called case sensitive. Java is case sensitive. Not all programming languages are.

Lines are indented to show the logical structure of the program. This is not required by Java, but makes the program easier to understand. (More on this later.)

The first line

public class Hello

says that this source program defines a class called Hello. A class is a section of a program that describes an object. (A more complete definition will come later on in these notes.) Small programs often consist of just one class. When the program is compiled the compiler creates a file of bytecodes called Hello.class.


Question 2:

Here is the first line of another Java program:

      public class AddUpNumbers   
  1. What should the source file be named?
  2. What is the name of the bytecode file the compiler create

3. Identifiers and Reserved Words


Answer:

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

Identifiers and Reserved Words

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


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 is called an identifier. An identifier is one or more characters long.

The first character of an identifier cannot be a digit. The remaining characters can be a mix of alphabetic characters, digits, underscore, and dollar sign $. No spaces are allowed inside an identifier.

It is conventional for a class name to start with a capital letter, but this is not required by the compiler. However, follow this convention so your programs are easier to understand. A source file should always end with .java in lower case.

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?

ExcitingGame
Lady Luck
x32
lastChance
x/y
1stPrize

4. Between the Braces


Answer:

ExcitingGame     OK: mixed upper and lower case is allowed
Lady Luck     BAD: no spaces allowed inside an identifier
x32     OK: identifiers must start with an alphabetical character, but the rest can be digits.
lastChance     OK: class names usually start with a capital, but identifiers don't have to.
x/y     BAD: the slash is not allowed inside an identifier
1stPrize     BAD: starts with a digit

Between the Braces

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


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

public class ClassName
{
}

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 parentheses 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   ) 

5. println()


Answer:

public    static void main(String[]  args   )

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

println()

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


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 on one line. (The quotation marks are not written.)

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.

Programs usually contain many methods. Our example program contains just one method.

The part "Hello World!" is called a string literal. A string is a sequence of characters. A string literal consists of characters between quote marks, but does not include the quote marks. It can contain any valid character, including white space and punctuation. This program writes a string to the monitor and then stops.

In a source file, a string literal must be on just one line. The following is not legal, and will not compile:

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


Question 5:

(Review: ) Say that the file Hello.java contains the example program. In order to run it, what
two things must be done?

6. Running a Java Program (Review)


Answer:

public    static void main(String[]  args   )

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

Running a Java Program (Review)

If you are running Java programs using BlueJ or some other environment, or using an OS other than Windows, skip this page.

Copy and paste the example program into a text editor (like Notepad or Notepad++), 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 .

C:\JavaSource>DIR *.java
 Volume in drive C has no label.
 Volume Serial Number is 7C68-1E55

 Directory of C:\JavaSource

 08/23/98  01:07a                   115 Hello.java
               1 File(s)            115 bytes
                          2,448,368,640 bytes free

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.

javac Hello.java
  compiling: Hello.java

C:\JavaSource>java Hello

Hello World!

C:\JavaSource>

Question 6:

  • What is the command that runs the Java compiler?
  • What is the command that runs the Java interpreter?

7. Syntax Errors


Answer:

    • What is the command that runs the Java compiler?
      • javac
    • What is the command that runs the Java interpreter?
      • java

Syntax Errors

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

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

Question 7:

What is the error?

8. A Capital Mistake


Answer:

The first letter of "Class" is wrong.

A Capital Mistake

The reserved word "class" has been changed to "Class" with a capital "C". So what? 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.

C:\JavaSource>javac Hello.java

  compiling: Hello.java
Hello.java:1: Class or interface declaration expected.
public Class Hello
       ^
1 error


Question 8:

What is the error in the following program?

C:\JavaSource>public class hello
{
  public static void main ( string[] args )
  {
    System.out.println("hello world!");
  }
}            

9. Fixing Errors


Answer:

The reserved word String has been changed to string . The other changes in case are OK.
The class name 
hello is OK. Class names are your choice. It is usual to start class names with
upper case, but OK not to. The characters inside quotes can be (nearly) anything you want.

Fixing Errors

editCycle

Usually you will have two windows open on your computer: one for a text editor (such as Notepad or Notepad++) 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?

10. Edit, Compile, and Run Cycle


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, and 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?

11. Bugs


Answer:

No

Bugs

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

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.

An Earwig

Question 11:

  1. Will this program compile without syntax errors?
  2. Will this program run?
  3. Does the program meet the assignment?

12. Longer Example Program


Answer:

  1. Will this program compile without syntax errors?
    • Yes.
  2. Will this program run?
    • Yes.
  3. Does the program meet the assignment?
    • No — it has a bug.

Longer Example Program

public class Emily
{
  public static void main ( String[] args )
  {
    System.out.println("A bird came down the walk:");
    System.out.println("He did not know I saw;");
    System.out.println("He bit an angle-worm in halves");
    System.out.println("And ate the fellow, raw.");
  }
}

Usually bugs are much more difficult to find than the one in the previous 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.

(Remember that you can use "copy-and-paste" with your program editor to very quickly create this program.) (Or you can use the web pages mentioned at the start of chapter 5.)

Save the program in a file called Emily.java. Compile it. The compiler will create a bytecode file called Emily.class .

Each System.out.println statement writes out the characters inside the quote marks on one line:

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


Question 12:

Another method, System.out.print("Some String") writes out the characters inside
the quote marks and then stops without going on the the next line of the monitor.

Imagine that each println in the program is changed to print. What will the program write?

13. Another Example


Answer:

A bird came down the walkHe did not know I saw;He bit an angle-worm in halvesAnd ate the fellow, raw.

To make this output more readable, put a space at the end of each string literal in the program.

Another Example

Public class Haiku

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.

14. Finished Program


Answer:

The completed program is given below.

Did you remember to put in the quote marks?

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!

public class Haiku
{
  public static void main ( String[] args )
  {
    System.out.println("On a withered branch"); System.out.println("
        A crow has just alighted:"); System.out.println("
        Nightfall in autumn."); } }         

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:

public                    class     
    Haiku{
  public   static void main(String[] args )
    {
  System.out.   println(          "On a withered branch");
    System  .  out.println("A crow has just alighted:"         );
System.out.println("Nightfall in autumn.");
  }}            

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.

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?

15. Comments


Answer:

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

Students sometimes try to save typing by not indenting sensibly. Often, this results in hours of debugging.

Comments

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!

// Write three lines of a poem to the computer monitor public class Haiku
public class Haiku
{
public static void main ( String[] args )
{
System.out.println("On a withered branch" );
System.out.println("A crow has just alighted:");
System.out.println("Nightfall in autumn.");
}
}


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. Most program editors (such as 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. The colors are how the editor displays them. (Unlike a word processor, where the colors of text are actually encoded in the file.)


Question 15:

Are comments translated into bytecode by the compiler?

16. Many Comments


Answer:

No. The compiler ignores comments when creating the bytecodes.
Comments are just for human readers of the source program.

Many Comments

public class Haiku
{
  public static void main ( String[] args )
  {
    System.out.println("On a withered branch" );      // Write first line of the poem
    System.out.println("A crow has just alighted:");  // Write 2nd line of the poem
    System.out.println("Nightfall in autumn.");       // Write 3rd line of the poem
  }
}


Comments can be placed after a program statement to explain what it does, as here.

The // and everything after it on that line is 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?

17. Many-line Comments


Answer:

No. The compiler ignores comments when creating the bytecodes.
Comments are just for human readers of the source program.

Many-line Comments

/* Program 1
Write out three lines of a poem.
The poem describes a single moment in time,
using 17 syllables.
*/ public class Haiku { public static void main ( String[] args ) { System.out.println("On a withered branch" ); System.out.println("A crow has just alighted:"); System.out.println("Nightfall in autumn."); } }


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 characters */  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.


Question 17:

Is the following correct?
public class Haiku
{
  public static void main ( String[] args )
  {
    System.out.println /* print a line containing the following string */ ("On a withered branch" );
    System.out.println("A crow has just alighted:");
    System.out.println("Nightfall in autumn."); 
  }
}

18. Commenting Out Code


Answer:

No. The compiler ignores comments when creating the bytecodes.
Comments are just for human readers of the source program.

Commenting Out Code

public class BuggyHaiku
{
  public static void main ( String[] args )
  {
    System.out.println("On a withered branch" );
/*
    System.out.println("A crow has just alighted:");
    System.out.println("Nightfall" in autumn.");
*/
  }
}


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:

What is the error in the program?

Why would you ever want to use comments to help a person understand your program?

19. Braces


Answer:

What is the error in the program?
    Quote marks begin and end strings. The extra quote mark following Nightfall will end the string.
Why would you ever want to use comments to help a person understand your program
    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

public class Haiku
{
  public static void main ( String[] args )
  {
    System.out.println( "On a withered branch" );
    System.out.println( "A crow has just alighted:" );
    System.out.println( "Nightfall in autumn." );
  }
}  

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.

Some people prefer to indent by four spaces for each level. If you use a clever programming editor, you can set it up to indent as your prefer. It is important to be consistent. The purpose of indenting is to visually show the logic of the program. If your indenting is inconsistent, you have defeated the purpose.

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.

20. Matching Pairs


Answer:

The matching braces are indicated in color, below:

Matching Pairs

public class Haiku
{
public static void main ( String[] args )
{
System.out.println( "On a withered branch" );
System.out.println( "A crow has just alighted:" );
System.out.println( "Nightfall in autumn." );
}
}


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.

Notepad++ has become a World-favourite programming editor for Windows. It has sophisticated brace matching and automatic indenting. It can easily be used with the JDK environment. Get it at Notepad++


Question 20:

If a program is missing just one brace, will it compile?

21. End of the Chapter


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.

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