You are on page 1of 71

Java Overview

CSE 422
Michigan State University
prepared by Philip K. McKinley
presented by SeyedMasoud Sadjadi
These materials are excerpted from a course created by Arthur Ryman
of IBM Toronto, and used at the University of Toronto. Thanks!

CSE422 Tuesday (Sept. 16, 2003)

Agenda

Introduction to Java (today)


What is Java?
Tools Overview
Language Overview

Advanced Topics (next session)


Error Handling
Multithreading
Networking

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

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.

Portable, Dynamic, and Extensible

A set of standardized packages (class libraries)

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

Java, A Concurrent OOPL

Complete OOPL (not only structures into objects)


Characteristics of both C++ and Smalltalk
C++

Same syntax for expressions, statements and control flow


Similar OO syntax (classes, access, constructors, methods, ... )

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

Concurrency and synchronization (threads)


Objects can force mutual exclusion of threads running inside them

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

Java Virtual Machine

Java is complied to byte-codes whose target


architecture is the Java Virtual Machine (JVM)
The virtual machine is embeddable within other
environments, e.g. web browser & operating sys.
Uses a byte-code verifier when reading in bytecodes.
The Class Loader for classes loaded over the
network (enhances security).
Java
Source

javac

Environment
Java
Byte-code

.java
Java Overview by SeyedMasoud Sadjadi

Java VM

.class
CSE 422
09/16/2003

Portable, Dynamic, and Extensible

Java runtime based on architecturally neutral byte-codes


(per class)

.class
files
interpret

load

Java Runtime
loaded classes
(byte-codes)

call
Native
.dll

Native
.dll

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

Standard Set of Packages

Windowed GUIs
Full set of standard window-based GUI classes
Extremely easy to build GUI clients

Images and audio


Support for creating Image objects from .gif, .jpg, etc.
Provides Image processing filters
Applets can also play audio files

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

Advanced Topics (next session)


Error Handling
Multithreading
Networking

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

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

Also included are:

javah Header file generator for interlanguage linking


javap A disassembler
javadoc HTML generator from Java source code
jdb a rudimentary Java debugger

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

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

JVM running
Applet or
Application

.class
machine
code

Java Overview by SeyedMasoud Sadjadi

J.I.T.
Compiler

CSE 422
09/16/2003

10

Eclipse

jdt: java development tools subproject


Plug-ins for Java development

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

11

Agenda

Introduction to Java (today)


What is Java?
Tools Overview
Language Overview

Advanced Topics (next session)


Error Handling
Multithreading
Networking

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

12

Language Overview

Java Programs
Variables
Flow Control
Objects
Arrays
Methods
Classes
Inheritance
Polymorphism
Abstract Classes

Java Overview by SeyedMasoud Sadjadi

Garbage Collection
Reflection
Packaging
Java vs. C++

CSE 422
09/16/2003

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.

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

A Simple Java Application


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

Compile the .java file to generate the .class file


cmd>javac Count.java

Run the interpreter on the .class file


cmd> java Count
This is a test.
Input has 16 chars
Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

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
*/

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

Java Overview by SeyedMasoud Sadjadi

Garbage Collection
Reflection
Packaging
Java vs. C++

CSE 422
09/16/2003

18

Variables and Identifiers

Variable may be a primitive data type or reference to an


object
Unicode 1.1 character set used (16 bit international
character set encoding). This applies to the char data
type.
An identifier starts with:
a letter (from any language encoded by Unicode)
an underscore (_), or
a dollar sign($)

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

Data Types - Primitive Types

Primitive Type
Precision
Default Value
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;
}

Java Overview by SeyedMasoud Sadjadi

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

Java Overview by SeyedMasoud Sadjadi

Garbage Collection
Reflection
Packaging
Java vs. C++

CSE 422
09/16/2003

23

Flow of Control - Conditional


if (condition) {
statements;
} else {
statements;
}
switch (intVal) {
case intVal1:
statements;
break;
case intVal2:
statements;
return;
default:
statements;
break;
}

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

Flow of Control - Looping


for (initialize; test; increment){
statements;
}
while (condition)
statements;
}

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

Java Overview by SeyedMasoud Sadjadi

Garbage Collection
Reflection
Packaging
Java vs. C++

CSE 422
09/16/2003

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

The new operator

The new operator creates an object by allocating memory.


Takes one parameter - the class constructor. The class
constructor is a special method declared in the class. It is
responsible for initializing the object to a known state.
Rectangle r = new Rectangle(0, 0, 100, 200);

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.

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

Objects and References

A variable stores a reference to an object. There is no equivalent of


C++ pointer.
Many objects references may refer to the same object
MyClass o1 = new MyClass();
MyClass o2 = o1;
Both o1 and o2 now refer to the same object

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

Java Overview by SeyedMasoud Sadjadi

Garbage Collection
Reflection
Packaging
Java vs. C++

CSE 422
09/16/2003

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

Java Overview by SeyedMasoud Sadjadi

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

Can provide partial sizing


int threeDArray[][][] = new int[10][][];
Multidimentional arrays need not be rectangular
int threeDArray[][][] = new int[10][][];
threeDArray[0] = new int[100][4];
threeDArray[1] = new int[3][5000];

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

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;

Similarly for multidimentional arrays

String param_info[][] = {
{"fps", "1-10", "frames per second"},
{"repeat", "boolean", "repeat image loop"},
{"imgs","url","images directory"}
};

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

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

Java Overview by SeyedMasoud Sadjadi

Garbage Collection
Reflection
Packaging
Java vs. C++

CSE 422
09/16/2003

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

Passing Arguments to Methods


Arguments are passed by value. Changing the value inside the method
does not effect the value outside the method. This applies to both
primitive types and object references.
public class myClass {
int x;
void myMethod(myClass ac, int ay) {
ay = 10;
ac.x = 5;
ac = null;
}
public static void main (String args[]) {
myClass c = new myClass();
c.x = 1000;
int y = 2000;
c.myMethod(c, y);
System.out.println("c:"+c+" c.x:"+c.x+" y:"+y);
}
}

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

Java Overview by SeyedMasoud Sadjadi

Garbage Collection
Reflection
Packaging
Java vs. C++

CSE 422
09/16/2003

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.

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

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

Does not provide default constructor with


arguments

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

Class Variables and Methods

Problem: If all method calls need an object, how to we provide global


constants and utility functions. Must we create an object just to use
them?
Classes can provide variables and methods that may be used with
out an object. There are called class variables and class methods.
To make a variable or method into a class variable, use the static
keyword, e.g.
static int count;

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.

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

Examples of Class Variables and


Methods
import java.util.*;
public class ClassMethodExample {
static String todaysDate() {
Date d = new Date();
return d.toString();
}
public static void main(String[] s) {
System.out.println( "The square root of pi is "+
Math.sqrt( Math.PI ));
System.out.println( "The date is "+todaysDate() );
}
}

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.

todaysDate is a user-defined class method. It constructs a Date object


to do its job.

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

Java Overview by SeyedMasoud Sadjadi

Garbage Collection
Reflection
Packaging
Java vs. C++

CSE 422
09/16/2003

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

The Object class

Every class you define has a super class. There is a special class
called Object which is the implicit super class of any class which does
not explicitly descend from a class, so
class MyClass

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.

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

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

But don't inherit those


with the same name a one in the sub class.
declared as private.
class SuperClass {
int x, y;
int methodA() {}
int methodB() {}
}
class SubClass extends SuperClass {
int y; // hides SuperClass.y
int methodB() {} // overrides SuperClass.methodB
}

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

Java Overview by SeyedMasoud Sadjadi

Garbage Collection
Reflection
Packaging
Java vs. C++

CSE 422
09/16/2003

48

Polymorphism - Method Hiding

A method with the same signature as a method in its


super class hides or overrides the method in the super
class.
An object of a sub class may be assigned to a reference
of a super class. In this case, these overridden methods
will be called
class SuperClass {
void aMethod() { }
}
class SubClass {
void aMethod() {}
}
SuperClass s = new SubClass();
s.aMethod(); // calls SubClass's aMethod

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

The final keyword

The final keyword is used to limit what can be changed


when it is inherited It can be applied to:
classes. A final class cannot be extended from.
Generally you do this for security reasons , e.g. the String
class
final class MyClass

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

this and super


In method body, this is a reference to the current object
and super is a reference to its parent.
class A {
Object x;
}
class B extends A {
float x;
float calculate(){ }
}
class C extends B {
int x;
void m(char x) {
char cmx = x;
//the method argument
int cx = this.x;
//Cs member x
float bx = super.x; //Bs x, also B.x
Object ax = A.x;
//As x
}
float calculate() {return super.calculate();}
}

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

Java Overview by SeyedMasoud Sadjadi

Garbage Collection
Reflection
Packaging
Java vs. C++

CSE 422
09/16/2003

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.

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

Abstract Classes and Methods

An abstract class may contain zero or more abstract methods. Any


class that contains an abstract method is implicitly abstract.
An abstract class cannot be instantiated.
An abstract method must be implemented in a subclass to instantiate
an object of the subclass.
Abstract methods can provide implementation. This is useful to
provide default processing:
class SuperClass {
abstract void aMethod() { /* something useful */ }
}
class SubClass extends SuperClass {
void aMethod() {
super.aMethod();
...

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

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

Class Inheritance Vs. Interfaces

Interfaces define only method signature. Inherited


classes can provide implementation.
Can only have one super class. Can implement a
number of interfaces
class A implements Runnable, Printable
{

Choose class inheritance for strongest isA


relationship. Choose interfaces for behavior (Note
frequent use of the suffix -able for interface
names)

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

Java Overview by SeyedMasoud Sadjadi

Garbage Collection
Reflection
Packaging
Java vs. C++

CSE 422
09/16/2003

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.

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

Java Overview by SeyedMasoud Sadjadi

Garbage Collection
Reflection
Packaging
Java vs. C++

CSE 422
09/16/2003

60

The Class class

The Class class contains information about a class. This


allows us to provide runtime type information (RTTI)
There is a Class object for each class that has been
loaded.
The Class class allows information about the class to be
inspected, e.g. getName, getInterfaces, getSuperClass.
The Object class has a method getClass which will return
a class object.
// print out the name of the class of an object
String objClassName = obj.getClass().getName();

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

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

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

Advanced Object Creation

It is not necessary to use the new operator to create an


object.
Objects can be created from a just a name.
Objects of the Class class provide the newInstance
method to create an instance of the class, e.g.
Class aClass = Class.forName ("myClass");
Object o = aClass.newInstance ();

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

Java Overview by SeyedMasoud Sadjadi

Garbage Collection
Reflection
Packaging
Java vs. C++

CSE 422
09/16/2003

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

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

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;

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

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

Java Overview by SeyedMasoud Sadjadi

Garbage Collection
Reflection
Packaging
Java vs. C++

CSE 422
09/16/2003

68

Java vs. C++


Java does not:

have pointers and pointer


arithmetic

have structs, unions, enums

have templates

Java does have:

different compilation model


(compiles to byte-codes per class)

single-rooted class inheritance


hierarchy

support operator overloading

multiple interface inheritance

support multiple inheritance

strings and arrays are true objects

have any standalone functions

garbage collection

support default arguments for


methods

support for concurrency via


Threads

have a delete operator

have variable arguments

make use of a preprocessor

synchronous destructors

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

Agenda

Introduction to Java (today)


What is Java?
Tools Overview
Language Overview

Advanced Topics (next session)


Error Handling
Multithreading
Networking

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

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

Java Overview by SeyedMasoud Sadjadi

CSE 422
09/16/2003

You might also like