Basic Java Syntax Vladimir Misic vmcs rit edu
Basic Java Syntax Vladimir Misic: vm@cs. rit. edu • 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 1
Program Structure Vladimir Misic: vm@cs. rit. edu • 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 Hello. World { public static void main( String args[] ) { System. out. println( "Hello World" ); } } Java 2
Comments Vladimir Misic: vm@cs. rit. edu • 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 3
Comments • Comments come in three forms: Vladimir Misic: vm@cs. rit. edu // single line comments /* multi line comment */ /** a * Javadoc * comment */ Java 4
Comments • Comments can not be put inside of another comment. • Comments are for the programmer only, they do not represent executable code. Vladimir Misic: vm@cs. rit. edu – The computer ignores comments. Java 5
Commenting Rules of Thumb • Do not state the obvious for self-evident information. For example if the code is: Vladimir Misic: vm@cs. rit. edu – 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 6
Vladimir Misic: vm@cs. rit. edu 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 7
Vladimir Misic: vm@cs. rit. edu 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 8
Vladimir Misic: vm@cs. rit. edu Javadoc Tags Java 9
Example /** * A class that manages a circle given the radius * @see java. lang. Math * @version 1. 0 * @author Paul Tymann */ public class Circle { Vladimir Misic: vm@cs. rit. edu private double radius; /** * Constructor for a circle. * * @param radius of the circle being created. * positive and greater than 0. * */ public Circle( double radius ) { this. radius = radius; } } Java 10 Must be
Vladimir Misic: vm@cs. rit. edu 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 java 2. Java 11
Vladimir Misic: vm@cs. rit. edu The Result Java 12
Java Classes Vladimir Misic: vm@cs. rit. edu • 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 13
Vladimir Misic: vm@cs. rit. edu 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 14
Vladimir Misic: vm@cs. rit. edu 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 15
Class Definition Vladimir Misic: vm@cs. rit. edu • All class definitions in Java have the following form: modifier class identifier { constant declarations class variable declarations instance variable declarations constructor declarations method declarations (class and instance) } Note: Top-level classes must be stored in a file named identifier. java Java 16
Class Modifiers • Top-level classes can optionally be declared as: Vladimir Misic: vm@cs. rit. edu Ø 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 17
Instance Variables Vladimir Misic: vm@cs. rit. edu • Instance variables form the state of an object. • An instance variable can be declared as final, meaning that it is a constant. public class Class 1 { public String hello = “Hello”; public final String world = “World”; protected int count = 0; private float length = 2. 345 f; } Java 18
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 Vladimir Misic: vm@cs. rit. edu – 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 19
Vladimir Misic: vm@cs. rit. edu 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 20
Method Declarations • The method declaration provides the function implementation in the program. Vladimir Misic: vm@cs. rit. edu <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 21
Vladimir Misic: vm@cs. rit. edu 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 22
Constructors • A constructor is a method that will be invoked, automatically, whenever an object is created Vladimir Misic: vm@cs. rit. edu 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 23
Constructors Vladimir Misic: vm@cs. rit. edu • 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 24
Default Constructor Example public class Point { Vladimir Misic: vm@cs. rit. edu private int x. Location; private int y. Location; // The X coordinate of this point // The Y coordinate of this point /** * Create a point at the origin ( x = y = 0 ) */ public Point() { x. Location = 0; y. Location = 0; } } Java 25
Other Constructors • You may also provide constructors that take arguments Vladimir Misic: vm@cs. rit. edu – 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 26
Constructor(s) Example public class Point { private int x. Location; private int y. Location; // The X coordinate of this point // The Y coordinate of this point /** * Create a point at the origin ( x = y = 0 ) */ Vladimir Misic: vm@cs. rit. edu public Point() { x. Location = 0; } Default constructor y. Location = 0; } /** * Create a point at the specified coordinate. * * @param x The X coordinate * @param y The Y coordinate */ public Point( int init. X, int init. Y ) { x. Location = init. X; y. Location = init. Y; Constuctor } overload public Point( double init. X, double init. Y ) { x. Location = (int) init. X; y. Location = (int) init. Y; } Java 27
Defining Behavior Vladimir Misic: vm@cs. rit. edu • 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 28
Vladimir Misic: vm@cs. rit. edu 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 29
Static or Class Variables Vladimir Misic: vm@cs. rit. edu • 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 30
Elevator public class Elevator { private static int next. Id = 0; public final static int UP = 0; public final static int DOWN = 1; Vladimir Misic: vm@cs. rit. edu private int direction = UP; private int my. Id; public Elevator() { my. Id = next. Id++; } public int get. Id() { return my. Id; } public int get. Direction() { return direction; } public void set. Direction( int dir ) { switch ( dir ) { case UP: case DOWN: direction = dir; } } } Java 31
Test. Elevator public class Test. Elevator { public static void main( String args[] ) { Elevator a = new Elevator(); Elevator b = new Elevator(); Elevator c = new Elevator(); Vladimir Misic: vm@cs. rit. edu a. set. Direction( a. DOWN ); // access through an object b. set. Direction( Elevator. DOWN ); // access through the class System. out. println( "Elevator A: Id=" + a. get. Id() + ", Dir=" + a. get. Direction() ); System. out. println( "Elevator B: Id=" + b. get. Id() + ", Dir=" + b. get. Direction() ); System. out. println( "Elevator C: Id=" + c. get. Id() + ", Dir=" + c. get. Direction() ); } } Java 32
Static Methods Vladimir Misic: vm@cs. rit. edu • 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. class. Method()) or by an object of the same class (class. Method) – 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 33
Vladimir Misic: vm@cs. rit. edu 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 34
Parameters • In a method declaration parameters (AKA, formal parameters) are used as place holders to indicate that arguments (AKA, actual parameters must be provided Vladimir Misic: vm@cs. rit. edu – 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 35
The Application Vladimir Misic: vm@cs. rit. edu public class Point. Test { public static void main( String args[] ) { Point my. Point = new Point(); Point other. Point = new Point( 12, 34 ); } } Java 36
The Implementation of the Class Vladimir Misic: vm@cs. rit. edu public class Point. Test { public static void main( String args[] ) { Point my. Point = new Point(); Point other. Point = new Point( 12, 34 ); } } public class Point { private int x. Location; private int y. Location; public Point() { x. Location = 0; y. Location = 0; } public Point( int init. X, int init. Y ) { x. Location = init. X; y. Location = init. Y; } } Java 37
Passing Parameters Vladimir Misic: vm@cs. rit. edu public class Point. Test { public static void main( String args[] ) { Point my. Point = new Point(); Point other. Point = new Point( 12, 34 ); } } init. X = 12; init. Y = 34; public class Point { private int x. Location; private int y. Location; public Point() { x. Location = 0; y. Location = 0; } public Point( int init. X, int init. Y ) { x. Location = init. X; y. Location = init. Y; } Note this is assignment, a copy of the arguments } Java 38
The Application public class Point. Test { public static void main( String args[] ) { int x. Location = 12; int y. Location = 34; Point other. Point = new Point( x. Location, y. Location ); System. out. println( x. Location ); System. out. println( y. Location ); } Vladimir Misic: vm@cs. rit. edu } Java 39
The Implementation of the Class public class Point. Test { public static void main( String args[] ) { int x. Location = 12; int y. Location = 34; Point other. Point = new Point( x. Location, y. Location ); System. out. println( x. Location ); System. out. println( y. Location ); } Vladimir Misic: vm@cs. rit. edu } public class Point { private int x. Location; private int y. Location; public Point() { x. Location = 0; y. Location = 0; } public Point( int new. X, int new. Y ) { x. Location = new. X; y. Location = new. Y; new. X = 0; new. Y = 67; } } Java 40
Passing Parameters public class Point. Test { public static void main( String args[] ) { int x. Location = 12; int y. Location = 34; Point other. Point = new Point( x. Location, y. Location ); new. X = x. Location; new. Y = y. Location; System. out. println( x. Location ); System. out. println( y. Location ); } Vladimir Misic: vm@cs. rit. edu } public class Point { private int x. Location; private int y. Location; Note these variables are not the same although they have the same name(s) public Point() { x. Location = 0; y. Location = 0; } public Point( int new. X, int new. Y ) { x. Location = new. X; y. Location = new. Y; new. X = 0; new. Y = 67; } } Java 41
Primitive vs. Complex Data Types • When you define a primitive data type (int, char, double, boolean) the memory location is allocated. Vladimir Misic: vm@cs. rit. edu – The number of bytes is always the same to store a value. – char let = 'A'; let Java 42 A
Primitive vs. Complex Data Types Vladimir Misic: vm@cs. rit. edu • 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 43
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. Vladimir Misic: vm@cs. rit. edu – The reference is the location of the first item in memory. – The information is stored sequentially beginning at the reference location. Java 44
Primitive vs. Complex Data Types name 0 name 1 Vladimir Misic: vm@cs. rit. edu • String name 0, name 1; • name 1 = "Rochester"; • name 0 = name 1; Java 45 2044 … R o c h e s t e r 1008 1012 2044 2048 2052 2056 2060
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 name 0 = name 1; Now name 1 and name 0 both point to memory location 2044. Vladimir Misic: vm@cs. rit. edu – – Java 46
Passing Objects to methods • Some of the String methods require a String as a parameter to the method. Vladimir Misic: vm@cs. rit. edu – For example, *. equals(String); – The method definition requires a String object to be passed to the method equals. Java 47
Passing Objects to methods – When we pass a String to a method we are passing it using call-by-reference. Vladimir Misic: vm@cs. rit. edu • 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 48
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. Vladimir Misic: vm@cs. rit. edu – 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 49
Returning Things from Methods • When a method returns an object, a memory reference is really returned. – Not the actual data. Vladimir Misic: vm@cs. rit. edu • When a method returns a primitive data type, then the actual value is returned. Java 50
UML for our Point class Point Vladimir Misic: vm@cs. rit. edu -x: double -y: double -number. Of. Points: int + means public - means private +Point( ) +Point( Point point ) +Point( double x, double y ) +get. Number. Of. Points(): int +distance. To(): double +distance. To( Point p ): double +distance. To( double x, double y): double +get. X( ): double +get. Y( ): double +move. TO( double x): void Java 51
- Slides: 51