Programmation 2 - irisa.fr · Data types •Java is a strongly typed language • Every variable...

40
Programmation 2 Introduction à la programmation Java 1

Transcript of Programmation 2 - irisa.fr · Data types •Java is a strongly typed language • Every variable...

Programmation 2Introduction à la programmation Java

1

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.fr

2

Contents

• Introduction to Java programming language

• Graphical interfaces: Swing

• Threads

• Network communication and Internet Java programming

• Programming with Big Data: Hadoop Map Reduce

3

Readings•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 website

• http://www.irisa.fr/kerdata/people/Alexandru.Costan/prog2/

4

Evaluation

• Project: 70%

• Written exam: 30%

5

Introduction to Java programming language

6

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 8

James Gosling - designer of Java

7

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

• Features

• Built-in multi-threading8

Java vs. C based OOP• C++

• pointers

• machine dependent

• no memory management support

• C#

• different support for generics

• no checked exceptions

• no anonymous inner classes9

Compiling 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 forWindows

Java VM forLinux

Java VM forMac OS

10

Hello World

• Compile: javac TestGreeting.java

• Run: java TestGreeting

• Result: Hello, world11

Access modifiers

• public: Accessible anywhere by anyone

• protected: Accessible only to the class itself and to its subclasses or other classes in the same “package”

• private: Only accessible within the current class

• default (no keyword): accessible within the current package

12

Data 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 references

• GradeBook myGradeBook = new GradeBook();13

Reference 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 content

public 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

Heap memory

14

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 same

int n1 = 1;int n2 = 1;System.out.println(n1 == n2); //true

Baby baby1 = new Baby("Tom");Baby baby2 = new Baby("Tom");System.out.println(baby1 == baby2); //false

15

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 available

• Clean-up tasks must be done explicitly by other “clean-up” methods

16

Packages

•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.lang• ex: java.lang.String; java.lang.System

17

Packages• Definition

package path.to.package.foo;class Foo{...}

• Usage

import path.to.package.foo.Foo;

import path.to.package.foo.*;

• Specific packages

java.lang, java.util, java.io, java.awt, java.net, java.applet

18

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 object

• normally enables a program to input bytes from the keyboard

19

Strings• 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 strings

StringBuffer sb1 = new StringBuffer(ch1); sb1.append('x'); sb1.insert(3,"yyy");

20

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 attributes

• can't call non-static methods

21

Constant 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 subclasses

final int number = 7;number = ...; //NO!number++; //NO!final Robot R2D2 = new Robot();R2D2 = ...; //NO!R2D2.positionX = 15; //YES!R2D2.positionY = 20; //YES!

22

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 try

• handled with the instruction catch

23

Exception handlingIf 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, typically for cleanup purposes (closing files, freeing resources)

24

Exception handling

Credits: Eric Anquetil

25

Java standard exceptions

ex: NullPointerException, NumberFormatException, IndexOutOfBoundsException

26

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

System.out.println(“Exception” + e); //cf. toString}27

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 superclass

• have all members of the superclass plus some more 28

java.lang.Object

• The root of the class hierarchy:

• every class has Object as a superclass

• Provides a number of methods that are common to all objects (including arrays):

•clone()

•equals(Object o)

•hashCode()

•finalize()

•toString()

• + synchronisation methods

29

You can only inherit from one class

30

Chaining constructors•When a class defines no constructor, the compiler will

automatically 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(...)

• super() or this() are called on the first line of the new constructor31

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(...)

32

Polymorphism

• "exist in many forms"

• Object polymorphism: an object can be treated in different ways

• A Manager object can be seen as an Employee object as well

• Method polymorphism: calling a method overrode 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"?

33

Object polymorphism: Upcasting

• Cast "up" the inheritance diagram

• Take an object reference and treat it as if it refers to its base type

Cat c = new Cat("Tom"); Animal a = c; // upcasting

• Cannot invoke methods not provided by the base type

a.chaseTail(); //Error! method not found in class Animal

• But

a.makeASound(); //"Meow…", Cat's makeASound() gets to run

34

Object polymorphism: Downcasting

• Cast "down" the inheritance diagram

Animal 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

• java.lang.ClassCastException35

Method polymorphismAnimal pet1 = new Cat("tom"); Animal pet2 = new Cow("mini"); ... pet1.makeASound(); pet2.makeASound();

• The same message is interpreted differently depending on the object's type:

Dynamic binding36

Dynamic binding

• Method binding: connect a method call to a method 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.

• private methods are implicitly final.

37

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

38

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

39

Generic methods

public <T> void inspect(T t) {

System.out.println("T: " + t.getClass().getName());

}

...

<String>inspect(String s);

optional40