Java Syntax - PowerPoint PPT Presentation

1 / 37
About This Presentation
Title:

Java Syntax

Description:

2nd Generation assembly language (mnemonic representation) ... (you should never hack code but unlike C, Java forces you to think about these issues) ... – PowerPoint PPT presentation

Number of Views:27
Avg rating:3.0/5.0
Slides: 38
Provided by: yvancar
Category:
Tags: hack | java | syntax

less

Transcript and Presenter's Notes

Title: Java Syntax


1
Java Syntax Classes
  • (A Quick Recap Explanation)
  • Yvan Cartwright yc1_at_staffs.ac.uk
  • www.soc.staffs.ac.uk/cmryjfc

2
But first a bit of background
  • 1st Generation machine language
  • (raw machine code)
  • 2nd Generation assembly language
  • (mnemonic representation)
  • 3rd Generation structured programming
  • (e.g. Pascal, C, C, Java)
  • 4th Generation application specific
  • (SQL, Mathematica, RPG II, PostScript)
  • 5th Generation combining artificial
    intelligence
  • (best not mentioned)
  • The aim is to have a programming language that is
    as close as possible to natural speech.

3
Structured Programming
  • As computer programs become larger and more
    complex, more errors are introduced.
  • It has been estimated that there 15 bugs in every
    1000 lines of commercial code.
  • Windows 2000 had 40 million lines of code!
  • Most bugs are caused by poor memory management.
  • Clearly there is a need for a structured
    programming language that helps in reducing the
    number of errors and speeds development for
    programming teams.
  • C ? C ? Java
  • Functional Programming ? Object Orientation
  • C makes it easy to shoot yourself in the foot
    C makes it harder, but when it happens you tend
    to take off the whole leg!

4
Java (why use it?)
  • Advantages over C C
  • Write once, run anywhere (portable).
  • Security (can run untrusted code safely).
  • Robust memory management (opaque references,
    automatic garbage collection)
  • Network-centric programming.
  • Multi-threaded (multiple simultaneous tasks).
  • Dynamic extensible.
  • Classes stored in separate files
  • Loaded only when needed
  • Can dynamically extend itself to expand its
    functionality (even over a network)

5
Java Syntax
  • A Quick Overview of the Basics

6
Primitive Types and Variables
  • boolean, char, int, long, float, double etc.
  • These basic (or primitive) types are the only
    types that are not objects (due to performance
    issues).
  • This means that you dont use the new operator to
    declare a primitive variable.
  • Declaring basic variables
  • float initVal
  • long firstNum, secondNum
  • int retVal, position 2
  • double gamma 1.2, brightness, contrast 100
  • boolean valueOk false
  • In Java, if no value is assigned during
    declaration then the value is set to zero (very
    handy) or false in the case of a boolean
    variable.
  • All object references are initially set to null
    (robust).

7
Incorrect Declarations
  • int index 1.2 // compiler error
  • float ratio 5.8 // compiler warning
  • boolean retOk 1 // compiler error
  • double fiveFourths 5 / 4 // no error or
    warning
  • Int index 1 // compiler error
  • float ratio 5.8f // correct
  • double fiveFourths 5.0 / 4.0 // correct
  • 1.2f is a float value accurate to 7 decimal
    places.
  • 1.2 is a double value accurate to 15 decimal
    places.
  • Due to the way fractional numbers are represented
    internally, the actual stored values are slightly
    different.

8
Assignment
  • All Java assignments are right associative.
  • float ratio circumference / diameter
  • int a b c
  • E.g.
  • int a 1, b 4, c 6
  • a b c
  • System.out.print(a a b b c
    c
  • What is the value of a, b c?

a, b c all equal 6. All assignments are
performed right-to-left. a b c is the same as
a (b c)
9
Basic Mathematical Operators
  • / - are the standard mathematical
    operators.
  • All have left to right associativity.
  • / have a higher precedence than or -.
  • E.g.
  • double myVal a b d c d / b
  • Is the same as
  • double myVal (a (b d)) ((c d) / b)
  • Although parentheses are not usually required
    they make the code more readable and can help to
    prevent errors (and many lost hours debugging!).

10
Statements
  • A statement is a single command that is executed
    by the Java interpreter.
  • By default, Java executes one statement after the
    other in the order they are written.
  • Many Java statements are flow control statements.
  • E.g.
  • if, if else, else if
  • switch
  • for
  • while, do while
  • break
  • continue
  • return

11
If The Conditional Statement
  • The if statement evaluates an expression and if
    that evaluation is true then the specified action
    is taken.
  • E.g.
  • if ( x lt 10 ) x 10
  • If the value of x is less than 10, make x equal
    to 10.
  • This is an example of a one line if statement.
  • It could have been written
  • if ( x lt 10 )
  • x 10
  • Or, alternatively
  • if ( x lt 10 )
  • x 10

12
If / Else
  • The if / else statement evaluates an expression
    and performs one action if that evaluation is
    true or a different action if it is false.
  • E.g.
  • if (x lt 10 )
  • x 10
  • System.out.print(x was changed)
  • else
  • System.out.print(x is unchanged)

13
Nested If / Else
  • It is possible to place if statements (and if /
    else statements) inside other conditional
    statements.
  • E.g.
  • if ( myVal gt 100 )
  • if ( remainderOn true)
  • myVal mVal 100
  • else
  • myVal myVal / 100.0
  • else System.out.print(myVal is in range)

14
Else If
  • Useful for choosing between several possible
    actions.
  • E.g.
  • if ( n 1 )
  • // execute code block 1
  • else if ( j 2 )
  • // execute code block 2
  • else
  • // if all previous tests have failed, execute
    code block 3

15
Now a Warning
  • There are many common errors made using if /
    else
  • E.g.
  • if ( i j )
  • if ( j k )
  • System.out.print(i equals k)
  • else
  • System.out.print(i is not equal to j) //
    Wrong!
  • if ( i j )
  • if ( j k )
  • System.out.print(i equals k)
  • else
  • System.out.print(i is not equal to j) //
    Correct!

16
The Switch Statement
  • When using multiple else if statements which
    depend upon the value of a single variable, it is
    more efficient to use switch.
  • E.g.
  • switch ( n )
  • case 1
  • // execute code block 1
  • break
  • case 2
  • // execute code block 2
  • break
  • case 3
  • // execute code block 3
  • break
  • default
  • // if all previous tests fail then execute code
    block 4
  • break

17
The Fall-Through Switch
  • switch ( response )
  • case y
  • case Y
  • // execute code block 1
  • break
  • case b
  • // execute code block 2
  • return
  • case n
  • case N
  • // execute code block 3
  • break
  • default
  • // execute code block 4
  • break

18
For The Deterministic Loop
  • A deterministic loop is a series of actions that
    will be repeated for a pre-specified number of
    times.
  • E.g.
  • for ( int index 1 index lt 10 index )
  • // this code body will execute 9 times
  • Nested for
  • for ( j 0 j lt 10 j )
  • for ( i 0 i lt 20 i )
  • // this code body will execute 200 times

19
Non-Deterministic Loops
  • A non-deterministic loop is a series of actions
    that will be repeated as specified during
    execution.
  • There are two similar methods for specifying a
    non-deterministic loop, the while and do / while
    statements.
  • E.g.
  • while( (response 1) (n lt maxID) )
  • System.out.print( ID userIDn )
  • n
  • response Console.readInt( Enter option )

20
Do / While
  • do / while is very similar to while.
  • The only difference is that a while loop may not
    execute at all whereas a do / while loop will
    execute at least once.
  • E.g.
  • do
  • System.out.print( ID userIDn )
  • n
  • response Console.readInt( Enter option )
  • while ( (response 1) (n lt maxID) )

21
Break
  • This can be a source of much confusion!
  • A break statement causes the Java interpreter to
    exit the innermost containing while, do, for or
    switch statement.
  • E.g.
  • for ( int i 0 i lt maxID, i )
  • if ( userIDi targetID )
  • index i
  • break
  • // the Java interpreter jumps to here after
    break

22
Labelled Break
  • An alternative to the standard break is the
    labelled break.
  • testforIndex if ( userID ! null )
  • for ( j 0 j lt maxjID j )
  • for ( i 0 i lt maxiID i )
  • if ( userIDij targetID )
  • indexi i
  • indexJ j
  • break testforIndex
  • // Java interpreter jumps to here after break

23
Continue
  • Another source of confusion.
  • Can only be used with while, do or for.
  • The continue statement causes the innermost loop
    to start the next iteration.
  • E.g.
  • for ( int i 0 i lt maxID i )
  • if ( userIDi ! -1 ) continue
  • System.out.print( UserID i
    userID)

24
Return
  • A return statement tells the Java interpreter to
    stop executing the current method and jump back
    to continue executing the calling statement.
  • Up to one value (or object) can be passed back
    from a method via the return mechanism.
  • E.g.
  • int findIndex()
  • for ( i 0 i lt maxID i )
  • if ( userIDi targetID) return i
  • return 1

25
Java Methods Classes
26
Methods
  • A method is a named sequence of code that can be
    invoked by other Java code.
  • A method performs some computations and then
    optionally returns a value (or object).
  • Methods can be used as part of an expression
    statement.
  • E.g.
  • float tFahrenheit convertCelsius ( tCelsius )
  • float convertCelsius( float tempC )
  • return( ((tempC 9.0f) / 5.0f) 32 )

27
Method Signatures
  • A method signature specifies
  • The name of the method.
  • The type and name of each parameter.
  • The type of the value (or object) returned by the
    method.
  • The checked exceptions thrown by the method.
  • Various method modifiers.
  • E.g.
  • modifiers type name ( parameter list ) throws
    exceptions
  • public float convertCelsius ( float tCelsius )
  • public boolean setUserInfo ( int i, int j, String
    name ) throws IndexOutOfBoundsException

28
Object Orientation
  • So far, all of this seems very similar to C. It
    is but!
  • C was the language of choice for commercial
    coding for many years.
  • It is fast, flexible and very powerful.
  • It also makes it very easy for large programs to
    become unmanageable (especially for groups of
    coders) and prone to memory errors.
  • It is very easy for a programmer to inadvertently
    change data in another part of the code or use
    short-cuts instead of a more formal system.
  • All non-object oriented languages are concerned
    with the functional aspects of the code not the
    data.
  • However, the data is more important than the code!

29
Data is King!
  • When designing code around a customers
    specification (written in a natural language), it
    is more realistic to talk in terms of objects.
  • In engineering, when designing a new car, a
    designer talks about engines, tyres, electrical
    systems, hydraulics etc.
  • These are things (objects), not functions.
  • C is C with object orientation bolted on.
  • Java was designed from the ground up to be an
    object oriented language thereby providing a more
    consistent programming experience.

30
Java Classes
  • If attributes (data) are more important than
    methods (functions), then mechanisms must be in
    place to safely access and change attributes.
  • To prevent the inadvertent changing of
    attributes, it is best to encapsulate attributes
    into related entities.
  • In Java (like C), a collection of attributes
    and methods is called a class.
  • Classes are the most fundamental structural
    element of all Java programs.

31
An Example Class
  • public class Point
  • public double x, y // public attributes
  • private int size // private attribute
  • public Point() // constructor to initialise
    attributes
  • // must have same name as class
  • x 0
  • y 0
  • size 1
  • public double getSize() // accessor method
  • return size
  • public void setSize(int newSize) // mutator
    method

32
Using the Class
  • public class PointWrapper
  • public static void main( String args )
  • Point testPoint new Point()
  • testPoint.x 12.5
  • testPoint.y 20.2
  • System.out.print( X testPoint.x ) // ok
  • System.out.print( Y testPoint.y ) // ok
  • testPoint.size 2 // compiler error
  • System.out.print( Size testPoint.size) //
    compiler error
  • testPoint.setSize( 2 ) // ok
  • System.out.print( Size testPoint.getSize())
    // ok

33
Multiple Classes
  • Most real programs have many classes.
  • It is important to design how these classes
    relate to each other before any coding is
    performed (you should never hack code but unlike
    C, Java forces you to think about these issues).
  • Consider the following simple example
  • A customer wants a program to display 100 points
    of increasing sizes on the screen in random
    locations. Also the colour of the point should
    increase from black to red as the point size
    increases.

34
Design
  • You already have a class that handles the
    position and size of a point on the screen. It
    has undergone rigorous testing so you dont want
    to write a new one.
  • As an object oriented language, java permits you
    to reuse and extend the functionality of code you
    have already created.
  • You could extend the Point class or you could
    create a new class that incorporates your
    existing Point class.

35
Class Within a Class
  • public class ColouredPoint
  • public Point myPoint
  • private float red
  • public ColouredPoint( float redValue )
  • this.red redValue
  • myPoint new Point()
  • public void setRandomPosition()
  • myPoint.x (int)(Math.random() (400 1))
  • myPoint.y (int)(Math.random() (400 1))
  • public void increasePointSize( int newSize )

36
  • public class PointWrapper
  • public static void main( String args )
  • ColouredPoint pointArray new
    ColouredPoint100
  • for( int i 0 i lt 100 i)
  • pointArrayi new ColouredPoint(i/100.0f)
  • pointArrayi.setRandomPosition()
  • pointArrayi.increasePointSize(i)
  • displayPoint(pointArrayi)
  • public static void displayPoint(ColouredPoint
    point)
  • / display code /

37
One Final Thing
  • Be careful when copying variables!
  • E.g.
  • int x 42
  • int y x
  • y contains a copy of the value stored in x (there
    are effectively two separate variables with their
    own distinct values).
  • Changing y will not change x.
  • Point p new Point( 1.0, 2.0 )
  • Point q p
  • q contains a copy of the reference held in the
    variable p.
  • Changing q will also change p!
Write a Comment
User Comments (0)
About PowerShow.com