CSC161 - Java Basics

Java Template

All the programs we write this semester will have the following look:

   public class Programmer-Defined {
      public static void main(String[ ] args) {
		Your code .....
      }
   }

The Programmer-Defined name is a name that you choose. The filename of the file in which you save your program must start with the same name as the Programmer-Defined name of the class, and must end with .java. It is standard practice to capitalize the first letter of a class name. Be sure to type main with a lowercase m and String with an uppercase S.

Sample Java program:

(1)  //
(2)  // First Java Example
(3)  //
(4)  // this program demonstrates some of the basic rules of Java
(5)  //
(6)     public class FirstExample {
(7)        public static void main(String[ ] args) {
(8)
(9)           // print a message
(10) 	     System.out.println("This message will appear on your screen.");
(11)       }
(12)    }
This program must be stored in a file named FirstExample.java. The numbers in parentheses at the beginning of each line are not part of the program. They are added to help us discuss the program.

Identifiers

In a program there are elements that the programmer must give a name. In the sample program the name FirstExample on line 6 was chosen by the programmer. These names are called identifiers, and all identifiers must conform to the following standard rules:

  1. The first character must be one of the letters a-z, A-Z, an underscore (_), or a dollar sign ($).
  2. After the first character, you may use the letters a-z, A-Z, the digits 0-9, underscore (_), or dollar sign ($).
  3. Uppercase and lowercase characters are distinct. This means that Java is a case sensitive language and interprets Salary and salary as two different identifiers.
  4. Identifiers cannot contain spaces.
  5. An identifier cannot be a keyword (see page 10 of your text for a list of keywords).

Comments

Comments are used to help humans understand a program. They are ignored by the compiler and have no effect on the execution of the program. A comment starts with two slashes; anything else on that line is ignored. There are comments on lines 1 through 5 and on line 9 of the above example.

Class Header

Line 6 is a class header. The class header marks the beginning of a class definition. In CSC161 we will use a class as the container for each program that we write. In CSC162 we will learn some additional uses for classes.

Method Header

Line 7 is the header for the method main. Later this semester we will write programs with multiple methods. For now our programs will have one method, which is always called main. All of our code will be inside the main method. The main method will always have the exact same header which is shown above.

Java Basics



Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2013