Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Agenda
Introduction to Java (today)
What is Java? Tools Overview Language Overview
What is Java?
A concurrent, object-oriented programming language (OOPL) A virtual machine (run-time environment)
can be embedded in web browsers (e.g. Netscape Navigator, Microsoft Internet Explorer and IBM WebExplorer) and operating systems.
Smalltalk
Similar object model (single-rooted inheritance hierarchy, access to objects via reference only) Compiled to a byte-code (initially interpreted) Dynamic loading Garbage collection
javac
Java VM
.class files interpret Java Runtime call Native .dll Native .dll loaded classes (byte-codes) load
Networking
Library supports retrieving files, images, etc. via URL Clean support for sockets providing access to Internetbased services VM can dynamically load classes over the Internet
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
Agenda
Introduction to Java (today)
What is Java? Tools Overview Language Overview
JDK Tools
Java Developers Kits (JDK) three main tools are:
javac the Java compiler java VM for running stand-alone Java applications appletviewer a utility to view applets
JIT Compiler
Although Java is interpreted, Just-In-Time compilers provide client-side compilation of byte-codes to machine code (native binary) This provides:
Improved performance Better match to specific hardware
10
Eclipse
jdt: java development tools subproject
Plug-ins for Java development
11
Agenda
Introduction to Java (today)
What is Java? Tools Overview Language Overview
12
Language Overview
Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++
13
Java Programs
Two broad categories of program can be written Applet
a Java program that runs inside a Java-enabled Web browser.
Application
a Java program run via the java command.
Analysis
import java.io.*; /** File: Count.java*/ public class Count {` public static void main (String[] s) throws IOException { int count = 0; while (System.in.read() != -1) count++; System.out.println("Input has "+count+" chars"); } }
All Java code is contained within classes. Java classes consist of fields (variables) and methods. A Java source file contains at most one public class. Applications must provide a method called main. To be recognized, the main method must have the correct method signature. Java stores collections of classes in packages (class libraries). The import keyword selects the packages available.
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
Comments
There are different types of comments
// single line comment (until eol) /* single/multi-line comment (do not nest) */ /** multi-line documentation comment. Use immediately before class, method, and variable declaration. The javadoc utility will use this comment to automatically generate HTML. May also include HTML and use optional tags: <B> Here is a bolded comment <\B> @author Neil Bartlett @param d a number @return sqrt of the number */
Language Overview
Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++
18
Subsequent characters may be letters or digits or both Identifiers can be any length Identifiers may not be a reserved word or a boolean literal (true, false)
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
byte 8 bits 0 short 16 bits 0 int 32 bits 0 long 64 bits 0 char 16 bits '\u0000' float 32 bits +0.0f double 64 bits +0.0d boolean false No variable can have an undefined value Class variables are implicitly initialized to the default unless set explicitly Local variables are not implicitly initialized to a default
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
Scope of a Variable
Scope is the block of code in which a variable is accessible.
member variable. Declared within a class but not within a method. local variable. Declared within a method or within a block. method parameter. Values passed into method (more later)
i f
class MyClass { float myMethod( float f ) { f1 float f1; f2 { // define a block inside a method just for fun float f2 = 10F; f1 = f2; } f3 float f3 = f1; return f*f3+i; } int i = 0; }
CSE 422 09/16/2003
Access Specifiers
Specifies who may access variables. Also applies to classes, constructors, and methods. public
available everywhere
protected
available only to the current class and its subclasses
private
available only to the class in which it is declared. This is applied at the class not the object level.
package
If no access specifier is explicitly, available only within the current package
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
Language Overview
Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++
23
do { statements; } while (condition); goto // reserved word that does nothing! break label; continue label;
restart: for (int i = start; i < a.length ; ++i) { // mess with start if (a[i] == ';') continue restart; } CSE 422 Java Overview by SeyedMasoud Sadjadi
09/16/2003
Language Overview
Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++
26
Creating Objects
Objects are instances of classes. To declare an object, use the class name (the type) and a identifier, e.g. Date today; A variables stores reference to an object. The declaration does not create an object. Objects are created with the new reserved word. This will create the memory for the object and return a reference to the object today = new Date(); Or, using one step Date today = new Date();
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
Constructors have the same name as the class. A class can have more than one constructor, e.g.
Rectangle r = new Rectangle(100, 200);
Constructors typically set up the object's variables and other initial state. They might also perform some initial behavior.
o1
MyClass Object
o2
Comparing variables that refer to objects just compares the references. It does not compare the objects. Integer i1 = new Integer(10); Integer i2 = new Integer(10); if (i1 == i2) { // not true }
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
Language Overview
Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++
30
Arrays
Arrays are objects in Java. Use new to create them. Arrays are fixed length. Length cannot be changed once created. Indexes start at zero. Indexes are bounds checked. Primitive Array
byte[] bArray = new byte[5]; for (int i=0; i < bArray.length; i++) bArray[i] = 42; // value
Object Array
Date dArray[] for (int i=0; // Must now dArray[i] = = new Date [5]; i < dArray.length; i++) create the date objs new Date (); //ref
CSE 422 09/16/2003
Multidimensional Arrays
Implemented as arrays of arrays
int twoDArray[][] = new int[300][400]; Declares a variable of type int[][] Dynamically allocates an array of with 300 elements Allocates arrays of 400 ints for each element of the 300 element array
Initializing Arrays
Arrays may be initialized with static initializers
int lookup_table[] = {1, 2, 3, 4, 5, 6, 7, 8};
This is equivalent to
int lookup_table[] = new int[8]; lookup_table[0] = 1;
Strings
Strings are objects, not primitives Not null-terminated, not array of char Rich set of string manipulation methods Initializing
must construct a string object, String s does not create an object
String a = "abc" eqv. String a = new String("abc")
Concatenation operator, "abc"+"def" String class is non-mutative Use StringBuffer class for strings that change
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
Language Overview
Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++
35
Declaring Methods
Must declare the data type of the value it returns. If no value is returned, it must be declared as returning void. Methods may take arguments. These are values that are passed into the method when it is called. Arguments are typed and named. If names conflict with the class level variables, the argument names will hide the class level variable names. Methods are scoped for the whole class. No need for forward references. Java is very strongly typed. No equivalent of C variable length argument list. Cannot pass methods into methods. (Methods are not a type)
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
Language Overview
Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++
38
Declaring Classes
A class is declared using the class keyword
class myClass { // class body }
A class is by default accessible (e.g. can create objects of the class) from any other classes in the same package. The public keyword can be used to create a class that is available anywhere.
Constructors
Constructors are called by the new operator when a class is created. The constructor initializes the new object.
class myClass { int x; String s; myClass() { x = 10; S = "Hello"; } }
Constructors have no return type, but they may take arguments. The argument types must match those provided by the new operator.
myClass(int x, String s) { } myClass c = new myClass(10, "Hello");
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
Default Constructor
If no constructor is present a default constructor will be provided by the compiler. The default constructor has no arguments and just calls the super class's constructor.
class myClass { myClass() { super(); } }
In contrast variables and methods of objects are called instance methods and instance variables. Class methods may directly use other class methods and class variables. If they want to use an instance methods or variables, they must instantiate objects. class method may not be overridden.
main method is a class method. It does not require an object. Math and System are part of the core java packages.
They provide useful math and system functions and constants. These are implemented as class methods and class variables.
Language Overview
Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++
44
Inheritance
To inherit a class from another class use the extends keyword
class SubClass extends SuperClass { ... }
The sub class inherits variables and methods from its super class. It also inherits variables and methods from the super class of the super class and so on up the inheritance tree. Java has single inheritance. A class can only have one super class.
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
is equivalent to
class MyClass extends Object
Object is the root class of all classes. The Object class provides generic methods for all objects. These include:
getClass. Returns an object that contains information about the class that the object was created from. toString. Provides a generic string detailing the object. clone. A placeholder method to allow copying of an object equals. A method to compare objects.
What's Inherited?
When one class extends from another, the sub class inherits those variables and methods that:
are declared with the public or protected access specifiers. have no access specifier
Language Overview
Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++
48
methods. This stops a method from being overridden in a subclass. The method may still be called by the subclass.
final double sqrt(double d)
variables. This declares a constant value. The value is available to the subclass but it may not change or shadow the value.
final int useful_constant=10;
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
super.calculate();}
CSE 422 09/16/2003
Language Overview
Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++
52
Abstract Classes
Super classes that define generic behaviours that must be implemented by derived classes
abstract class DiscPlayer { protected int track; void setTrack() { /* cue the track to play*/ } public abstract void play(); } class VideoDiscPlayer extends DiscPlayer { public void play() { /* play the video disk */ } } class MultiCDPlayer extends DiscPlayer { protected int currentCD; public void play() { /* play the current CD */ } }
DiscPlayer explicitly provides some responsibility while deferring other responsibility to its subclasses.
Interfaces
An interface specifies methods that must be implemented. The interface does not implement the methods; The methods are implemented by the class that implements the interface.
public interface Runnable { public abstract void run (); } class A implements Runnable { public void run() { // do something } }
All interfaces are public. All methods of interfaces are implicitly public and abstract Also permitted as part of an interface are public static final fields.
public interface myInterface { public static final aConstant=100; }
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
Choose class inheritance for strongest isA relationship. Choose interfaces for behavior (Note frequent use of the suffix -able for interface names)
Language Overview
Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++
57
Garbage Collection
The runtime reclaims storage asynchronously using a garbage collector. The garbage collector frees the memory associated with any objects that do not have references. The garbage collector runs in a low-priority thread. It is also called if the memory system runs out of memory to allocate. Use System.gc() to explicitly force garbage collection For variables that do not go out of scope, but that you still want to be garbage collected, set the object reference variable to null. This removes the reference to the underlying object.
obj = null;
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
Finalize
A class may request finalization of its instances by implementing a finalize() method
protected void finalize () throws Throwable { /* cleanup */; super.finalize(); }
Note that this method may NOT have any other method modifiers associated with it. When an object is first detected to be unreferenced, the finalize method is invoked (if present). If it is subsequently determined to be unreferenced, the object is reclaimed. All uncaught exceptions occurring during finalization are ignored.
Language Overview
Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++
60
Class Loading
Classes are loaded dynamically by the system from .class files. When a class is first referenced, a store of classes is checked, if the class has not been loaded, it is loaded. Classes can be dynamically loaded under program control. The Class class has a method forName which takes a String of the name of the class and returns a Class object. Any blocks inside the class that are marked as static are run when the class first loads. class myClass { static { System.loadLibrary("mylib.dll"); } }
This is often used to load subclasses of superclass, e.g. a game player might be allowed to upload new monsters. In this case it is necessary to cast the returned class
String monsterClassName = getNameFromUser(); Class aClass = Class.forName (monsterClassName); Monster m = (Monster) aClass.newInstance ();
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
Language Overview
Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++
64
Compilation Units
Classes and interface are defined in a compilation unit (a file) A compilation unit declares zero or more classes. At most, one declared type (class or interface) may be declared public. For a compilation unit which declares a public type ClassName, the file must be named ClassName.java. Multiple classes in a compilation unit will result in multiple .class files after compilation
Packages
Packages are used to logically group together classes. Each .class file is part of a package. Package is declared using the package operator. This must form the first statement in the source.
package mypackage;
If no package is explicitly stated, then the package is unnamed. All 'unpackaged' classes in the directory in which the .class file resides are part of this package. Package names have a one-to-one correspondence to a directory. Package names are dot separated (e.g., java.lang) Packages can be imported by other source files:
Example: import packagename.*; import packagename.classname;
The CLASSPATH
The CLASSPATH is an environment variable used to locate packages. The CLASSPATH consists of a series of directories separated by semi-colons (Windows) and colons (UNIX).
set CLASSPATH = d:\mydir;c:\java
Each directory forms the root directory to search for a package. Thus if the package were java.lang, there must be a directory called java under one of the directories in the CLASSPATH and there must be a directory call lang under that, for the package to be found.
Java Overview by SeyedMasoud Sadjadi
CSE 422 09/16/2003
Language Overview
Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++
68
Java does have: different compilation model (compiles to byte-codes per class) single-rooted class inheritance hierarchy multiple interface inheritance strings and arrays are true objects garbage collection support for concurrency via Threads
Agenda
Introduction to Java (today)
What is Java? Tools Overview Language Overview
70
Summary
Java is a full-featured OOP language
Single-implementation inheritance Multiple-interface inheritance
Java has a similar syntax to C++ but different semantics Portable Garbage Collection Dynamic Loading Reflection