Вот и подошёл к концу наш конкурс! Поздравляем победителей!!! Подробнее.
Проект Programmers.kz и школа hotPen3D2D предлагает Вам курсы по веб-дизайну, веб-программированию и компьютерной графике. Подробности здесь.
- Просмотров: 1001
- Автор: КазКиберГетик
Beginning to Program
Категория: Программирование » Java » Уроки Java
Java Unit 2
Beginning to Program
2.1 Initial Example
2.2 Information on Program Appearance and Printing
2.3 The Java API Documentation
2.4 Creating and Using Objects
2.5 Errors
2.1 Initial Example
The goal of this section is to give an initial explanation of the first example program, given at the end of the previous set of notes. Here is the program:
public class FirstProg
{
public static void main(String[] args)
{
MyTerminalIO myterminal = new MyTerminalIO();
myterminal.println("Hello World");
}
}
What follows is a step by step description of the syntax of the program along with some explanation of how and why the code is written in this way. At this early stage it is most important to become familiar with the syntax, so that you can make use of it when beginning to write your own programs. The explanations are given because most people don’t want to try and learn something in a vacuum. However, if the explanations seem cryptic or incomplete, don’t worry. More detail will be given in future units.
- The first line of code shows the syntax for the declaration of a class:
public class FirstProg
All user written programs are classes. The class is public, which means it is freely available for general use. The name of the class is “FirstProg”.
- The second line of code is quite easy to explain, and it goes with the last line of code. All class definitions are enclosed in a matched set of braces, {}.
- The third line of code introduces a method.
public static void main(String[] args)
The name of this method is “main()”. A stand-alone program has to have a main() method. When you ask the Java system to run the program, the system looks inside the program class and causes this method to run. The keyword “public” signifies that the method is freely available for the system to call. The keyword “static” signifies that main() is a general purpose method, not one that is used on an object. This will be explained in greater detail later. The keyword “void” indicates that running this method does not cause any value to be returned.
Every method name is followed by a matched pair of parentheses. When methods are referred to in these notes, they will always be referred to by name plus parentheses, such as “main()”. This makes it clear that the name “main” is the name of a method rather than the name of something else. The main() method has something in the parentheses. These are parameters for command line arguments. This program does not make use of them, but it is still necessary to include the declaration in the code. The actual form of the declaration will be explained in a future set of notes.
- The fourth and seventh lines of code are quite easy to explain. All method definitions are enclosed in a matched set of braces, {}.
- The fifth line of code accomplishes the construction of an object. The class of the object is MyTerminalIO. The name of the object is myterminal. The keyword new comes immediately before the call to the constructor, which is the name of the class followed by a set of parentheses.
MyTerminalIO myterminal = new MyTerminalIO();
This object, myterminal, an instance of the class MyTerminalIO, can make use of a method which makes it possible to write output to the output screen. You will see later that the class also supports input from the keyboard.
- The sixth line of code does the real work of the program. It exemplifies the model for doing useful work using objects. The name of the object is myterminal. This is followed by a dot, which is followed by the name of a method. The method is called on the object with the parameter “Hello World”.
myterminal.println("Hello World");
If you were able to compile and run the program when it was given in Chapter 1, you know what it does: It prints the message “Hello World” in a window on the screen. The ability to accomplish this is the starting point for learning how to do other things in Java.
2.2 Information on Program Appearance and Printing
Comments are explanatory notes that a programmer can include in a program. They are not code and they do not affect how the program runs. On any line where “//” appears, whatever follows this pair of symbols is treated as a comment. Likewise, anything that appears between “/*” and “*/” will be treated as a comment. Here is a commented version of the first program:
/* This is my first program. */
public class FirstProg
{
public static void main(String[] args)
{
// An object is created here.
MyTerminalIO myterminal = new MyTerminalIO();
// A method is called on the object here.
myterminal.println("Hello World");
}
}
When writing a program it is helpful to indent every set of matched braces so that it is clear where a block of code begins and ends, and whether or not there are nested sets of blocks. The TextPad editor will do this for you automatically, and all examples given will be shown in this form.
Here is a brief summary of some of the aspects of printing in Java when using println() and related methods.
- The method println() prints a line of output followed by a new line or carriage return. You can also make use of the method print(), which prints a line without a carriage return. The complete call would be of the form:
- You can print arithmetic constants as well as strings of characters. A call such as this would print out the numeric value 3:
Note that what would appear on the screen for the following call would be exactly the same, but that there is an important distinction in the meaning of the program code. The example above prints a numeric value, while the example below prints a string containing the symbol “3”:
myterminal.println(“3”);
- You can print out more than one parameter at a time. The symbol that accomplishes this is the “+” sign. When printing strings, if you want blank spaces between things, you need to supply them explicitly. If you did this:
myterminal.println(“Hello” + “World”);
You would see this:
HelloWorld
However, you could also do this:
myterminal.println(“Hello” + “ World”);
Or this:
myterminal.println(“Hello” + “ “ + “World”);
And you would see:
Hello World
- Using the “+” sign when printing numeric values has a different effect. If you did this:
myterminal.println(3 + 4);
You would see this:
7
- You can also combine a parameter in quotes with a numerical value without quotes using a “+” sign. In this case the system automatically converts the numerical value to a string and does concatenation. If you did this:
You would see this:
Hello7
The full explanation of the different ways in which the “+” sign works will be given later. For the time being you should simply be able to use it correctly with strings and numbers.
- Although the dot has a special syntactic meaning in various places in Java code, in places where simple parameters in the form of numbers are allowed, such as when printing, it has its customary meaning—that of a decimal point. Thus, if you did this:
You would see this value:
3.4
- In Java printing, the backslash “\” is used as the escape sequence. This means that any symbol immediately following the backslash is simply treated as a printable character. That character is not treated as having any syntactic meaning. This allows you to print characters that would otherwise be ambiguous or syntactically incorrect in a printing parameter. If you wanted to print a double quote, you could do this:
myterminal.println(“\””);
If you wanted to print the backslash itself, you could do this:
myterminal.println(“\\”);
The backslash can also be used to insert special printing instructions into a printed string. \n represents a new line. Thus, if you did this:
myterminal.println(“Hello\nWorld”);
You would see this:
Hello
World
2.3 The Java API Documentation
What follows are the contents of the Java Application Programming Interface (API) Documentation for the system supplied class Point. The complete Java API documentation can be found at this Web address: http://java.sun.com/j2se/1.3/docs/api/. This is the best reference available when you have questions about programming in Java. An explanation is given after the excerpt.
java.awt
Class Point
java.lang.Object
|
+--java.awt.geom.Point2D
|
+--java.awt.Point
All Implemented Interfaces:
public class Point
extends Point2D
implements Serializable
A point representing a location in (x, y) coordinate space, specified in integer precision.
Since:
JDK1.0
See Also:
|
Inner classes inherited from class java.awt.geom.Point2D |
|
Field Summary |
|
|
|
|
|
|
|
|
Constructor Summary |
|
|
|
|
|
|
|
|
|
|
|
Method Summary |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The information given at the top of the documentation concerns the naming of the class and where it is located. System supplied classes are arranged in packages. If you scan through the information at the top you will eventually find this: java.awt.Point. “awt” stands for “abstract windowing toolkit”. This is the name of a package in Java which includes classes related to doing graphical things. Point is one of those classes. If a program uses a system supplied class, a line like this can be put at the top of the code:
import java.awt.Point;
The idea is that this will make the class available for use in the program. This will be done in the example programs. It is possible to import all classes in a package at once. If you chose to do this, you would use a wildcard:
import java.awt.*;
The next segment of interest in the documentation is entitled “Field Summary”. In the documentation, what are referred to in these notes as instance variables are referred to as fields. In other words, you discover from this documentation that an object created from the Point class will have two instance variables, an x coordinate and a y coordinate. These instance variables are given the type “int”, which signifies that these coordinates can take on integer values.
The next segment in the documentation is entitled “Constructor Summary”. Constructors are special pieces of code used for creating instances of classes. Constructors have a form reminiscent of methods—they have a name followed by a set of parentheses which may or may not contain parameters. Constructors are not methods. Their name is the same as the class they belong to. As you can see, a single class may have more than one constructor. The system can tell them apart because they have different parameter lists. In the documentation the types of the parameters are shown. For the time being we will restrict our attention to examples with parameters of the type “int”.
The last segment of the documentation is the “Method Summary”. This gives all of the methods by name and all of their parameters by name, including their types. There can be different methods with the same name. The system tells them apart by their parameter lists. It is only through these methods that a program can affect the instance variables, the x and y coordinates, of a Point object that has been created. As you can see, int and double are two different numeric types. The meaning of types will be covered in the next unit. For the time being, examples will be restricted to the int, or integer type. This type can hold whole number values.
2.4 Creating and Using Objects
Writing the code for classes of your own will come later. You have already created and used an object of a class supplied with these notes, MyTerminalIO. Now it is possible to understand and correctly write lines of code and small, complete programs that construct objects from system supplied classes and then make use of them.
Assuming that the Point class has been imported into a program, the following two lines of code 1) Declare a name which can be used for a Point object, and 2) Construct an object and give it that name, using the “=” sign, or assignment to do so:
Point mypoint;
mypoint = new Point(10, 20);
This is the specific syntax for calling a constructor and passing it parameters:
new Point(10, 20);
In order to call a constructor, the keyword “new” has to be used. The call shown will initialize the x and y coordinate values of the constructed point to 10 and 20, respectively.
The two lines given above are typically compressed into a single line of code:
Point mypoint = new Point(10, 20);
When you construct an object and give it a name, you can think of this as putting a handle on the object. The name, “mypoint” is the handle. You can use this handle later on to refer to the object and manipulate it. To make this idea clearer, it is possible to consider the following example, where an object is created, but it is not given a name:
new Point(10, 20);
The code is syntactically valid. It will not cause compile time or run time errors. It causes a Point object to be created. However, the object cannot be accessed in the rest of the program because it doesn’t have a name.
In the discussion above, the ideas were explained in terms of “giving an object a name”. The more technical term, which will be used in the rest of these notes, is “object reference”. A call to a constructor returns an unnamed reference to an object. When you declare a name, such as mypoint, and assign the unnamed reference to that name, the name becomes a reference to the object.
The idea of named and unnamed references can be illustrated further with another example. Consider the following line of code, which is syntactically correct. The println() method will accept the reference returned by a call to the constructor for a Point, even though the object is unnamed. This reference is a valid parameter and println() will print out information about the object referred to.
myterminal.println(new Point(10, 20));
Code where one call is contained in another is not particularly easy to read or understand, and the use of unnamed references is generally not very clear. This example is not given because it illustrates good code writing. It is given because it concretely illustrates that a call to a constructor causes an object to come into existence even if it remains unnamed.
If an object has been constructed and given a name, methods can be used on it. The Point class has a method translate(), which has the effect of shifting the location of a point in the plane by adding or subtracting values to its x and y coordinates. Here is an example of a line of code where a method is called on an object:
mypoint.translate(30, 40);
The call takes this form: An object reference, a dot, a method name, and a parameter list. It is the dot which signifies the call of the method on the object. It is important to note the syntactic difference between calling a constructor and a method. The method call does not use the keyword “new”.
The effect of executing this line of code is to shift the point which was constructed above with x and y coordinates of 10 and 20 to a new location with an x coordinate of 10 + 30, or 40, and a y coordinate of 20 + 40, or 60. The line of code making the method call does not take the form of an assignment. Values are assigned to instance variables as a result of the call, but the work of doing the assignments is hidden inside the method code. The Point class is a black box because it is not necessary to see the method code in order to correctly make use of the method.
Here is a synopsis of the basic method calling pattern, which will be repeated over and over again, with variations:
object.method(parameters);
At this stage there is one more thing we can do with the object: Print it out. The printing methods will accept object references as parameters. If the object exists, this is a valid line of code:
myterminal.println(mypoint);
We are not yet doing graphical programming, and the output looks like this:
java.awt.Point[x = 10, y = 20]
The system is simply telling the type of the reference and what the current values of the instance variables are.
It is now possible to write an example program which includes the features described above:
import java.awt.Point;
/* This is the second example program. */
public class SecondProg
{
public static void main(String[] args)
{
MyTerminalIO myterminal = new MyTerminalIO();
Point mypoint = new Point(10, 20);
myterminal.println(mypoint);
mypoint.translate(30, 40);
myterminal.println(mypoint);
}
}
2.5 Errors
Programming errors can be classified in several ways. One way of classifying them is by when they are detected, before, during, or after a run. Another way, which is related, is by whether they are errors of syntax or errors of logic. Syntax errors are mistakes in using the rules of the language. Logic errors are mistakes in understanding the problem and coming up with a set of steps to solve it. Here is a table with some general information about these categories of errors.
|
When errors are detected |
Type of errors |
Explanation |
|
Compilation time |
Syntax errors |
The compiler will try to find syntax errors. A program containing syntax errors can’t be run. |
|
Run time |
Syntax errors |
The system may also find errors at run time and terminate a program with an error message. |
|
After running |
Logic errors |
A program that runs to completion may give obviously incorrect results. A program may also give incorrect results which are not obvious. It is up to the programmer to test programs and verify their output. The compiler and the system cannot do this. |
The three most common, simplest, and often most vexing syntax errors for beginners are the following:
1. Forgetting a semicolon at the end of a line of code. This can be troublesome because the error message will indicate that the error is in a neighboring line, not the line missing the semicolon.
2. Forgetting to match braces. This can also be troublesome because the compiler will not correctly identify the line where the error is. If you indent matched braces when writing programs, this decreases the chance of making this mistake and increases the chance of finding it easily if it is made.
3. The fact that Java is case sensitive can also be troublesome. Forgetting to capitalize something that should be capitalized or mistakenly capitalizing something that shouldn’t be capitalized will lead to problems. It is difficult for the human eye to detect such minor differences in code.
Mistakes in capitalization are especially problematic. Quite often they are simply typographical errors, not logic errors on the part of the programmer. Sometimes they result in a syntax error which the compiler will detect or which will be detected at run time. However, they may also result in apparently correct code and the error will only become apparent at run time, as if it were a logic error. In other words, these mistakes cause problems that seem to straddle the boundary between syntax and logic errors. For this reason and because it is not easy to see either a missing or unintentional capital letter, they can be hard to track down.
In a language with references to objects another source of errors arises. This is the attempt to use references when an object has not yet been constructed. Consider the following fragment of code, which contains this kind of error:
…
Point mypoint;
myterminal.println(mypoint);
…
In this example, you declare a reference but do not construct an object. The reference doesn’t refer to anything. In the code, this reference is passed to the println() method as a parameter. When you try to compile it, the compiler will give an error saying that mypoint has not been initialized. Now consider the following example:
…
Point mypoint;
mypoint.translate(30, 40);
…
This time you’re calling a method on a reference which does not refer to an object. The compiler will also find this error and say that mypoint hasn’t been initialized.
The Java compiler and run time environment try to detect errors and print helpful error messages. However, they can’t find everything and sometimes the messages are somewhat cryptic. As more powerful concepts and syntax become available, and as programs grow more complex, programming errors can become more subtle in nature and the programmer has to be careful when programming and attentive when trying to debug faulty programs. Object references are a critical part of Java programming. Their correct use and errors resulting from their misuse will be covered in greater detail in future units of these notes.
Author: Kirk Scott
Мы рекомендуем Вам зарегистрироваться либо войти на сайт под своим именем.




