unit 2: java introduction to programming

81
Unit 2: Java Introduction to Programming Kirk Scott

Upload: yuki

Post on 22-Mar-2016

42 views

Category:

Documents


4 download

DESCRIPTION

Unit 2: Java Introduction to Programming. Kirk Scott. 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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Unit  2:   Java Introduction  to Programming

Unit 2: Java Introduction to Programming

Kirk Scott

Page 2: Unit  2:   Java Introduction  to Programming

2.1 Initial Example2.2 Information on Program Appearance and Printing2.3 The Java API Documentation2.4 Creating and Using Objects2.5 Errors

Page 3: Unit  2:   Java Introduction  to Programming

2.1 Initial Example

Page 4: Unit  2:   Java Introduction  to Programming

• 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)• {• System.out.println("Hello World");• }• }

Page 5: Unit  2:   Java Introduction  to Programming

• 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.

Page 6: Unit  2:   Java Introduction  to Programming

• 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.

Page 7: Unit  2:   Java Introduction  to Programming

• 1. 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”.

Page 8: Unit  2:   Java Introduction  to Programming

• 2. 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, {}.

Page 9: Unit  2:   Java Introduction  to Programming

• 3. 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.

Page 10: Unit  2:   Java Introduction  to Programming

• 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.

Page 11: Unit  2:   Java Introduction  to Programming

• 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.

Page 12: Unit  2:   Java Introduction  to Programming

• 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.

Page 13: Unit  2:   Java Introduction  to Programming

• 4. The fourth and sixth lines of code are quite easy to explain.

• All method definitions are enclosed in a matched set of braces, {}.

Page 14: Unit  2:   Java Introduction  to Programming

• 5. The fifth line of code does the real work of the program.

• System.out.println("Hello World");• • Here the method println() is called. • This causes output to be sent to the Console. • In general a method is called “on” something, and that is

symbolized by the words System and out and the use of dots. • The method is called with the parameter “Hello World”. • Calling methods is important and will be a major topic in the note

files.

Page 15: Unit  2:   Java Introduction  to Programming

• If you were able to compile and run the program when it was given in Unit 1, you know what it does:

• It prints the message “Hello World” in the Console.

• The ability to accomplish this is the starting point for learning how to do other things in Java.

Page 16: Unit  2:   Java Introduction  to Programming

2.2 Information on Program Appearance and Printing

Page 17: Unit  2:   Java Introduction  to Programming

• 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.

Page 18: Unit  2:   Java Introduction  to Programming

• Here is a commented version of the first program:

• /* This is my first program. */•  • public class FirstProg• {• public static void main(String[] args)• {• // A method is called here.• System.out.println("Hello World");• }• }

Page 19: Unit  2:   Java Introduction  to Programming

• 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.

• Eclipse will do this for you automatically, and all examples given will be shown in this form.

Page 20: Unit  2:   Java Introduction  to Programming

• Here is a brief summary of some of the aspects of printing in Java when using println() and related methods.

• 1. 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:• • System.out.print("Some Parameter");

Page 21: Unit  2:   Java Introduction  to Programming

• 2. You can print arithmetic constants as well as strings of characters.

• A call such as this would print out the numeric value 3:

• • System.out.println(3);

Page 22: Unit  2:   Java Introduction  to Programming

• 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”:

• • System.out.println("3");

Page 23: Unit  2:   Java Introduction  to Programming

• 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:• • System.out.println("Hello" + "World");• • You would see this:• • HelloWorld

Page 24: Unit  2:   Java Introduction  to Programming

• However, you could also do this:• • System.out.println("Hello" + " World");• • Or this:• • System.out.println("Hello" + " " + "World");

• • And you would see:• • Hello World

Page 25: Unit  2:   Java Introduction  to Programming

• 4. Using the “+” sign when printing numeric values has a different effect.

• It does the arithmetic. • If you did this:• • System.out.println(3 + 4);• • You would see this:• • 7

Page 26: Unit  2:   Java Introduction  to Programming

• 5. 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:• • System.out.println("Hello" + 7);• • You would see this:• • Hello7

Page 27: Unit  2:   Java Introduction  to Programming

• 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.

Page 28: Unit  2:   Java Introduction  to Programming

• 6. 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:• • System.out.println(3.4);• • You would see this value:• • 3.4

Page 29: Unit  2:   Java Introduction  to Programming

• 7. 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.

Page 30: Unit  2:   Java Introduction  to Programming

• If you wanted to print a double quote, you could do this:

•• System.out.println("\"");• • If you wanted to print the backslash itself, you could

do this:• • System.out.println("\\");

Page 31: Unit  2:   Java Introduction  to Programming

• 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:• • System.out.println("Hello\nWorld");• • You would see this:• • Hello• World

Page 32: Unit  2:   Java Introduction  to Programming

2.3 The Java API Documentation

Page 33: Unit  2:   Java Introduction  to Programming

• What follows are the contents of the Java Application Programming Interface (API) Documentation for the system supplied class Point.

• The complete online Java API documentation can easily be found through a Web search.

• This is a comprehensive reference for questions about programming in Java.

• An explanation of the excerpt from the documentation is given following it.

Page 35: Unit  2:   Java Introduction  to Programming

• 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: • Serialized Form

Page 38: Unit  2:   Java Introduction  to Programming

Constructor SummaryPoint() Constructs and initializes a point at the origin (0, 0) of the coordinate space.

Point(int x, int y) Constructs and initializes a point at the specified (x, y) location in the coordinate space.

Point(Point p) Constructs and initializes a point with the same location as the specified Point object.

Page 39: Unit  2:   Java Introduction  to Programming

Method Summary boolean

equals(Object obj) Determines whether an instance of Point2D is equal to this point.

Point

getLocation() Returns the location of this point.

double

getX() Returns the X coordinate of the point in double precision.

double

getY() Returns the Y coordinate of the point in double precision.

void

move(int x, int y) Moves this point to the specificed location in the (x, y) coordinate plane.

Page 40: Unit  2:   Java Introduction  to Programming

void setLocation(double x, double y) Sets the location of this point to the specified float coordinates.

void setLocation(int x, int y) Changes the point to have the specificed location.

void setLocation(Point p) Sets the location of the point to the specificed location.

String toString() Returns a string representation of this point and its location in the (x, y) coordinate space.

void translate(int x, int y) Translates this point, at location (x, y), by dx along the x axis and dy along the y axis so that it now represents the point (x + dx, y + dy).

Page 41: Unit  2:   Java Introduction  to Programming

• 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.

Page 42: Unit  2:   Java Introduction  to Programming

• Point is one of those classes. If a program uses a system supplied class, a line like this is 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 the * as a wildcard:• • import java.awt.*;

Page 43: Unit  2:   Java Introduction  to Programming

• 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.

Page 44: Unit  2:   Java Introduction  to Programming

• 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.

Page 45: Unit  2:   Java Introduction  to Programming

• 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”.

Page 46: Unit  2:   Java Introduction  to Programming

• 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.

Page 47: Unit  2:   Java Introduction  to Programming

• 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.

Page 48: Unit  2:   Java Introduction  to Programming

2.4 Creating and Using Objects

Page 49: Unit  2:   Java Introduction  to Programming

• Writing the code for classes of your own will come later.

• At this time 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.

Page 50: Unit  2:   Java Introduction  to Programming

• 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);

Page 51: Unit  2:   Java Introduction  to Programming

• 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 frequently compressed into a single

line of code:• • Point myPoint = new Point(10, 20);

Page 52: Unit  2:   Java Introduction  to Programming

• 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);

Page 53: Unit  2:   Java Introduction  to Programming

• 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.

Page 54: Unit  2:   Java Introduction  to Programming

• 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.

Page 55: Unit  2:   Java Introduction  to Programming

• 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.

• • System.out.println(new Point(10, 20));

Page 56: Unit  2:   Java Introduction  to Programming

• 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.

Page 57: Unit  2:   Java Introduction  to Programming

• 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);

Page 58: Unit  2:   Java Introduction  to Programming

• 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”.

Page 59: Unit  2:   Java Introduction  to Programming

• 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.

Page 60: Unit  2:   Java Introduction  to Programming

• 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.

Page 61: Unit  2:   Java Introduction  to Programming

• Here is a synopsis of the basic method calling pattern, which will be repeated over and over again, with variations:

• • object.method(parameters);

Page 62: Unit  2:   Java Introduction  to Programming

• 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:• • System.out.println(myPoint);

Page 63: Unit  2:   Java Introduction  to Programming

• 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, namely, the class of the object, and what the current values of its instance variables are.

Page 64: Unit  2:   Java Introduction  to Programming

• It is now possible to write an example program which includes all of the features described above:• • import java.awt.Point;•  • /* This is the second example program. */•  • public class SecondProg• {• public static void main(String[] args)• {• Point myPoint = new Point(10, 20);• System.out.println(myPoint);• myPoint.translate(30, 40);• System.out.println(myPoint);• }• }

Page 65: Unit  2:   Java Introduction  to Programming

2.5 Errors

Page 66: Unit  2:   Java Introduction  to Programming

• 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.

Page 67: Unit  2:   Java Introduction  to Programming

• 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.

Page 68: Unit  2:   Java Introduction  to Programming

When errors are detected Type of errors ExplanationCompilation 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.

Page 69: Unit  2:   Java Introduction  to Programming

• 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.

Page 70: Unit  2:   Java Introduction  to Programming

• 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.

Page 71: Unit  2:   Java Introduction  to Programming

• 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.

Page 72: Unit  2:   Java Introduction  to Programming

• 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.

Page 73: Unit  2:   Java Introduction  to Programming

• 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.

Page 74: Unit  2:   Java Introduction  to Programming

• You may already have noticed that it is customary to capitalize the first letter of the names of classes, but not of object references.

• For object references, such as myPoint, it is also customary to capitalize internal letters in order to bring out the subparts of a name.

• These conventions make capitalization errors possible. • However, the conventions are useful because when

you read code you can quickly recognize class and object names.

Page 75: Unit  2:   Java Introduction  to Programming

• In a language where objects are constructed and references to objects are declared, there is another basic mistake that programmers can make.

• 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 yourPoint;• System.out.println(yourPoint);• …

Page 76: Unit  2:   Java Introduction  to Programming

• 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 yourPoint has not been initialized.

Page 77: Unit  2:   Java Introduction  to Programming

• Now consider the following example:• • …• Point yourPoint;• yourPoint.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 yourPoint hasn’t been initialized.

Page 78: Unit  2:   Java Introduction  to Programming

• 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.

Page 79: Unit  2:   Java Introduction  to Programming

• 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.

Page 80: Unit  2:   Java Introduction  to Programming

• 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.

Page 81: Unit  2:   Java Introduction  to Programming

The End