Java Programming Tutorial 1
Every programming language has two defining characteristics: Syntax Semantics
Programming Writing code with good style also provides the following benefits: It improves the readability, consistency, and homogeneity of the code, which makes it easier to understand and maintain. It makes the code easier to trace and debug, because it's clear and consistent. It allows you to continue more easily where you or another programmer stopped, particularly after a long period of time. It increases the benefit of code walkthroughs, because the participants can focus more on what the code is doing.
General Guidelines: Writing Java with good style is not hard, but it does require attention to detail. Here are some general guidelines to follow: Make the code clear and easy to read. Make the code consistent. Use obvious identifier names. Logically organize your files and classes. Have only one class per file (not including inner classes). Use a maximum line width of 80-90 characters. Use whitespace and/or other separators judiciously. Use spaces instead of tabs for indentation.
The Java language supports three kinds of comments: /* text */ The compiler ignores everything from /* to */. /** documentation */ This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The JDK javadoc tool uses doc comments when preparing automatically generated documentation. For more information on javadoc, see the Java tool documentation. // text The compiler ignores everything from // to the end of the line.
Comments There are two type of comments that you can put in your Java code: Javadoc comments (also called documentation comments) and implementation comments. Javadoc comments can be extracted by the javadoc tool to produce API documentation. Implementation comments are those comments that explain the how and why of the code. Use Also, keep in mind that good comments are helpful; bad comments are a nuisance. Example 1. Bad Comment Style // applyrotascii() -- Apply ASCII ROT private void applyrotascii(){ try{ int rotlength = Integer.parseInt(rotationLengthField.getText().trim()); // get rot len RotAscii cipher = new RotAscii(rotLength); // new cipher textarea.settext(cipher.transform(textarea.gettext())); // transform catch(exception ex){ /* Show exception */ ExceptionDialog.show(this, "Invalid rotation length: ", ex);
Example 2. Good Comment Style. /** * Apply the ASCII rotation cipher to the user's text. The length is retrieved * from the rotation length field, and the user's text is retrieved from the * text area. * * @author Thornton Rose */ private void applyrotascii() { int rotlength = 0; // rotation length RotAscii cipher = null; // ASCII rotation cipher try { // Get rotation length field and convert to integer. rotlength = Integer.parseInt(rotationLengthField.getText().trim()); // Create ASCII rotation cipher and transform the user's text with it. cipher = new RotAscii(rotLength); textarea.settext(cipher.transform(textarea.gettext())); catch(exception ex) { // Report the exception to the user. ExceptionDialog.show(this, "Invalid rotation length: ", ex);
Blocks and Statements Use the following guidelines for writing blocks and statements: Put only one statement per line. Always use braces with control statements (e.g., 'if'). Consider marking the end of a block with a comment (e.g., // end if), particularly with long or nested blocks. Put variable declarations at the beginning of a block. Always initialize variables.. Indent the case clauses in a switch block. Put whitespace before and after operators. In if, for, or while, put whitespace before the "(". Use whitespace and parentheses in expressions to increase readability.
Example 3. Bad Block Style. try{ for(int i=0;i<5;i++){... int threshold=calculatethreshold(); float variance=(threshold*2.8)-1; int c=0; if (threshold<=15) c=calculatecoefficient(); switch(c){ case 1: setceiling(c*2); break; case 2: setceiling(c*3); break; else: freakout(); catch(exception ex){...
Example 4. Good Block Style. try { int threshold = 0; float variance = 0.0; int coefficient = 0; // Prepare 5 cycles. for (int i = 0; i < 5; i ++){ preparecycle(i); // Calculate the threshold and variance. threshold = calculatethreshold(); variance = (threshold * 2.8) - 1; // If the threshold is less than the maximum, calculate the coefficient. // Otherwise, throw an exception. if (threshold <= MAX_THRESHOLD) { coefficient = calculatecoefficient(); else { throw new RuntimeException("Threshold exceeded!"); // Set the ceiling based on the coefficient. switch (coefficient) { case 1: setceiling(coefficient * 2); break; case 2: setceiling(coefficient * 3); break; else: freakout(); // end switch
Bytecode Programming code that, once compiled, is run through a virtual machine instead of the computer's processor. By using this approach, source code can be run on any platform once it has been compiled and run through the virtual machine. Bytecode is the compiled format for Java programs. Once a Java program has been converted to bytecode, it can be transferred across a network and executed by Java Virtual Machine (JVM). Bytecode files generally have a.class extension.
JVM A Java virtual machine (JVM), an implementation of the Java Virtual Machine Specification, interprets compiled Java binary code (called bytecode) for a computer's processor (or "hardware platform") so that it can perform a Java program's instructions. Java was designed to allow application programs to be built that could be run on any platform without having to be rewritten or recompiled by the programmer for each separate platform. A Java virtual machine makes this possible because it is aware of the specific instruction lengths and other particularities of the platform. The Java Virtual Machine Specification defines an abstract -- rather than a real -- machine or processor. The Specification specifies an instruction set, a set of registers, a stack, a "garbage heap," and a method area. Once a Java virtual machine has been implemented for a given platform, any Java program (which, after compilation, is called bytecode) can run on that platform. A Java virtual machine can either interpret the bytecode one instruction at a time (mapping it to a real processor instruction) or the bytecode can be compiled further for the real processor using what is called a just-in-time compiler.
Object-Oriented Programming Concepts Object: is an instance of a class Class: is a template for an object Inheritance: allows the creation of hierarchical classification class MountainBike extends Bicycle { // new fields and methods defining a mountain bike would go here Interface: allows a set of methods to be implemented by one or more classes class ACMEBicycle implements Bicycle { // remainder of this class implemented as before Package: a namespace for organizing related classes and interfaces in a logical manner
Class Definition Every Java program is defined as a class. A class is a collection of data, stored in named fields, and coded, organized into named methods, that operates on that data. The fields and methods are called members of a class. The members of a class come in two distinct types: class, or static, members are associated with the class itself, while instance members are associated with individual instances of the class (i.e., with objects) There are four types of members: Class fields Class methods Instance fields Instance methods
Class Is a template that defines attributes and methods Is written by a programmer as a part of a program Does not exist when programs execute, except in the form of one or more member objects Is static in the sense that its code cannot be altered during program execution Is named by a class name
Object Must belong to some class Exists during the time that a program executes Must be explicitly declared and constructed by the execution program Has attributes that can change in value and method that can execute during program execution( The class to which the object belongs defines these attributes and methods. )
Classfield A classfield is associated with the class in which it is defined, rather than with an instance of the class. The following line declares a class field: public static final double PI = 3.14159; The static modifier says that the field is a class field. Class fields are sometimes called static fields because of this static modifier. The final modifier says that the value of the field does not change. the public modifier says that anyone can use the field. The key point to understand about a static field is that there is only a single copy of it. This field is associated with the class itself, not with instances of the class. A class field is essentially a global variable.
Class method As with class fields, class methods are declared with the static modifier: public static double radianstodegrees(double rads) { return rads * 180 / PI; Like class fields, class methods are associated with a class, rather than with an object. When invoking a class method from code that exists outside the class, you must specify both the name of the class and the method. A class method can use any class fields and class methods of its own class (or of any other class). But it cannot use any instance fields or instance methods because class methods are not associated with an instance of the class. class method is a global method, or global function.
Instance Fields Any field declared without the static modifier is an instancefield : public double r; // The radius of the circle Instance fields are associated with instances of the class, rather than with the class itself. Thus, every Circle object we create has its own copy of the double field r. In our example, r represents the radius of a circle. Thus, each Circle object can have a radius independent of all other Circle objects. Inside a class definition, instance fields are referred to by name alone. In code outside the class, the name of an instance method must be prepended by a reference to the object that contains it. For example, if we have a Circle object named c, we can refer to its instance field r as c.r Circle c = new Circle(); // Create a new Circle object; store it in variable c c.r = 2.0; // Assign a value to its instance field r, Circle d = new Circle(); // Create a different Circle object d.r = c.r * 2; // Make this one twice as big
Instance Methods Any method not declared with the static keyword is an instance method. An instancemethod operates on an instance of a class (an object) instead of operating on the class itself. To use an instance method from outside the class in which it is defined, we must prepend a reference to the instance that is to be operated on. For example: Circle c = new Circle(); // Create a Circle object; store in variable c c.r = 2.0; // Set an instance field of the object double a = c.area(); // Invoke an instance method of the object
Declaring Variables There are several kinds of variables: Member variables in a class these are called fields. Variables in a method or block of code these are called local variables. Variables in method declarations these are called parameters. Field declarations are composed of three components, in order: Zero or more modifiers, such as public or private. The field's type. The field's name.
public class Bicycle { Example private int cadence; private int gear; private int speed; public Bicycle(int startcadence, int startspeed, int startgear) { gear = startgear; cadence = startcadence; speed = startspeed; public int getcadence() { return cadence; public void setcadence(int newvalue) { cadence = newvalue; public int getgear() { return gear; public void setgear(int newvalue) { gear = newvalue; public int getspeed() { return speed; public void applybrake(int decrement) { speed -= decrement; public void speedup(int increment) { speed += increment;
Methods More generally, method declarations have six components, in order: Modifiers such as public, private,... The return type the data type of the value returned by the method, or void if the method does not return a value. The method name the rules for field names apply to method names as well, but the convention is a little different. The parameter list in parenthesis a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses. An exception list The method body, enclosed between braces the method's code, including the declaration of local variables, goes here.
Overloading Methods The Java programming language supports overloading methods. public class DataArtist {... public void draw(string s) {... public void draw(int i) {... public void draw(double f) {... public void draw(int i, double f) {...
Constructors A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations except that they use the name of the class and have no return type. For example, Bicycle has one constructor: public Bicycle(int startcadence, int startspeed, int startgear) { gear = startgear; cadence = startcadence; speed = startspeed; To create a new Bicycle object called mybike, a constructor is called by the new operator: Bicycle mybike = new Bicycle(30, 0, 8) //new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields Although Bicycle only has one constructor, it could have others, including a no-argument constructor: public Bicycle() { gear = 1; cadence = 10; speed = 0; Bicycle yourbike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourbike.
Creating Objects Creating objects has three parts: Declaration: is variable declarations that associate a variable name with an object type. Instantiation: The new keyword is a Java operator that creates the object. The new operator instantiates a class by allocating memory for a new object and returning a reference to the object it created. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
Parameters You can use any data type for a parameter of a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computepayment method, and reference data types, such as objects and arrays. public Polygon polygonfrom(point[] corners) { // method body goes here public double computepayment(double loanamt, double rate, double futurevalue, int numperiods) { double interest = rate / 100.0; double partial1 = Math.pow((1 + interest), -numperiods); double denominator = (1 - partial1) / interest; double answer = (-loanamt / denominator)- ((futurevalue * partial1) / denominator); return answer;
Class level access modifiers Only two access modifiers is allowed, public and no modifier If a class is public, then it CAN be accessed from ANYWHERE. If a class has no modifer, then it CAN ONLY be accessed from same package.
Controlling Access to Members of a Class Access level modifiers determine whether other classes can use a particular field or invoke a particular method. At the member level public, private, protected, or package-private (no explicit modifier). Modifier Class Package Subclass World Public Y Y Y Y Protected Y Y Y N No modifier Y Y N N Private Y N N N
Thanks for your attension!