3 Copyright © 2005, Oracle. All rights reserved. Basic Java Syntax and Coding Conventions.
Basic Java Syntax
description
Transcript of Basic Java Syntax
Java 1
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Basic Java Syntax
• The java language will be described by working through its features:– Variable types and expressions.
– Selection and iteration.
– Classes (Using and Writing!)
– Exceptions.
• Small sample programs will be provided to illustrate how each feature is used (IF WE HAVE ENOUGH TIME )
Java 2
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Program Structure
• A program in java consists of one or more class definitions. One of these classes must define a method main(), which is where the program starts running
// A Java Hello World Program
public class HelloWorld { public static void main( String args[] ) { System.out.println( "Hello World" ); }}
// A Java Hello World Program
public class HelloWorld { public static void main( String args[] ) { System.out.println( "Hello World" ); }}
Java 3
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Comments
• Providing a description of what the program does is called commenting the code.– Commenting is used to provide an overall description of the class
and what it does, who the author is, when the class was created and modified, etc. – Header comments (See Java Coding Standard!)
– Commenting is also used throughout your code to provide a description of a method, as well as to provide descriptions of complicated code.
– The use of meaningful variable and method names helps “comment” the code.
Java 4
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Comments
• Comments come in three forms:
// single line comments
/* multi line comment*/
/** a * Javadoc * comment */
Java 5
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Comments
• Comments can not be put inside of another comment.
• Comments are for the programmer only, they do not represent executable code. – The computer ignores comments.
Java 6
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Commenting Rules of Thumb
• Do not state the obvious for self-evident information. For example if the code is: – x = x + y; // it is not necessary to comment that you are adding x
and y and storing the result in x.
• Provide a brief statement about each variable and a brief description for each method.
Java 7
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Commenting Rules of Thumb
• Do not comment code that is bad, if you are writing a long paragraph to describe what is going on, then re-write the code to make it simpler.
• Make sure your comments agree with the code.
• Use comments to clarify not confuse the unsuspecting reader. Use them to help the reader.
Java 8
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Javadoc
• A tool that comes with the JDK that produces html-based documentation from java source code.
• Within a Javadoc comment, various tags can appear which allow additional information to be processed.
• Each tag is marked by an @ symbol and should start on a new line.
Java 9
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Javadoc Tags
Tag Description@author Name the author(s) of the code:
@author Paul Tymann@author Paul Tymann, Jim Gosling
@deprecated Indicates that the following method will be removed in future versions@exception Information on exceptions thrown by a method@param Provide information about method and constructor parameters. The tag is followed by a
parameter name and a comment
@param count number of elements
@return Return value for non-void methods@see Provide cross reference to another class, interface, method, variable or URL.
@see java.lang.Integer
@since When a particular feature was included (i.e. since when it has been available)
@since JDK 1.0
@version Version information about the current revision of the code being documentated
Java 10
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Example
/** * A class that manages a circle given the radius * @see java.lang.Math * @version 1.0 * @author Paul Tymann */
public class Circle {
private double radius;
/** * Constructor for a circle. * * @param radius radius of the circle being created. Must be * positive and greater than 0. * */
public Circle( double radius ) { this.radius = radius; }}
/** * A class that manages a circle given the radius * @see java.lang.Math * @version 1.0 * @author Paul Tymann */
public class Circle {
private double radius;
/** * Constructor for a circle. * * @param radius radius of the circle being created. Must be * positive and greater than 0. * */
public Circle( double radius ) { this.radius = radius; }}
Java 11
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
The Result
• The result is a set of HTML pages.
• The documentation that is produced is meant to be part of the overall documentation that comes with the JDK.
• The 1.1 version of Javadoc did not support local modifications to the java documentation well.
• A much improved version of Javadoc is provided with java2.
Java 12
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
The Result
Java 13
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Java Classes
• The Java system comes with an extensive set of classes from which you may create objects, such as String and Math.
• To find out what you can do to java Strings you need to refer to the documentation that comes with the JDK (Java API link).
Java 14
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Classes
• Up to this point you have been using classes that have been provided to you
• In most programs you will find yourself in situations where the class you need does not exist
• Object-oriented programming languages allow you to create your own classes
Java 15
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Classes
• The class declaration introduces a new class.
• A class describes the structure and behavior of its instance objects in terms of instance variables and methods.
• Like variables, classes may be declared at different scopes. The scope of a class directly affects certain properties of the class.
• We will start with top-level classes.
Java 16
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Class Definition
• All class definitions in Java have the following form:
modifier class identifier { constant declarations class variable declarations instance variable declarations
constructor declarationsmethod declarations (class and instance)
}
Note: Top-level classes must be stored in a file named identifier.java
Java 17
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Class Modifiers
• Top-level classes can optionally be declared as: public - a public class is globally accessible. A single source file
can have only one public class or interface. abstract - an abstract class can have no instance objects. final -a final class cannot be subclassed.
• A class that does not have a modifier, can only be accessed by classes in the same package.
• In order to produce javadoc documentation for a class, that class must be declared public.
Java 18
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Instance Variables
• Instance variables form the state of an object.
• An instance variable can be declared as final, meaning that it is a constant.
public class Class1 { public String hello = “Hello”; public final String world = “World”; protected int count = 0; private float length = 2.345f;}
public class Class1 { public String hello = “Hello”; public final String world = “World”; protected int count = 0; private float length = 2.345f;}
Java 19
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Instance Variables
• Instance variables make up the state of the object
• In addition to a type, instance variables are also given one of three possible access levels– Public
• accessible to any class
– Private• only accessible from within the class it is declared in
– Protected• accessible to any subclass, or any class in the same package
Java 20
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Methods
• Methods define the behavior of the object.
• A method name is an identifier. Following the method name is a parenthesized formal parameter list, which may be empty (the parenthesis are still required).
• Each parameter consists of a type name followed by a parameter variable name.
Java 21
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Method Declarations
• The method declaration provides the function implementation in the program.
<modifiers> <return type> <method name> (<parameters>) {<method body>
}
• Modifiers represent terms that determine what kind of method is declared. (public/private/protected)
• The return type is the data type of the value returned by the method.– If the method does not return a value this value is void.– If a method returns a value, the body of the method must contain
one return statement.
Java 22
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Method Declarations
• Method names may be overloaded.
• Each method of the same name though must have a parameter list that differs in type and number of parameters from all the others.
• The return type of all methods of the same name must be the same!
Java 23
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Constructors
• A constructor is a method that will be invoked, automatically, whenever an object is created
String foo = new String();
• Initialization of the object is usually handled by the constructor
• A constructor is declared like a method:– constructors have no return type
– the constructor name is the same as the class
• Constructors are always public
Java 24
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Constructors
• A constructor with an empty parameter list is known as a default constructor.
• If a class does not define ANY constructor, the compiler will automatically insert one.
Java 25
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Default Constructor Example
public class Point {
private int xLocation; // The X coordinate of this point private int yLocation; // The Y coordinate of this point
/** * Create a point at the origin ( x = y = 0 ) */
public Point() { xLocation = 0; yLocation = 0; }
}
public class Point {
private int xLocation; // The X coordinate of this point private int yLocation; // The Y coordinate of this point
/** * Create a point at the origin ( x = y = 0 ) */
public Point() { xLocation = 0; yLocation = 0; }
}
Java 26
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Other Constructors
• You may also provide constructors that take arguments– This arguments can be used by the constructor when initializing
the object
• This means the constructor name is overloaded.
• Each constructor though must have a parameter list that differs in type and number of parameters from all the others
Java 27
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Constructor(s) Example
public class Point { private int xLocation; // The X coordinate of this point private int yLocation; // The Y coordinate of this point
/** * Create a point at the origin ( x = y = 0 ) */
public Point() { xLocation = 0; yLocation = 0; }
/** * Create a point at the specified coordinate. * * @param x The X coordinate * @param y The Y coordinate */ public Point( int initX, int initY ) { xLocation = initX; yLocation = initY; } public Point( double initX, double initY ) { xLocation = (int) initX; yLocation = (int) initY; }}
public class Point { private int xLocation; // The X coordinate of this point private int yLocation; // The Y coordinate of this point
/** * Create a point at the origin ( x = y = 0 ) */
public Point() { xLocation = 0; yLocation = 0; }
/** * Create a point at the specified coordinate. * * @param x The X coordinate * @param y The Y coordinate */ public Point( int initX, int initY ) { xLocation = initX; yLocation = initY; } public Point( double initX, double initY ) { xLocation = (int) initX; yLocation = (int) initY; }}
Constuctor overload
Default constructor
Java 28
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Defining Behavior
• A typical class will provide several methods that allow you to manipulate/query the state of an object
• The declaration of a method is very similar to the declaration of a constructor– The name of a method can be anything you like
– Methods can be declared public, private, or protected– Parameters are handled in the same way
Java 29
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
this
• this is a final variable that holds a reference to the object in which it exists (i.e. this IS a reference to the current object)
• The type of this is the reference type of the object
• It is sometimes necessary to pass a reference to the current object as a parameter to another method.
• this may also be used to refer to another constructor of the same class.
Java 30
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Static or Class Variables
• A static variable belongs to a class and is not part of the state of individual instance objects.
• Only one copy of each static variable exists.
• Class variables have several uses:– they are global to the class and can be shared by all objects of the
class.
– class constants
• (final = constant and static = global)
• Static variables must be explicitly initialized (because no constructor can do it).
Java 31
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Elevator
public class Elevator { private static int nextId = 0;
public final static int UP = 0; public final static int DOWN = 1;
private int direction = UP; private int myId;
public Elevator() { myId = nextId++; } public int getId() { return myId; } public int getDirection() { return direction; }
public void setDirection( int dir ) { switch ( dir ) { case UP: case DOWN: direction = dir; } } }
public class Elevator { private static int nextId = 0;
public final static int UP = 0; public final static int DOWN = 1;
private int direction = UP; private int myId;
public Elevator() { myId = nextId++; } public int getId() { return myId; } public int getDirection() { return direction; }
public void setDirection( int dir ) { switch ( dir ) { case UP: case DOWN: direction = dir; } } }
Java 32
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
TestElevator
public class TestElevator { public static void main( String args[] ) { Elevator a = new Elevator(); Elevator b = new Elevator(); Elevator c = new Elevator();
a.setDirection( a.DOWN ); // access through an object b.setDirection( Elevator.DOWN ); // access through the class
System.out.println( "Elevator A: Id=" + a.getId() + ", Dir=" + a.getDirection() ); System.out.println( "Elevator B: Id=" + b.getId() + ", Dir=" + b.getDirection() ); System.out.println( "Elevator C: Id=" + c.getId() + ", Dir=" + c.getDirection() ); }}
public class TestElevator { public static void main( String args[] ) { Elevator a = new Elevator(); Elevator b = new Elevator(); Elevator c = new Elevator();
a.setDirection( a.DOWN ); // access through an object b.setDirection( Elevator.DOWN ); // access through the class
System.out.println( "Elevator A: Id=" + a.getId() + ", Dir=" + a.getDirection() ); System.out.println( "Elevator B: Id=" + b.getId() + ", Dir=" + b.getDirection() ); System.out.println( "Elevator C: Id=" + c.getId() + ", Dir=" + c.getDirection() ); }}
Java 33
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Static Methods
• Static methods generally follow the same rules as methods, but:– a static method belongs to a class not its instance objects.
– a static method can be called directly (Classname.classMethod()) or by an object of the same class (classMethod)
– a static method cannot access any instance variables or methods (since it does not belong to an instance object); In other words, class methods can only access class methods and class variables!
– this cannot be used
Java 34
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Static Methods
• There is one special use of static methods in the form of static main.
• When a class defines a public static method main, it provides a starting point for execution of a program using that class.
• Any class can have a static main method.
• Static methods are generally used to provide utility or helper methods. For examples see java.lang.Math.
Java 35
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Parameters
• In a method declaration parameters (AKA, formal parameters) are used as place holders to indicate that arguments (AKA, actual parameters must be provided– Parameters specify the number and the types of the arguments that
must be provided when the method is invoked
• When a method is invoked, imagine that an assignment takes place between the parameters and the corresponding arguments
Java 36
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
The Application
public class PointTest { public static void main( String args[] ) { Point myPoint = new Point(); Point otherPoint = new Point( 12, 34 ); }}
Java 37
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
The Implementation of the Class
public class Point { private int xLocation; private int yLocation;
public Point() { xLocation = 0; yLocation = 0; }
public Point( int initX, int initY ) { xLocation = initX; yLocation = initY; }}
public class PointTest { public static void main( String args[] ) { Point myPoint = new Point(); Point otherPoint = new Point( 12, 34 ); }}
Java 38
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Passing Parameters
public class Point { private int xLocation; private int yLocation;
public Point() { xLocation = 0; yLocation = 0; }
public Point( int initX, int initY ) { xLocation = initX; yLocation = initY; }}
initX = 12;initY = 34;
Note this is assignment, a copy of the arguments
public class PointTest { public static void main( String args[] ) { Point myPoint = new Point(); Point otherPoint = new Point( 12, 34 ); }}
Java 39
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
The Application
public class PointTest { public static void main( String args[] ) { int xLocation = 12; int yLocation = 34;
Point otherPoint = new Point( xLocation, yLocation );
System.out.println( xLocation ); System.out.println( yLocation ); }}
Java 40
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
The Implementation of the Class
public class Point { private int xLocation; private int yLocation;
public Point() { xLocation = 0; yLocation = 0; }
public Point( int newX, int newY ) { xLocation = newX; yLocation = newY;
newX = 0; newY = 67; }}
public class PointTest { public static void main( String args[] ) { int xLocation = 12; int yLocation = 34;
Point otherPoint = new Point( xLocation, yLocation );
System.out.println( xLocation ); System.out.println( yLocation ); }}
Java 41
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Passing Parameters
public class Point { private int xLocation; private int yLocation;
public Point() { xLocation = 0; yLocation = 0; }
public Point( int newX, int newY ) { xLocation = newX; yLocation = newY;
newX = 0; newY = 67; }}
public class PointTest { public static void main( String args[] ) { int xLocation = 12; int yLocation = 34;
Point otherPoint = new Point( xLocation, yLocation );
System.out.println( xLocation ); System.out.println( yLocation ); }}
newX = xLocation;newY = yLocation;
Note these variables are not the samealthough they have the same name(s)
Java 42
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Primitive vs. Complex Data Types
• When you define a primitive data type (int, char, double, boolean) the memory location is allocated.– The number of bytes is always the same to store a value.
– char let = 'A';
let A
Java 43
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Primitive vs. Complex Data Types
• A complex data type is a data type defined by a class. – String is an example of a complex data type.
– Complex data types usually begin with a capital letter.
– The amount of storage required for a complex data type varies depending upon how large the actual values are.
– Complex data types are also called reference data types.
Java 44
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Primitive vs. Complex Data Types
• When we define a String a memory location is allocated to hold a reference to the actual location of the information.– The reference is the location of the first item in memory.
– The information is stored sequentially beginning at the reference location.
Java 45
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Primitive vs. Complex Data Types
• String name0, name1;
• name1 = "Rochester";
• name0 = name1; name1 2044 1012
…2044
2048R oc h
e s
t e
r
2052
2056
2060
name0 2044 1008
Java 46
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Primitive vs. Complex Data Types
• If we define another string and assign it equal to name then they will both point to the same location in memory.– string name0 = name1;
– Now name1 and name0 both point to memory location 2044.
Java 47
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Passing Objects to methods
• Some of the String methods require a String as a parameter to the method.– For example, *.equals(String);
– The method definition requires a String object to be passed to the method equals.
Java 48
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Passing Objects to methods
– When we pass a String to a method we are passing it using call-by-reference.
• This means that we do not pass the actual string, we are passing the contents of the memory location that holds the reference (address) to the actual string.
– A problem associated with call-by-reference is that the original object may be modified.
– All objects (both Java defined and user defined) are passed using call-by-reference.
Java 49
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Passing Primitive Data to Methods
• If a program passes a variable that has a primitive data type to a method, the actual value is passed using call-by-value.– The advantage is that the original value can not be modified by the
method.
– The disadvantage is that a copy of the original value is made, this requires more memory.
Java 50
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
Returning Things from Methods
• When a method returns an object, a memory reference is really returned. – Not the actual data.
• When a method returns a primitive data type, then the actual value is returned.
Java 51
Vla
dim
ir M
isic
: vm
@cs
.rit
.ed
u
UML for our Point class
Point -x: double-y: double-numberOfPoints:int
+Point( )
+Point( Point point )
+Point( double x, double y )
+getNumberOfPoints():int
+distanceTo(): double
+distanceTo( Point p ): double
+distanceTo( double x, double y):double
+getX( ): double
+getY( ): double
+moveTO( double x): void
+moveTO( double x): void
+moveTO( double x): void
+ means public
- means private