JAVA Programming
JAVA Programming
JAVA Programming
in JNTU World
ld
Introduction
to the
or
Java Programming Language
W
TU
JN
Contents
Day 1
● Basics of the Java Language
● Object-oriented Principles with Java
ld
● Encapsulation
● Inheritance
● Polymorphism
● Exception Handling
or
Day 2
● Java API
● Some design patterns that are useful to understand the Java API
Iterator Design Pattern
W
●
Day 3
Input/Output Operations in Java
●
ld
● Architecture neutral
● Object oriented
● Portable
Distributed
or
●
W
● Secure
● Open source
Java Platform
● Java API
TU
● JVM
JN
ld
●
or
● The Java run-time system provides the JVM
W
● Since the bytecodes are interpreted, the performance of Java
programs slower than comparable C/C++ programs
ld
●
● J2EE (servlets)
or
● J2ME (MIDlets)
W
They have different runtime environments but they are all programmed with the
Java language.
TU
JN
Keywords of Java
ld
Abstract double int static
Boolean Else interface super
Break extends long switch
Byte Final native synchronized
or
Case Finally new this
Catch Float null throw
Char For package throws
Class Goto private transient
W
Const if protected try
Continue implements public void
Default import return volatile
Do instanceof short
TU
Not much different from C/C++
ld
● No header files
No structures or unions
or
●
● No enums
W
●
● No multiple inheritance
● No pointers
JN
Naming Conventions
ld
Identifier type Convention Examples
or
Method names Capitalize each word except the first connectPhone
W
Constant Capitalize each word with underscores
MAX_CONNECTIONS btw words
TU
If you comply with these conventions, you make everyone's life easier.
JN
ld
// AnExample.java
or
class AnExample
{
private int x; Variable declarations
W
public AnExample(int x) Constructor
{
this.x = x;
}
Information on Exercises
ld
● These slides are accompanied with a lab-skeletons.tar.gz file
where all the exercises that will be done during the class are put in
a directory structure along with
● a test driver class for the classes you are expected to write,
or
● Makefiles and
W
● make to compile
● make run to run
● make check to see if your implementation is correct
● make clean to remove *.class files
TU
● See the README file in lab-skeletons.tar.gz for more information
JN
ld
// HelloWorld.java
class HelloWorld
{
or
public HelloWorld()
{
}
W
System.out.println(“Hello World!”);
}
}
TU
export PATH=$PATH:/opt/java/bin
Compiling
javac HelloWorld.java
java HelloWorld
Running
JN
ld
package ch.alari.javatutoring.examples;
class HelloWorld
or
{
public HelloWorld()
{
}
W
{
System.out.println(“Hello World!”);
}
}
TU
javac
Compiling
ch/alari/javatutoring/examples/HelloWorld.java
java ch.alari.javatutoring.examples.HelloWorld
Running
JN
ld
● Garbage collection
or
● Anything else is derived from java.lang.Object
(as if public class MyExampleClass extends Object)
W
● Arguments in method calls are passed always by value. (value of reference)
TU
JN
Pass-by-value(-of-reference) (ex.3)
public class Main {
ld
public Main() {
}
or
public static void main(String[] args)
{
Point p1 = new Point(1,2);
W
translateBy5(p1);
}
- Analyze JavaValueReference.java
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
● Write a swap function that swaps two integers.
or
● Compile and run your program.
● Check if it works.
W
Hint:
Sol.1) Use an array
Sol.2) Define a MyInteger class
TU
JN
ld
● Convert one of the C++ exercises you have written last week into Java.
or
● Or convert bubblesort.cpp to BubbleSort.java
W
● Check if it works.
TU
JN
ld
● Encapsulation: provided by private-protected-public identifiers
in class members
● Inheritance:
or
● provided by extends keyword
W
● Polymorphism:
● Method overloading: same method name with different signatures
Encapsulation
ld
● provided by private-protected-public identifiers in class members
or
private Key prisonKey;
public Key getPrisonKey(Person requester)
{
if(requester.getType() == Person.PRISON_STAFF)
W
return prisonKey;
else
return null;
}
}
TU
JN
Encapsulation
ld
or
W
For members of Alpha class:
private Y N N N
See http://www.uni-bonn.de/~manfear/javaprotection.php
for a nice example
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Inheritance
ld
● Inheritance:
● provided by extends keyword
or
● public abstract class Shape
{
protected double area;
protected String name;
W
public abstract double getArea();
public Shape(String name){ this.name = name; }
}
return area;
}
}
● Shape s = new Rectangle(“Rectangle A”); // up-casting done implicitly.
● s.getArea();
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Polymorphism
ld
● Method overloading: same method name with different signatures
or
public Matrix(){ ... }
public Matrix multiply(Matrix m){ ... }
public Matrix multiply(double scalar){ ... }
}
W
●
An Example: Bondus
ld
● Bondus is a program that bonds people together by informing each other
on their current status (Available, Busy, Out of office etc.)
● http://www.alari.ch/~derino/bondus
● Interested students are welcome to join
or
Class Hierarchy
● public interface Publisher
● public boolean publish(String status);
W
● public class FTPPublisher implements Publisher
● public boolean publish(String status)
{
// connect to FTP server and send the status file
TU
}
{
JN
ld
three dimensional point class (Point3D.java)
or
W
TU
JN
ld
or
W
TU
JN
Lab Exercise
● Operations of subclasses shown
ld
or
W
TU
JN
ld
public void methodName () throws Aexception, BException
{
...
or
throw new AException();
...
throw new Bexception();
...
W
}
try{
methodName(); // a code block that can throw an exception.
} catch(AException ex)
TU
{
// handle the exception of type AException
} catch(BException ex)
{
// handle the exception of type BException
JN
} finally
{
// this code block is executed whether there is an exception or not.
}
Exception Handling
ld
● Define exceptions by extending from Exception class
or
}
W
TU
JN
Java API
ld
● All classes contained under the package java and javax.
or
● Provides a lot of useful classes (Containers, Enumerators, ...)
W
● Before trying to write a class, first check the 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
ld
exposing its underlying representation
● Supports multiple, concurrent traversals of collections
● Provides a uniform interface for traversing different collections
(that is, supports polymorphic iteration)
or
● Appears in Java API as
W
for(Iterator i = v.iterator(); i.hasNext(); )
System.out.println(i.next());
Adapter Pattern
● Convert the interface of a class into another interface clients expect.
ld
● Adapter lets classes work together that couldn't otherwise because of
incompatible interfaces.
or
● Also known as Wrapper
● You want to use an existing class, and its interface does not match the one
you need
Client
W
TargetInterface
targetMethod()
TU
adaptee
Adapter Adaptee
JN
targetMethod() aMethod()
Decorator Pattern
● A flexible alternative to subclassing for extending functionality
ld
● Also known as Wrapper
or
W
Decorator2
aMethod() Decorator1
aMethod() Component
TU
aMethod()
JN
Observer Pattern
ld
● Define a one-to-many dependency between objects so that when one object
changes state, all its dependants are notified and updated automatically
or
classes tightly coupled
W
Subject Observer
observers
addObserver() notify()
TU
removeObserver()
notify()
JN
Strategy Pattern
ld
● Define variants of algorithms, encapsulate each one, and make them
interchangeable Clients can use different algorithms when needed.
or
SortArray SortStrategy
W
sortStrategy
sort() sort()
TU
BubbleSort QuickSort
sort() sort()
JN
Composite Pattern
ld
● Compose objects into three structures
or
Component
W
operation()
TU
Leaf Composite
children
operation() operation()
JN
ld
● In the case when
● A system should be independent of how its products are created,
or
● A family of related product objects is designed to be used together
and you need to enforce this constraint
● e.g. Consider a VLSI design tool. The class to instantiate an AND gate may
W
vary depending on the configuration set by the designer.
Singleton Pattern
ld
● To make sure there is only one instance of a class and it is accessible globally
Singleton
or
static instance()
class Singleton {
W
private static Singleton uniqueInstance = new Singleton();
...
private Singleton(){
...
}
TU
public static Singleton instance() {
return uniqueInstance;
}
...
JN
ld
● A collection is an object that represents a group of objects
or
● Increases performance
W
● Fosters software reuse
● 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
JN
criteria
java.util.Vector
ld
● Is a List
● implements a growable array of objects.
● Like an array, it contains components that can be accessed using an integer
index.
or
● However, the size of a Vector can grow or shrink as needed to accommodate
adding and removing items after the Vector has been created.
Ex.9
W
Vector fruits = new Vector();
fruits.add(“apple”);
fruits.add(“orange”);
fruits.add(“potato”); Run this code
fruits.remove(“potato”); and change it to use
TU
fruits.contains(“potato”); generics
fruits.size();
fruits.elementAt(0);
{
System.out.println(e.nextElement());
}
ld
●Using java.util.Vector class and Adapter pattern, write a SortedVector class
that implements a SortedCollection interface that has methods:
or
● Object elementAt(int index)
● Enumeration elements()
● int size()
W
● public class SortedVectorTest {
public SortedVectorTest() {}
java.util.Stack
● represents a last-in-first-out (LIFO) stack of objects.
ld
● extends class Vector with five operations that allow a vector to be treated
as a stack.
● The usual push and pop operations are provided,
or
● a method to test for whether the stack is empty,
W
Ex.11
Stack fruits = new Stack();
fruits.push(“apple”);
TU
fruits.push(“orange”); Run this code
fruits.push(“potato”); and change it to use
fruits.pop(); generics
fruits.search(“potato”);
fruits.isEmpty();
JN
ld
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.
or
Prefix Notation Infix Notation
- / +*abcde ((((a*b)+c)/ d)- e)
W
/ - ab*c+de ((a- b)/ (c*(d+e)))
java.util.Hashtable
● This class implements a hashtable, which maps keys to values.
ld
● Any non-null object can be used as a key or as a value.
or
Ex.13
Hashtable phoneBook = new Hashtable();
phoneBook.put("A", "+41111111111"); Run this code and
W
phoneBook.put("B", "+41222222222"); change it to use
phoneBook.put("C", "+41333333333"); generics
if(phoneBook.containsKey("D"))
phoneBook.remove("D");
TU
for(java.util.Enumeration e= phoneBook.keys(); e.hasMoreElements(); )
{
Object key = e.nextElement();
System.out.println(key + ": " + phoneBook.get(key) );
JN
Hashtable Exercises
ld
Ex.14
● Write a Dictionary class by which you can
or
● Retrieve a specified word
W
Ex.15
● Using java.util.Hashtable class, write a HashtableAdapter class that
● Enumeration keysInPutOrder()
ld
● java.util.Collections class provides static methods that operate on collections.
● For example,
or
● static void sort(List list)
● Sorts the specified list into ascending order, according to the natural
W
● Sorts the specified list according to the order induced by the specified
comparator.
● Strategy pattern
TU
● Similar to sorting, you can use other algorithms (like shuffle, search) of
Collections class.
JN
ld
public SortTest() {
list.addElement(new String("grape"));
or
list.addElement(new String("apple"));
list.addElement(new String("orange"));
list.addElement(new String("cherry"));
}
W
public void sort() {
Collections.sort(list);
} Run this code!
TU
public void print() {
System.out.println(list);
}
s.sort();
s.print();
}
}
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
● Using Strategy pattern write AgeComparator, HeightComparator classes
deriving from Comparator interface.
or
● Make a test to sort people according to their age and their height.
W
TU
JN
Input/Output Operations
● Fundamental concept is a stream.
ld
● Stream: flow of data from a source to a destination.
or
Source Destination
W
● Java provides two fundamental classes that abstracts this phenomenon.
● java.io.InputStream
● java.io.OutputStream
These two classes are byte-oriented.
TU
●
● java.io.Reader
● java.io.Writer
JN
java.io.InputStream
● Is an abstract class
ld
● 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.
or
Source Program
java.io.OutputStream
W
TU
● Is an abstract class
● Has abstract write(int)
JN
Destination Program
File I/O
ld
● java.io.FileInputStream
● java.io.FileOutputStream
● Ex. 18
or
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
W
which accesses the disk every time it is called.
● Similarly for write.
java.io.BufferedInputStream
ld
● Constructed from an InputStream object.
BufferedInputStream
● Holds inside a buffer as an array.
read()
or
● Acts as a decorator (remember previous lecture)
InputStream
● Supports marking and reseting
java.io.BufferedOutputStream
W
TU
● Constructed from an OutputStream object.
BufferedOutputStream
● Holds inside a buffer as an array.
write()
JN
ld
● Ex. 19
● Understand the code in BufferedCopy.java
or
● Test results for a file ~4.5Mb
W
real 0m51.405s
user 0m11.245s
sys 0m35.818s
java.io.DataInputStream
● Constructed from an InputStream object.
ld
● Allows reading primitive Java data types from the underlying InputStream
object.
● Works in a machine-independent way.
● Acts as a decorator
or
DataInputStream
read()
W
InputStream
java.io.DataOutputStream
TU
● 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
JN
write()
OutputStream
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
Data IO (ex.20)
● Using DataInputStream, DataOutputStream, FileInputStream, FileOutputStream
ld
classes,
or
● Write an application in which you retrieve what you have written from the file.
W
TU
JN
A Short Introduction to
Multi-threaded Programming in Java
ld
● Thread: is a thread of execution in a program.
or
1) Extending from Thread class and overriding the run() method.
W
...
public void run()
{
...
}
TU
}
m.start();
A Short Introduction to
Multi-threaded Programming in Java
ld
2) Implementing Runnable interface and providing the Runnable
object as an argument to the constructor of Thread.
or
public class MyClass implements Runnable {
...
public void run()
{
W
...
}
}
TU
Somewherelse in your code
ld
● java.io.PipedInputStream
● java.io.PipedOutputStream
or
Pipe
Thread Thread
W
TU
● Ex.21
● Understand the code in PipeTest.java,
ld
● Extensive use of design patterns
● Strategy
● Container's layout manager (FlowLayout, BorderLayout, GridbagLayout)
or
● TextComponent's validator (Numeric, AlphaNumeric, TelNumber)
● Composite
● See java.awt.Container extends java.awt.Component. Attention to paint()
W
method.
● Observer
● See java.util.EventListener and all of its subclasses
TU
● Abstract Factory
● See java.awt.Toolkit and all of its create methods
● Singleton
● e.g. Toolkit instance is never created by the programmers, see
JN
ld
● Let's see things in action and create a simple calculator
or
W
TU
JN
ld
import org.dom4j.*;
import org.dom4j.io.*;
import java.util.List;
or
public class XMLTest {
Element modelRoot;
public XMLTest() {}
W
public static void main(String[] args){
Document document = DocumentHelper.createDocument();
Element projectRoot = document.addElement( "Automata");
Element automataRoot = projectRoot.addElement("Automaton")
.addAttribute("name", "preg1");
TU
Element eventsElement = automataRoot.addElement("Events");
ld
try
{
XMLWriter writer = new XMLWriter( new FileWriter("test1.xml") );
writer.write( document );
or
writer.close();
}
catch(Exception e)
{
W
System.out.println("exception");
}
TU
JN
ld
newElement.addAttribute("id", "e3");
List eventsList = eventsElement.content();
eventsList.add(3, newElement);
or
// lets write to a file
try
{
W
XMLWriter writer = new XMLWriter( new FileWriter("test2.xml") );
writer.write( document );
writer.close();
}
catch(Exception e)
TU
{
System.out.println("exception");
}
}
JN
You can obtain dom4j.jar from www.dom4j.org
Downloaded From JNTU World (http://www.alljntuworld.in)
www.alljntuworld.in JNTU World
ld
● To see the assignment, visit:
http://www.alari.ch/people/derino/Teaching/Java/Pishti/index.php
or
W
TU
JN
ld
● ALaRI CfP tracker lists open and closed call for papers at the following address:
http://www.alari.ch/NewsAndEvents/cfp
or
● wget http://www.alari.ch/NewsAndEvents/cfp/es/cfp.xml
● wget http://www.alari.ch/NewsAndEvents/cfp/es/cfp-past.xml
W
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
TU
XYZ'10
ABC'09
ABC'10
DEF'09
ABC'11
JN
February
...
ld
● ALaRI CfP tracker lists open and closed call for papers at the following address:
http://www.alari.ch/NewsAndEvents/cfp
or
● wget http://www.alari.ch/NewsAndEvents/cfp/es/cfp.xml
write a program that creates a file in the webcal format listing the upcoming
W
CfPs according to their submission due dates.
TU
JN
ld
● Tell me about your own idea, once approved, do it as your final assignment!
or
W
TU
JN
References
ld
● 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
or
● Jeff Friesen’s Book: Java 2 By Example, Second Edition
W
TU
JN