1 / 51

Basic Java Syntax

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 ).

riva
Download Presentation

Basic Java Syntax

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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. 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" ); } } Java

  3. 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. Comments • Comments come in three forms: // single line comments /* multi line comment */ /** a * Javadoc * comment */ Java

  5. 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. 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. 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. 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. Javadoc Tags Java

  10. 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; } } Java

  11. 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. The Result Java

  13. 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. 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. 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. 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 Java

  17. 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. 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; } Java

  19. 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. 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. 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. 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. 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. 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. 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; } } Java

  26. 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. Constructor(s) Example Default constructor Constuctor overload 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; } } Java

  28. 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. 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. 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 = constantand static = global) • Static variables must be explicitly initialized (because no constructor can do it). Java

  31. 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; } } } Java

  32. 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() ); } } Java

  33. 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. 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. 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. The Application public class PointTest { public static void main( String args[] ) { Point myPoint = new Point(); Point otherPoint = new Point( 12, 34 ); } } Java

  37. The Implementation of the Class public class PointTest { public static void main( String args[] ) { Point myPoint = new Point(); Point otherPoint = new Point( 12, 34 ); } } 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; } } Java

  38. Passing Parameters public class PointTest { public static void main( String args[] ) { Point myPoint = new Point(); Point otherPoint = new Point( 12, 34 ); } } 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 Java

  39. 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. The Implementation of the Class 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 ); } } 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; } } Java

  41. Passing Parameters 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; 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; } } Note these variables are not the same although they have the same name(s) Java

  42. 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. 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. 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. Primitive vs. Complex Data Types • String name0, name1; • name1 = "Rochester"; • name0 = name1; 1008 name0 2044 name1 2044 1012 … 2044 R o c h 2048 e s 2052 t e 2056 r 2060 Java

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

More Related