Skip to content Skip to navigation

Connexions

You are here: Home » Content » Java Syntax Primer

Navigation

Lenses

What is a lens?

Definition of a lens

Lenses

A lens is a custom view of Connexions content. You can think of it as a fancy kind of list that will let you see Connexions through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to Connexions materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual Connexions member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

This content is ...

Affiliated with (What does "Affiliated with" mean?)

This content is either by members of the organizations listed or about topics related to the organizations listed. Click each link to see a list of all content affiliated with the organization.
  • OrangeGrove display tagshide tags

    This module is included inLens: Florida Orange Grove Textbooks
    By: Florida Orange GroveAs a part of collection:"Principles of Object-Oriented Programming"

    Click the "OrangeGrove" link to see all content affiliated with them.

    Click the tag icon tag icon to display tags associated with this content.

Also in these lenses

  • SHN CNX Workshop display tagshide tags

    This module is included inLens: Stategic Horizon Network Workshop on Alternative Couseware -- Connexions Session
    By: ConnexionsAs a part of collection:"Principles of Object-Oriented Programming"

    Click the "SHN CNX Workshop" link to see all content selected in this lens.

    Click the tag icon tag icon to display tags associated with this content.

  • eScience, eResearch and Computational Problem Solving

    This module is included inLens: eScience, eResearch and Computational Problem Solving
    By: Jan E. OdegardAs a part of collection:"Principles of Object-Oriented Programming"

    Click the "eScience, eResearch and Computational Problem Solving" link to see all content selected in this lens.

Recently Viewed

This feature requires Javascript to be enabled.

Tags

(What is a tag?)

These tags come from the endorsement, affiliation, and other lenses that include this content.

Java Syntax Primer

Module by: Stephen Wong, Dung Nguyen. E-mail the authors

User rating (How does the rating system work?)
Ratings

Ratings allow you to judge the quality of modules. If other users have ranked the module then its average rating is displayed below. Ratings are calculated on a scale from one star (Poor) to five stars (Excellent).

How to rate a module

Hover over the star that corresponds to the rating you wish to assign. Click on the star to add your rating. Your rating should be based on the quality of the content. You must have an account and be logged in to rate content.

:
(0 ratings)

Summary: An introduction to Java syntax covering simple Java expressions and the declaration of concrete classes and methods.

General:

A Java program consists of one or more classes one of them must be public and must have a method with the following signature:

public static void main (String[] args)

Basically, the main() method will instantiate appropriate objects and send them "messages" (by calling their methods) to perform the desired tasks.  The main() method should not contain any complicated program logic nor program flow control. In the example shown below, PizzaClient is the main class with the main() method.

Figure 1: UML Class Diagram of a Java program
Figure 1 (graphics1.png)

 Example:

public class PizzaClient {
    /**
     * Prints the answer to the problem stated in the above.. 
     */
    public void run() {

        Pizza round = new Pizza (3.99, new Circle (2.5));
        Pizza rect =  new Pizza (4.99, new Rectangle (6, 4));

        PizzaDeal pd = new PizzaDeal();

        System.out.println(round + " is a better deal than " + rect + ": " +
                           pd.betterDeal(round, rect));

    }

    /**
    * Main entry to the program to find the better deal.
    * Instantiates an instance of PizzaClient and tells it to run.
    * This is what all main() should do: instantiates a bunch of objects and
    * "turn them loose"!
    * There should be no complicated logic and/or control in main().
    * @param nu not used
    */
    public static void  main (String[] nu) {
        new PizzaClient().run();
    }
}

public class Rectangle implements IShape {

    private double _width;
    private double _height;

    /**
    * Initializes this Rectangle width a given width and a given height
    * @param w width of this Rectangle, >= 0.
    * @param h height of this Rectangle, >= 0.
    */
    public Rectangle(double w, double h) {
        _height  = h;
        _width   = w;
    }

    /**
    *  @returns this Rectangle's area.
    */
    public double getArea() {
        return _height * _width;
    }

    /**
    * Overrides the inherited method from class Object.
    * @returns a String describing a Rectangle with its width and height.
    */
    public String toString() {
        return "Rectangle(h = " + _height + ", w = " + _width + ")";
    }
}

Notes on the toString() method:

toString() is a method that is inherited all the way from the base class, Object. It is the method that the Java system calls by default whenever a string representation of the class is needed. For instance, "This is "+ myObject is equivalent to "This is " + myObject.toString(). DrJava will call an object's toString() method if you type the object's name in the interaction window, without terminating the line with a semicolon. The return value of toString() is what prints out on the next line.

Comments syntax:

// Line-oriented - comment goes to end of the current line.

/*
    block-oriented
    can span several lines.
*/
    

Class definition syntax:

[…] means optional.

[public] class class-name [inheritance-specification] {
    [field-list;]
    [constructor-list;]
    [method-list;]
    

}

Inheritance Specification looks like

[extends SomeClass] [implements Interface1,..., InterfaceN]

We will discuss the meaning of inheritance in due time.

Java Statement syntax:

Note:

Each Java statement must terminate with a semi-colon. 

Field list syntax:

A field list consists of zero or more field declarations of the form

[static] [final] [public | private | protected] field-type field-name [assignment];

 

Constructor list syntax:

A constructor list consists of zero or more constructor definitions of the form

[public | private | protected] class-name ([parameter-list]){
    [statement-list;]
}
    

Note:

The constructor's name must the same as the class name. Constructors are used for initialization of the object during the object's instantiation only.

Method list syntax:

A method list consists of zero or more method definitions of the form

[static] [final] [public | private | protected]
    return-type method-name ([param-list]) {
        [statement-list;]
    }
    

A return type void means the method does not return any value.

param-list can be:

  • empty;

for example,

public double getArea() {
    // code ...
}
    
  • of a fixed number of parameters

type1 param1, type2 param2, ... , typeN paramN

for example,

private void doSomethingWith(int n, double x, Pizza p) {
    // code ...
}
    
  • of a variable number of parameters (this is a new feature for Java 5.0 and upward)
type1 param1, type2 param2, .., typeN... params
    

In the above, typeN... params is called a variable argument list.  It must appear at the end of the whole parameter list.

for example,

private void doSomethingWith(int n, double x, Pizza... p) {
    // code ...
}
    

The variable argument list can have zero or more arguments.  Here is a simple example:  use DrJava to define the following class in the definition pane.

public class VarArgExample {
    /**
    * returns the number of arguments in the variable argument list.
    */
    int argNum(int... nums) {
        return nums.length; // the var arg list is viewed as an array
    }
}
    

Compile the above class and in the interactions pane, type the following:

VarArgExample vae = new VarArgExample(); // creates a VarArgExample object
    vae.argNum() // returns 0
    vae.argNum(42) // returns 1
    vae.argNum(34, -99) // returns 2
    
    

Content actions

Give Feedback:

E-mail the module authors | Rate module ( How does the rating system work?)

Rating system

Ratings

Ratings allow you to judge the quality of modules. If other users have ranked the module then its average rating is displayed below. Ratings are calculated on a scale from one star (Poor) to five stars (Excellent).

How to rate a module

Hover over the star that corresponds to the rating you wish to assign. Click on the star to add your rating. Your rating should be based on the quality of the content. You must have an account and be logged in to rate content.

(0 ratings)

Download:

Add module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections directly in Connexions. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need a Connexions account to use 'My Favorites'.

| A lens (?)

Definition of a lens

Lenses

A lens is a custom view of Connexions content. You can think of it as a fancy kind of list that will let you see Connexions through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to Connexions materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual Connexions member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks