Title: Java Overview CSE 422
1Java OverviewCSE 422
- Michigan State Universityprepared by Philip K.
McKinleypresented by SeyedMasoud SadjadiThese
materials are excerpted from a course created by
Arthur Ryman of IBM Toronto, and used at the
University of Toronto. Thanks!
2Agenda
- Introduction to Java (today)
- What is Java?
- Tools Overview
- Language Overview
- Advanced Topics (next session)
- Error Handling
- Multithreading
- Networking
3What 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)
4Java, 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
5Java 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
byte-codes. - The Class Loader for classes loaded over the
network (enhances security).
javac
Java Source
Java Byte-code
.java
.class
6Portable, Dynamic, and Extensible
- Java runtime based on architecturally neutral
byte-codes (per class)
.class files
load
interpret
Java Runtime
loaded classes (byte-codes)
call
Native.dll
Native.dll
7Standard 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
Internet-based services - VM can dynamically load classes over the Internet
8Agenda
- Introduction to Java (today)
- What is Java?
- Tools Overview
- Language Overview
- Advanced Topics (next session)
- Error Handling
- Multithreading
- Networking
9JDK 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
10JIT 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
.class
JVM running Applet or Application
J.I.T.Compiler
machine code
11Eclipse
- jdt java development tools subproject
- Plug-ins for Java development
12Agenda
- Introduction to Java (today)
- What is Java?
- Tools Overview
- Language Overview
- Advanced Topics (next session)
- Error Handling
- Multithreading
- Networking
13Language Overview
- Java Programs
- Variables
- Flow Control
- Objects
- Arrays
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstract Classes
- Garbage Collection
- Reflection
- Packaging
- Java vs. C
14Java 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.
15A 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 - cmdgtjavac Count.java
- Run the interpreter on the .class file
- cmdgt java Count
- This is a test.
- Input has 16 chars
16Analysis
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.
17Comments
- 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 - ltBgt Here is a bolded comment lt\Bgt
- _at_author Neil Bartlett
- _at_param d a number
- _at_return sqrt of the number/
18Language Overview
- Java Programs
- Variables
- Flow Control
- Objects
- Arrays
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstract Classes
- Garbage Collection
- Reflection
- Packaging
- Java vs. C
19Variables 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)
20Data 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
21Scope 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
- class MyClass
- float myMethod( float f )
- float f1
- // define a block inside a method just
for fun - float f2 10F
- f1 f2
-
- float f3 f1
- return ff3i
-
- int i 0
-
f
f1
f2
f3
22Access 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
23Language Overview
- Java Programs
- Variables
- Flow Control
- Objects
- Arrays
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstract Classes
- Garbage Collection
- Reflection
- Packaging
- Java vs. C
24Flow of Control - Conditional
if (condition) statements else
statements switch (intVal) case
intVal1 statements break case
intVal2 statements return default state
ments break
25Flow 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 lt a.length i)
// mess with start if (ai '')
continue restart
26Language Overview
- Java Programs
- Variables
- Flow Control
- Objects
- Arrays
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstract Classes
- Garbage Collection
- Reflection
- Packaging
- Java vs. C
27Creating 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()
28The 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.
29Objects 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
- 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
-
30Language Overview
- Java Programs
- Variables
- Flow Control
- Objects
- Arrays
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstract Classes
- Garbage Collection
- Reflection
- Packaging
- Java vs. C
31Arrays
- 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 byte5
- for (int i0 i lt bArray.length i)
- bArrayi 42 // value
- Object Array
- Date dArray new Date 5
- for (int i0 i lt dArray.length i)
- // Must now create the date objs
- dArrayi new Date () //ref
32Multidimensional Arrays
- Implemented as arrays of arrays
- int twoDArray new int300400
- 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 int10
- Multidimentional arrays need not be rectangular
- int threeDArray new int10
- threeDArray0 new int1004
- threeDArray1 new int35000
33Initializing 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 int8
- lookup_table0 1
-
- Similarly for multidimentional arrays
- String param_info "fps", "1-10",
"frames per second","repeat", "boolean",
"repeat image loop","imgs","url","images
directory"
34Strings
- 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
35Language Overview
- Java Programs
- Variables
- Flow Control
- Objects
- Arrays
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstract Classes
- Garbage Collection
- Reflection
- Packaging
- Java vs. C
36Declaring 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)
37Passing 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) -
-
38Language Overview
- Java Programs
- Variables
- Flow Control
- Objects
- Arrays
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstract Classes
- Garbage Collection
- Reflection
- Packaging
- Java vs. C
39Declaring 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.
40Constructors
- 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")
41Default 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
42Class 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.
43Examples 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.
44Language Overview
- Java Programs
- Variables
- Flow Control
- Objects
- Arrays
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstract Classes
- Garbage Collection
- Reflection
- Packaging
- Java vs. C
45Inheritance
- 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.
46The 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.
47What'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
48Language Overview
- Java Programs
- Variables
- Flow Control
- Objects
- Arrays
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstract Classes
- Garbage Collection
- Reflection
- Packaging
- Java vs. C
49Polymorphism - 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
-
50The 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_constant10
51this 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()
52Language Overview
- Java Programs
- Variables
- Flow Control
- Objects
- Arrays
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstract Classes
- Garbage Collection
- Reflection
- Packaging
- Java vs. C
53Abstract 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.
54Abstract 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()
- ...
55Interfaces
- 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 aConstant100
56Class 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)
57Language Overview
- Java Programs
- Variables
- Flow Control
- Objects
- Arrays
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstract Classes
- Garbage Collection
- Reflection
- Packaging
- Java vs. C
58Garbage 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
59Finalize
- 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.
60Language Overview
- Java Programs
- Variables
- Flow Control
- Objects
- Arrays
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstract Classes
- Garbage Collection
- Reflection
- Packaging
- Java vs. C
61The 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()
62Class 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")
-
-
63Advanced 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 ()
64Language Overview
- Java Programs
- Variables
- Flow Control
- Objects
- Arrays
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstract Classes
- Garbage Collection
- Reflection
- Packaging
- Java vs. C
65Compilation 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
66Packages
- 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
67The 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\mydirc\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.
68Language Overview
- Java Programs
- Variables
- Flow Control
- Objects
- Arrays
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstract Classes
- Garbage Collection
- Reflection
- Packaging
- Java vs. C
69Java vs. C
- Java does not
- have pointers and pointer arithmetic
- have structs, unions, enums
- have templates
- support operator overloading
- support multiple inheritance
- have any standalone functions
- support default arguments for methods
- have a delete operator
- have variable arguments
- make use of a preprocessor
- synchronous destructors
- 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
70Agenda
- Introduction to Java (today)
- What is Java?
- Tools Overview
- Language Overview
- Advanced Topics (next session)
- Error Handling
- Multithreading
- Networking
71Summary
- 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