Small Java Programs

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.

19. Braces


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.


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.