Java Basics - for RoboCup Lab -

advertisement

Java Basics

- for RoboCup Lab -

Aleksandra Tešanovi ć (alete@ida.liu.se)

Calin Curescu (calcu@ida.liu.se)

Real-Time Systems Laboratory

Department of Computer and Information Science

Linköping University

October 2005

This Lesson

„

Gives an introduction to Java language

„

Provides an overview over basic knowledge required by unskilled Java programmers to program the RoboCup lab assignments with success

„

Focuses on specific issues required for programming the RoboCup lab assignments

„

Tailored for students that have some experience with object-oriented programming (e.g., C++)

1

Motivation: RoboCup Lab

Lesson Content

„

„

Java overview and features

Control Statements

„

„

Variables

Classes and inheritance

„

„

Type conversion

Operator summary

„

„

Compiling and running programs

Resources

2

Java Programming: an Overview

Java Programming myScheduler.java

compiler myScheduler.class

Java Platform program bytecode

Java Virtual

Machines

(JVM) interpreter my scheduler interpreter my scheduler myScheduler.java

Java API

(+RoboCup API)

_______________

JVM

Hardware Platform

Java (+RoboCup)

Platform

Windows Solaris

Java Features

„

„

„

„

„

Object oriented language

Interpreted at runtime

Garbage collection

… Java runtime environment deletes objects that are no longer being used different than in C++!

… automatic deletion of objects=> no deconstructors

Strong type checking

Exception handling

3

Control Flow statements

„

„

Loops

… while, do…while , for similar to C and C++!

Branching

… if…else, switch…case

„

Exceptions

… try…catch…finally, throw, throws

„

Aborts

… break, continue, label:, return

… Scope of these is block dependent

Classes

public class Scheduler{ public string PolicyName; public Scheduler() {this(true);}

Variable

Constructor

} public void fireThread(RealtimeThread s){ s.run();

}

„

„

„

„

Method constructor does not have to be specified

…

… system uses default constructor default constructor does nothing classes have modifiers

… public, protected, private a class is an implementation of an interface

… interface is Java’s response to multiple inheritance public static void main(String[] args)

… method used for executing a program similar to C++!

CLASS

4

Variables in Java

„ declaration: type name

RLThread newThread

„

„

„ can be declared as static

… class-wide, same value for all instance of the class have modifiers

… access modifiers: public, protected, private

… static, final, transient, volatile are valid within a scope similar to C++!

Class member variable scope class Scheduler{ public string PolicyName;

Method Parameter public void fireThread

(RealtimeThread s)

{

...

if (..)

{ int i=7;

}

Scope

Local block variable scope

}

System.out.println("The value of i = "+i);

} Error

(”i” does not exist out of scope)

Variable Types

„

Primitive type

… byte,short, int, long

… float double

… char, boolean double missedDeadlines= 0.0; manipulation of the value!

similar to C++!

„

Reference type

… reference is a memory address (pointer in C++) different than in C++!

RTLThread newThread; manipulation of the address!

… arrays are objects and are of reference type

… all objects are manipulated by Java using their references!

5

Object Creation

„ are created from a class (as you know)

AbsoluteTime abs= new AbsoluteTime(); class object name allocates space for an object constructor

„ used as in C++ objectReference.variableName

… manipulate or inspect its variables

… call its methods

„ remember that objects are of reference type

Methods

„ represent the behavior of a class class Scheduler{ public string PolicyName;

} public void fireThread(RealtimeThread s){ s.run();

} modifier output input

„ have parameters

… several input

… one output (return)

„ and modifiers

… public, protected, private

… static, final, synchronized, native

OBS! Value of the pointer is passed if an input parameter is an object !

6

Example

public void tricky(Point arg1, Point arg2) {

Point temp = arg1; arg1 = arg2; arg2 = temp; arg2.x = 200;

}

What is the value of p1.x, p2.x after the following sequence of statements?

p1.x = 50; p2.x = 100; tricky(p1,p2);

Inheritance

public class EarliestDeadlineFirstScheduler extends Scheduler{…}

„

Subclass

(EarliestDeadlineFirstScheduler) inherits all members of superclass

(Scheduler)

„

Exceptions to inheritance are when

… members are not accessible (i.e., private)

… members are explicitly overridden (i.e., redefined) in subclass

„

Constructors are not inherited

… since they are not members of a class

7

Type Conversions (Casting)

„

Object casting!

Upcast (widening conversion)

… from subclass to ancestor

… usually automatic; always safe

„

Downcast (narrowing conversion)

… from ancestor to subclass

… checked at runtime for validity

… if not an instance – an Exception is thrown

„

”instanceof” operator can be used to check if an object belongs to a class

Operators

Priority Operators

[ ]

1

()

.

2

3

4

5

6

++

--

Operation array index method call member access pre- or postfix increment pre- or postfix decrement unary plus, minus + -

~

!

bitwise NOT boolean (logical) NOT type cast

(type)

New

+ -

* / % object creation multiplication, division, remainder addition, substraction string concatenation

+

<<

>> signed bit shift left signed bit shift right

>>>

< <=

> >=

Instanceof unsigned bit shift right less than, less than or equal to greater than, greater than or equal to reference test

Associativity left right left left left left

Priority

7

8

9

10

11

12

13

14

Operators

==

Operation equal to

!= not equal to

&&

||

|

|

&

&

^

^ bitwise AND boolean (logical) AND bitwise XOR boolean (logical) XOR bitwise OR boolean (logical) OR boolean (logical) AND boolean (logical) OR

? :

= conditional assignment

*= /= += -= %= <<=

>>= >>>= &= ^= |= combinated assignment

(operation and assignment)

Associativity left left left left left left right right

8

RoboCup Example 1

Class

HighResolution

Time

Relevant Members setTime(HighResolutionTi me new)

Subclass

AbsoluteTime

Relevant members

....

ReleaseParamet ers

.....

PeriodicParameters

...

...

AbsoluteTime getStart()

RealtimeThread

ReleaseParameters getReleaseParameters()

....

RLThread ....

ThreadNode ....

RMThreadNode

AbsoluteTime deadline

AbsoluteTime nextRelease

Assume:

RLThread[] threadList=(RLThread[]) getThreads(); threadNode= new RMThreadNode(threadList[i]) ;

How can we set the next release time of the threadNode (using setTime ). The value of the (old) release time of the thread can be obtained using getRealeseParameters.

What should follow?

RoboCup Example 1

This statement: threadNode.nextRelease.setTime(((PeriodicParameters)threa dList[i].getReleaseParameters()).getStart());

...is equivalent with:

AbsoluteTime nextRel = threadNode.nextRelease; RLThread thr

= threadList[i];

ReleaseParameters ppo = thr.getReleaseParameters();

PeriodicParameters pp = (PeriodicParameters)ppo;

AbsoluteTime sTime = pp.getStart(); nextRel.setTime(sTime);

When not sure use ”()” to enforce presedence.

Expression between ”()” is always evaluated first!

9

RoboCup Example 2

Subclass Class

PlannerControl

Relevant Members restart()

ThreadNode ....

RMThreadNode

Additional members

AbsoluteTime deadline

AbsoluteTime nextRelease

Assume:

RLThread[] threadList=(RLThread[]) getThreads(); threadNode= new RMThreadNode(threadList[i]) ;

How can we restart the planner of the threadNode in the list ?

What should follow?

Other examples

What is the result of the following statements?

„

„ if(!t.isGreater(a.deadline)&&b<a+c) {...}

System.out.println(”temperature is ”+3+2);

„

„

System.out.println(”temperature is

”+(3+2));

(PlannerControl)threadList[1].restart();

„

((PlannerControl)threadList[1]).restart();

10

Code Organization

„

Each class is in its own .java file

… ClassName has to be the same as FileName in CyclicScheduler.java: public class CyclicScheduler extends BasicScheduler

… exception is that inner classes contained wihin the class do not have its own .java file

„

Related classes are grouped in packages”

…

…

… in CyclicScheduler.java: package rt; similar to namespaces in C++ packages are structured hierarchically each .java file should start with the declaration of the package import soccorob.rt.*; import soccorob.ai.agent.*; public class CyclicScheduler extends BaseCyclicScheduler {

„

Import allows you to use short names for classes

Compiling (*.java Æ *.class)

„ correct compiling depends on setting the CLASSPATH environment variable

… points to the directories under which the compiler can find classes on which new compiled class depends

In Windows: set CLASSPATH=%CLASSPATH %;c:\ programs\Robolab;z:\robolab

„

Class files must respect the package hierarchy

„ class rt.CyclicScheduler should be in CLASSDIR\rt\, where

CLASSDIR is contained in CLASSPATH

„

Compiling command example javac [–classpath C:\programs\Robolab] CyclicScheduler.java

… ”-classpath ...” option can be used instead of the CLASSPATH variable

11

Running the program

„

Result of the compilation is a .class file

… sorted in the same directory as the source file

„

Can be changed with ”–d DestinationDirectory”

„ command for running the program

… java myPackage.ClassName

Example with this and super

this

…

Can be used to access methods or fields

… Reference to “this ” object can be in a return statement super

… Only for accessing the parent’s methods or fields public class HelloWorld extends Hello {

String msg; public HelloWorld(String message) { super(message); msg = message;

} public HelloWorld() { this("hello world");

} public void changeMsg(msg) { this.msg = msg;

} public HelloWorld returnMe() { return this;

}

}

12

Printing

„

Standard I/O: stdin, stdout, stderr

… defined in java.lang.System

object as public static final InputStream in; public static final PrintStream out;

„

Example

String mes1 = ”Hello World\nSecond line:”;

String mes2 = ”\tValue of ion =”

String mes3 = mes1 + mes2; int ion = 3;

System.out.println(mes3);

System.out.println(mes2 + ion);

Escape codes for unprintable characters:

\b - Backspace

\t - Tab

\n - Newline

\f - Form feed

\r - Carriage return

\‘ - Single quote

\” - Double quote

\\ - A backslash

\nnn - The character with octal value nnn

('\012' == '\n')

Resources

„

On-line tutorials

…

Help you to learning the Java language

„

… Provide explantions for essential Java classes

… Available at http://java.sun.com/docs/books/tutorial/

Other available material at IDA

… Introduction to Java

… Available at http://www.ida.liu.se/~TDDI48/intro.pdf

13

Next Lesson

„

Introduces RoboCup Real-Time

Scheduling Lab

… Environment: software and hardware

… RoboCup Lab assignments

„

„

Provides really good help for successful completions of the lab assignments

Scheduled for November 4th 15-17

14

Download