Java Lecture Notes
Java Lecture Notes
Java Lecture Notes
to the
Java Programming Language
Onur Derin
ALaRI, Faculty of Informatics, USI
derino@alari.ch
cc by sa 3.0
Contents
Day 1
● Basics of the Java Language
● Object-oriented Principles with Java
● Encapsulation
● Inheritance
● Polymorphism
● Exception Handling
Day 2
● Java API
● Some design patterns that are useful to understand the Java API
● Iterator Design Pattern
● Adapter Design Pattern
● Decorator Design Pattern
● Observer Design Pattern
● Strategy Design Pattern
● Composite Design Pattern
● Abstract Factory Design Pattern
● Singleton Design Pattern
● Java Collections Framework
● Data structures
● Algorithms
Day 3
● Input/Output Operations in Java
● Multi-threaded Programming in Java
● GUI Design in Java
● Using an external library
● XML processing in Java
Java Programming Language
● Simple
● Architecture neutral
● Object oriented
● Portable
● Distributed
● High performance (!)
● Multi-threaded
● Robust
● Dynamic
● Secure
● Open source
Java Platform
● Java API
● JVM
Java Virtual Machine
● Java is compiled into bytecodes
Major Java Technologies
● J2SE (Java applications, applets)
● J2EE (servlets)
● J2ME (MIDlets)
They have different runtime environments but they are all programmed with the
Java language.
Keywords of Java
Abstract double int static
Boolean Else interface super
Break extends long switch
Byte Final native synchronized
Case Finally new this
Catch Float null throw
Char For package throws
Class Goto private transient
Const if protected try
Continue implements public void
Default import return volatile
Do instanceof short
● No header files
● No structures or unions
● No enums
● No multiple inheritance
● No pointers
Naming Conventions
Identifier type Convention Examples
If you comply with these conventions, you make everyone's life easier.
Structure of a Java Source File
// AnExample.java Source file should have the same name as the class it declares
package ch.alari.javatutoring; AnExample.java needs to reside in ch/alari/javatutoring
import java.io.*; Imported classes need to be in the classpath at compile-time
class AnExample
{
private int x; Variable declarations
public AnExample(int x) Constructor
{
this.x = x;
}
● Makefiles and
● make to compile
● make run to run
● make check to see if your implementation is correct
● make clean to remove *.class files
HelloWorld Example (ex.1)
// HelloWorld.java
class HelloWorld
{
public HelloWorld()
{
}
export PATH=$PATH:/opt/java/bin
Compiling
javac HelloWorld.java
java HelloWorld
Running
HelloWorld Example using packages (ex.2)
// HelloWorld.java
package ch.alari.javatutoring.examples;
class HelloWorld
{
public HelloWorld()
{
}
javac
Compiling
ch/alari/javatutoring/examples/HelloWorld.java
java ch.alari.javatutoring.examples.HelloWorld
Running
Pass-by-value(-of-reference) (ex.3)
public class Main {
public Main() {
}
translateBy5(p1);
}
- Analyze JavaValueReference.java
Lab exercise (ex.4)
● Check if it works.
Hint:
Sol.1) Use an array
Sol.2) Define a MyInteger class
Lab exercise (ex.5)
● Convert one of the C++ exercises you have written last week into Java.
● Check if it works.
Object-Oriented Principles with Java
● Encapsulation: provided by private-protected-public identifiers
in class members
● Inheritance:
● provided by extends keyword
● Polymorphism:
● Method overloading: same method name with different signatures
Encapsulation
● provided by private-protected-public identifiers in class members
Encapsulation
See http://www.uni-bonn.de/~manfear/javaprotection.php
for a nice example
Inheritance
● Inheritance:
● provided by extends keyword
Class Hierarchy
● public interface Publisher
● public boolean publish(String status);
{
// connect to FTP server and send the status file
}
{
// connect to SSH server and send the status file
}
Lab Exercise (ex.6)
● Given a two dimensional point class (Point.java), extend it to a
three dimensional point class (Point3D.java)
Lab Exercise (ex.7)
● Create the Java code corresponding to the following UML class diagram
Lab Exercise
● Operations of subclasses shown
Exception Handling (ex.8)
● try, catch, finally, throw, throws, Exception class
try{
methodName(); // a code block that can throw an exception.
} catch(AException ex)
{
// handle the exception of type AException
} catch(BException ex)
{
// handle the exception of type BException
} finally
{
// this code block is executed whether there is an exception or not.
}
Exception Handling
● Define exceptions by extending from Exception class
Java API
●
A lot of 3rd party APIs are available as open
source projects
Iterator Pattern
● Provides a way to access the elements of a collection sequentially without
exposing its underlying representation
● Supports multiple, concurrent traversals of collections
● Provides a uniform interface for traversing different collections
(that is, supports polymorphic iteration)
● Appears in Java API as
Adapter Pattern
● Convert the interface of a class into another interface clients expect.
● You want to use an existing class, and its interface does not match the one
you need
Client TargetInterface
targetMethod()
adaptee
Adapter Adaptee
targetMethod() aMethod()
Decorator Pattern
● A flexible alternative to subclassing for extending functionality
Decorator2
aMethod() Decorator1
aMethod() Component
aMethod()
Observer Pattern
● Define a one-to-many dependency between objects so that when one object
changes state, all its dependants are notified and updated automatically
Subject Observer
observers
addObserver() notify()
removeObserver()
notify()
Strategy Pattern
● Define variants of algorithms, encapsulate each one, and make them
interchangeable Clients can use different algorithms when needed.
SortArray SortStrategy
sortStrategy
sort() sort()
BubbleSort QuickSort
sort() sort()
Composite Pattern
● Compose objects into three structures
Component
operation()
Leaf Composite
children
operation() operation()
Abstract Factory Pattern
● In the case when
● A system should be independent of how its products are created,
● e.g. Consider a VLSI design tool. The class to instantiate an AND gate may
vary depending on the configuration set by the designer.
Singleton Pattern
● To make sure there is only one instance of a class and it is accessible globally
Singleton
static instance()
class Singleton {
● Increases performance
● It consists of
● Collection interfaces (Collection, Set, List, Map, Queue, ... )
access.
● Map: A mapping from keys to values. Each key can map to at most one
value.
● Several implementations which differ in abstraction and performance
criteria
Ex.9
Vector fruits = new Vector();
fruits.add(“apple”);
fruits.add(“orange”);
fruits.add(“potato”); Run this code
fruits.remove(“potato”); and change it to use
fruits.contains(“potato”); generics
fruits.size();
fruits.elementAt(0);
Ex.11
Stack fruits = new Stack();
fruits.push(“apple”);
fruits.push(“orange”); Run this code
fruits.push(“potato”); and change it to use
fruits.pop(); generics
fruits.search(“potato”);
fruits.isEmpty();
for(Enumeration e= fruits.elements(); e.hasMoreElements(); )
{
System.out.println(e.nextElement());
}
Stack Exercise (ex.12)
Use java.util.Stack class for the following exercise.
Write a class that converts a String given in prefix notation form into infix notation
form.
java.util.Hashtable
● This class implements a hashtable, which maps keys to values.
Ex.13
Hashtable phoneBook = new Hashtable();
phoneBook.put("A", "+41111111111"); Run this code and
phoneBook.put("B", "+41222222222"); change it to use
phoneBook.put("C", "+41333333333"); generics
if(phoneBook.containsKey("D"))
phoneBook.remove("D");
Hashtable Exercises
Ex.14
● Write a Dictionary class by which you can
Ex.15
● Using java.util.Hashtable class, write a HashtableAdapter class that
● Enumeration keysInPutOrder()
Algorithms for Collection classes
● java.util.Collections class provides static methods that operate on collections.
● For example,
comparator.
● Strategy pattern
● Similar to sorting, you can use other algorithms (like shuffle, search) of
Collections class.
Sort exercise (ex.16)
class SortTest {
private Vector list = new Vector();
public SortTest() {
list.addElement(new String("grape"));
list.addElement(new String("apple"));
list.addElement(new String("orange"));
list.addElement(new String("cherry"));
}
● Make a test to sort people according to their age and their height.
Input/Output Operations
● Fundamental concept is a stream.
Source Destination
● java.io.InputStream
● java.io.OutputStream
● These two classes are byte-oriented.
● java.io.Reader
● java.io.Writer
● These are character-oriented.
java.io.InputStream
● Is an abstract class
● Has abstract int read()
● When read is implemented, be careful if it is blocking.
● Provides int available() to see how many bytes are ready to be read.
Source Program
java.io.OutputStream
● Is an abstract class
● Has abstract write(int)
Destination Program
File I/O
● java.io.FileInputStream
● java.io.FileOutputStream
● Ex. 18
Understand the code in Copy.java, compile and run the application.
● As you have noticed, for every byte of the file, there is a function call to read
which accesses the disk every time it is called.
● Similarly for write.
java.io.BufferedInputStream
● Constructed from an InputStream object.
BufferedInputStream
● Holds inside a buffer as an array.
read()
● Acts as a decorator (remember previous lecture)
InputStream
● Supports marking and reseting
java.io.BufferedOutputStream
● Constructed from an OutputStream object.
BufferedOutputStream
● Holds inside a buffer as an array.
write()
● Acts as an decorator (remember previous lecture)
OutputStream
● write() is called when buffer is full.
Buffered File I/O
● Ex. 19
● Understand the code in BufferedCopy.java
real 0m51.405s
user 0m11.245s
sys 0m35.818s
real 0m0.837s
user 0m0.620s
sys 0m0.052s
java.io.DataInputStream
● Constructed from an InputStream object.
● Allows reading primitive Java data types from the underlying InputStream
object.
● Works in a machine-independent way.
● Acts as a decorator
DataInputStream
read()
InputStream
java.io.DataOutputStream
● Constructed from an OutputStream object.
● Allows writing primitive Java data types to the underlying OutputStream
object.
● Machine-independent, DataInputStream can be used to read what has been
written
● Acts as a decorator DataOutputStream
write()
OutputStream
Data IO (ex.20)
● Using DataInputStream, DataOutputStream, FileInputStream, FileOutputStream
classes,
● Write an application in which you retrieve what you have written from the file.
A Short Introduction to
Multi-threaded Programming in Java
● Thread: is a thread of execution in a program.
A Short Introduction to
Multi-threaded Programming in Java
2) Implementing Runnable interface and providing the Runnable
object as an argument to the constructor of Thread.
Piped I/O Streams
● java.io.PipedInputStream
● java.io.PipedOutputStream
Pipe
Thread Thread
● Ex.21
● Understand the code in PipeTest.java,
GUI Design in Java
● Strategy
● Container's layout manager (FlowLayout, BorderLayout, GridbagLayout)
● Composite
● See java.awt.Container extends java.awt.Component. Attention to paint()
method.
● Observer
● See java.util.EventListener and all of its subclasses
● Abstract Factory
● See java.awt.Toolkit and all of its create methods
● Singleton
● e.g. Toolkit instance is never created by the programmers, see
GUI Design in Java (ex.22)
Using external libraries (ex.23)
“XML processing with dom4j”
import java.io.FileWriter;
import org.dom4j.*;
import org.dom4j.io.*;
import java.util.List;
Using external libraries
“XML processing with dom4j”
Element newElement = (Element)modelElement.clone();
newElement.addAttribute("id", "e3");
List eventsList = eventsElement.content();
eventsList.add(3, newElement);
You can obtain dom4j.jar from www.dom4j.org
Writing an intelligent Pishti player (ex. 24)
● To see the assignment, visit:
http://www.alari.ch/people/derino/Teaching/Java/Pishti/index.php
ALaRI CfP tracker monthly timeline (ex.25)
● ALaRI CfP tracker lists open and closed call for papers at the following address:
http://www.alari.ch/NewsAndEvents/cfp
● wget http://www.alari.ch/NewsAndEvents/cfp/es/cfp.xml
● wget http://www.alari.ch/NewsAndEvents/cfp/es/cfp-past.xml
write a program that lists the CfPs grouped by month in a single year
timeline according to their submission due dates.
e.g.
January
ABC'08
XYZ'10
ABC'09
ABC'10
DEF'09
ABC'11
February
...
ALaRI CfP tracker in webcal format (ex.26)
● ALaRI CfP tracker lists open and closed call for papers at the following address:
http://www.alari.ch/NewsAndEvents/cfp
● wget http://www.alari.ch/NewsAndEvents/cfp/es/cfp.xml
write a program that creates a file in the webcal format listing the upcoming
CfPs according to their submission due dates.
Propose your own assignment (ex. 27)
● Tell me about your own idea, once approved, do it as your final assignment!
References
● Thinking in Java by Bruce Eckel (available online)
● Sun’s Java Homepage: http://java.sun.com
● Bob Tarr’s Design Patterns Homepage:
http://research.umbc.edu/~tarr/dp/dp.html
● Jeff Friesen’s Book: Java 2 By Example, Second Edition