Presentation is loading. Please wait.

Presentation is loading. Please wait.

Vladimir Misic: Java1 Basic Java Syntax The java language will be described by working through its features: –Variable types and expressions.

Similar presentations


Presentation on theme: "Vladimir Misic: Java1 Basic Java Syntax The java language will be described by working through its features: –Variable types and expressions."— Presentation transcript:

1 Vladimir Misic: vm@cs.rit.edu Java1 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 )

2 Vladimir Misic: vm@cs.rit.edu Java2 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" ); }

3 Vladimir Misic: vm@cs.rit.edu Java3 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.

4 Vladimir Misic: vm@cs.rit.edu Java4 Comments Comments come in three forms: // single line comments /* multi line comment */ /** a * Javadoc * comment */

5 Vladimir Misic: vm@cs.rit.edu Java5 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.

6 Vladimir Misic: vm@cs.rit.edu Java6 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.

7 Vladimir Misic: vm@cs.rit.edu Java7 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.

8 Vladimir Misic: vm@cs.rit.edu Java8 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.

9 Vladimir Misic: vm@cs.rit.edu Java9 Javadoc Tags

10 Vladimir Misic: vm@cs.rit.edu Java10 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; }

11 Vladimir Misic: vm@cs.rit.edu Java11 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.

12 Vladimir Misic: vm@cs.rit.edu Java12 The Result

13 Vladimir Misic: vm@cs.rit.edu Java13 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).

14 Vladimir Misic: vm@cs.rit.edu Java14 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

15 Vladimir Misic: vm@cs.rit.edu Java15 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.

16 Vladimir Misic: vm@cs.rit.edu Java16 Class Definition 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

17 Vladimir Misic: vm@cs.rit.edu Java17 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.

18 Vladimir Misic: vm@cs.rit.edu Java18 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; }

19 Vladimir Misic: vm@cs.rit.edu Java19 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

20 Vladimir Misic: vm@cs.rit.edu Java20 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.

21 Vladimir Misic: vm@cs.rit.edu Java21 Method Declarations The method declaration provides the function implementation in the program. ( ) { } 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.

22 Vladimir Misic: vm@cs.rit.edu Java22 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!

23 Vladimir Misic: vm@cs.rit.edu Java23 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

24 Vladimir Misic: vm@cs.rit.edu Java24 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.

25 Vladimir Misic: vm@cs.rit.edu Java25 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; }

26 Vladimir Misic: vm@cs.rit.edu Java26 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

27 Vladimir Misic: vm@cs.rit.edu Java27 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

28 Vladimir Misic: vm@cs.rit.edu Java28 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

29 Vladimir Misic: vm@cs.rit.edu Java29 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.

30 Vladimir Misic: vm@cs.rit.edu Java30 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).

31 Vladimir Misic: vm@cs.rit.edu Java31 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; }

32 Vladimir Misic: vm@cs.rit.edu Java32 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() ); }

33 Vladimir Misic: vm@cs.rit.edu Java33 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

34 Vladimir Misic: vm@cs.rit.edu Java34 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.

35 Vladimir Misic: vm@cs.rit.edu Java35 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

36 Vladimir Misic: vm@cs.rit.edu Java36 The Application public class PointTest { public static void main( String args[] ) { Point myPoint = new Point(); Point otherPoint = new Point( 12, 34 ); }

37 Vladimir Misic: vm@cs.rit.edu Java37 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 ); }

38 Vladimir Misic: vm@cs.rit.edu Java38 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 ); }

39 Vladimir Misic: vm@cs.rit.edu Java39 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 ); }

40 Vladimir Misic: vm@cs.rit.edu Java40 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 ); }

41 Vladimir Misic: vm@cs.rit.edu Java41 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 same although they have the same name(s)

42 Vladimir Misic: vm@cs.rit.edu Java42 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'; letA

43 Vladimir Misic: vm@cs.rit.edu Java43 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.

44 Vladimir Misic: vm@cs.rit.edu Java44 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.

45 Vladimir Misic: vm@cs.rit.edu Java45 Primitive vs. Complex Data Types String name0, name1; name1 = "Rochester"; name0 = name1; name120441012 … 2044 2048 R o c h e s t e r 2052 2056 2060 name02044 1008

46 Vladimir Misic: vm@cs.rit.edu Java46 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.

47 Vladimir Misic: vm@cs.rit.edu Java47 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.

48 Vladimir Misic: vm@cs.rit.edu Java48 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.

49 Vladimir Misic: vm@cs.rit.edu Java49 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.

50 Vladimir Misic: vm@cs.rit.edu Java50 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.

51 Vladimir Misic: vm@cs.rit.edu Java51 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 + means public - means private


Download ppt "Vladimir Misic: Java1 Basic Java Syntax The java language will be described by working through its features: –Variable types and expressions."

Similar presentations


Ads by Google