Programmation 2
Course information
•
CM: 6 x 2 hours•
TP: 6 x 2 hours•
CM: Alexandru Costan alexandru.costan at inria.fr•
TP: Vincent Laporte vincent.laporte at irisa.frContents
•
Introduction to Java programming language•
Graphical interfaces: Swing•
Threads•
Network communication and Internet Javaprogramming
•
Programming with Big Data: Hadoop MapReadings
•
Main references (Oracle)• The Java Language Specification
• The Java Virtual Machine Specification
• The Java Tutorial Books
• Java Series Books
•
Further readings• Le langage Java: Concepts et pratique -le JDK 5.0, Irène Charon
• Introduction à la programmation objet en Java: Cours et exercices, Jean Brondeau
• Algorithmique et programmation en Java: Cours et exercices corrigés, Vincent Granet
• Java 2.0: De l'esprit à la méthode, Michel Bonjour, Gilles Falquet, Jacques Guyot, André Le Grand
• Algorithms in Java: Fundamentals, Data Structures, Sorting, Searching, and Graph Algorithms, Robert Sedgewick
•
Course websiteEvaluation
•
Project: 70%Introduction to Java
programming language
History
•
1991: developed by Sun as a small programming language for embedded household devices•
1995: Java 1.0 released•
“Write Once, Run Anywhere”•
Became popular with webpages running applets•
1997: Standard - SDK, JRE•
1998: Java 1.2 - J2EE, J2ME, J2SE•
2004: Java 5 - Collections, Enumerate, Concurrent•
2014: Java 8James Gosling - designer of Java
Why Java?
•
Easy to use•
Addresses the weaknesses of older programming languages•
Object-oriented•
Supports good programming styles•
Portability•
Interpreter environment•
Safe•
Data always initialised, references always type-safe•
FeaturesJava vs. C based OOP
•
C++•
pointers•
machine dependent•
no memory management support•
C#•
different support for generics•
no checked exceptionsCompiling and interpreting
•
Program source code compiled into bytecode•
Bytecode is executed in an interpreter environment (Virtual Machine)Java program .java Compiler Java bytecode program .class Java VM for Windows Java VM for Linux Java VM for Mac OS
Hello World
•
Compile: javac TestGreeting.java•
Run: java TestGreetingAccess modifiers
•
public: Accessible anywhere by anyone•
protected: Accessible only to the classitself and to its subclasses or other classes in the same “package”
•
private: Only accessible within the currentclass
•
default (no keyword): accessible within the current packageData types
•
Java is a strongly typed language•
Every variable must have a declared type•
There are two kinds of data types•
Primitive data types•
Variables are manipulated via variable names•
int a = 5;•
have wrapper types: int/Integer, char/Character, double/Double etc.•
Reference types•
Arrays and objects•
Manipulated via referencesReference types
•
Objects are manipulated via references•
Object references store object locations in computer’s memory•
NO explicit pointers in Java (no direct access to the references)•
NO pointer operators•
Directly handle attributes and methods•
Assignments (=) of references do NOT copy object’s contentpublic class Baby{ String name; boolean isMale; int weight;
public Baby(String n, int w){ name = n;
isMale = true; weight = w; }
Baby tom = new Baby(“Tom”,2); Baby alex = new Baby(“Alex”,3); tom = alex;
alex.weight=5;
System.out.print(tom.weight);
Baby tom name
isMale weight
a Baby object
Equality operators: “==“and “!=“
•
Compare the content of the variables•
Value of primitive data•
Value of references•
i.e. check if they point to the same object, NOT whether the content of the objects are the sameint n1 = 1; int n2 = 1;
System.out.println(n1 == n2); //true Baby baby1 = new Baby("Tom");
Baby baby2 = new Baby("Tom");
Garbage collection
•
To reclaim the memory occupied by objects that are no longer in use•
Programmers don’t have to deallocate objects•
Java Virtual Machine (JVM) performs automatic garbage collection•
Method finalize() is called by JVM, not by programmers•
Guarantees no memory leaks•
However, there’s no guarantee when/whether an object is freed before the program terminates•
Might not be needed as memory is still availablePackages
•
Each class belongs to a package•
Classes in the same package serve a similar purpose•
Packages are just directories•
Classes in other packages need to be imported•
All classes "see" classes in the same package (no import needed)•
All classes "see" classes in java.langPackages
•
Definition package path.to.package.foo; class Foo{ ... }•
Usage import path.to.package.foo.Foo; import path.to.package.foo.*;•
Specific packagesjava.lang, java.util, java.io, java.awt, java.net, java.applet
Standard I/O
•
Three stream objects automatically created when a Java program begins executing•
System.out: standard output stream object•
normally enables a program to output data to the screen (console)•
ex: System.out.println("some text");•
System.err: standard error stream object•
normally enables a program to output error messages to the screen•
System.in: standard input stream objectStrings
•
String - constant strings (non-modifiable)String r = “essai”;
String s = “es”+”sai”;
String t = “ESSAI”.toLowerCase(); int i =r.indexOf('i');
char c = s.charAt(3);
int comp =r.compareTo(s); boolean test1 = (r==s); boolean test2 = (r==t)
•
StringBuffer - mutable stringsStringBuffer sb1 = new StringBuffer(ch1); sb1.append('x');
Static types and methods
•
Applies to fields and methods•
Means the field/method•
is defined for the class declaration•
is unique for all instances•
Static methods•
can't access non-static attributesConstant data
•
final keyword•
primitive data types: constant values•
reference types: constant references•
final class cannot be subclassed•
final method cannot be overridden or hidden by subclassesfinal int number = 7; number = ...; //NO! number++; //NO!
final Robot R2D2 = new Robot(); R2D2 = ...; //NO!
R2D2.positionX = 15; //YES! R2D2.positionY = 20; //YES!
Exception handling
•
Allows to forward the exception handling in a
qualified context (at a higher level)
•
Simplifies the code through a recentralisation
of exception handling
•
Exceptions
•
triggered with the instruction throw•
caught in a block tryException handling
If a method p() uses an instruction susceptible to trigger an
exception:
• catch and handle the exception
void p(){ ...
try { ... exception ...}
catch(xxxException e){//handling e} }
• or, propagate the exception
void p() throws xxxException{
... if(some test) throw new xxxException() ...}
finally{ ... } associated with a try{...} block,
Java standard exceptions
ex: NullPointerException, NumberFormatException, IndexOutOfBoundsException
Create your own exceptions
•
By extending the java.lang.Exception class•
Typically define constructor(s) and redefine the toString() method public class ExceptionRien extends Exception {int nbChaines;
public ExceptionRien(int nombre) { nbChaines = nombre;
}
public String toString() {
return "ExceptionRien : aucune des " + nbChaines + " chaines n'est valide";
} }
•
Usage:... throw new ExceptionRien(n);
•
Handling:try {…} catch (ExceptionRien e){
System.out.println(e.getMessage()); //ou
Inheritance
•
Based on "is-a" relationship•
Subclass: more specialised•
Superclass: more general•
Subclass is derived or inherits from superclass hence, the terms 'derived class' and 'base class' respectively•
extends keyword•
Objects of a subclass•
can be treated as objects of its superclassjava.lang.Object
•
The root of the class hierarchy:•
every class has Object as a superclass•
Provides a number of methods that arecommon to all objects (including arrays):
•
clone()•
equals(Object o)•
hashCode()•
finalize()•
toString()•
+ synchronisation methodsYou can only inherit
from one class
Chaining constructors
•
When a class defines no constructor, the compiler willautomatically add one:
class MaClasse { MaClasse() { super(); } ... }
•
super() - calls the constructor of the superclass•
All constructors (except those of java.lang.Object)call another constructor:
•
a constructor of the superclass: super(...)•
another constructor of the same class: this(...)Virtual methods
•
A subclass can override (redefine) methods inherited from its superclass.•
to specialise these methods to suit the new problem•
NB: override <> overloading•
New and old version must have the same prototype:•
same return type•
same argument types•
Private, final methods cannot be overrode!•
Private members are hidden from subclass•
Objects of the subclass will work with the new version of the methods•
Superclass’s methods of the same name can be reused by using the keyword super.methodName(...)Polymorphism
•
"exist in many forms"•
Object polymorphism: an object can be treatedin different ways
•
A Manager object can be seen as an Employee objectas well
•
Method polymorphism: calling a methodoverrode for different objects which has
different behaviour according to the object type
•
Different objects interpret the same method differently: how do cats and dogs "talk"?Object polymorphism:
Upcasting
•
Cast "up" the inheritance diagram•
Take an object reference and treat it as if it refers to its base typeCat c = new Cat("Tom"); Animal a = c; // upcasting
•
Cannot invoke methods not provided by the base typea.chaseTail();
//Error! method not found in class Animal
•
Buta.makeASound();
//"Meow…", Cat's makeASound() gets to run
Object polymorphism:
Downcasting
•
Cast "down" the inheritance diagramAnimal animal = new Cat("Tom"); //upcast ...
Cat c = (Cat) animal; // downcast c.sayHello(); // "Meow.."
•
But, not always possible. Why?Animal animal = new Animal("Dummy"); ...
Cat c = (Cat) animal; // run-time error
Method polymorphism
Animal pet1 = new Cat("tom"); Animal pet2 = new Cow("mini"); ...
pet1.makeASound(); pet2.makeASound();
•
The same message is interpreted differentlydepending on the object's type:
Dynamic binding
•
Method binding: connect a method call to amethod body
•
Static/early binding: performed by compiler/linker before the program is run.•
the only option of procedural languages.•
Dynamic/late binding: performed at run-time•
Java uses late binding, except for static, final, and private methods.Generic programming
•
Write code that can be
reused
for
objects of many
different types
•
Indicate some type
parameters
instead of actual types
•
Java 1.5: generic classes and
methods
Generic classes
•
General form of a generic class:class A<T1, T2, ...> {...} T1, T2, ... generic parameters
•
Example:class Stack<T>{ //generic stack private int s;
private Object[] P = new Object[100]; public Stack() {s=-1;}
public void push(T e) {s++; P[s]=e}; ...
}
Student toto = new Student("toto",...);
Stack<Student> sStu = new Stack<Student>(); sStu.push(toto);
Generic methods
public <T> void inspect(T t) { System.out.println("T: " + t.getClass().getName()); } ... <String>inspect(String s); optional