introduction à la programmaion java.pdf

Embed Size (px)

Citation preview

  • 7/30/2019 introduction la programmaion java.pdf

    1/48

    Programmation 2Introduction la programmation Java

  • 7/30/2019 introduction la programmaion java.pdf

    2/48

    Course information

    Lectures: 6 x 2 hours

    TPs: 6 x 2 hours Lecturer: Alexandru Costan

    alexandru.costan at inria.fr

    TP instructor: Delphine Demangedelphine.demange at irisa.fr

    mailto:[email protected]:[email protected]:[email protected]
  • 7/30/2019 introduction la programmaion java.pdf

    3/48

    Contents

    Introduction to Java programming language

    Inheritance and applications Introduction to Swing

    Swing interactions

    Threads Perspectives

  • 7/30/2019 introduction la programmaion java.pdf

    4/48

    Readings Main references (Sun)

    The Java Language Specification The Java Virtual Machine Specification The Java Tutorial Books

    Java Series Books (on the Sun website)

    Further readings Le langage Java: Concepts et pratique -le JDK 5.0, Irne Charon Introduction la programmation objet en Java: Cours et exercices, Jean Brondeau Algorithmique et programmation en Java: Cours et exercices corrigs, Vincent Granet Java 2.0: De l'esprit la mthode, Michel Bonjour, Gilles Falquet, Jacques Guyot, Andr

    Le Grand

    Algorithms in Java: Fundamentals, Data Structures, Sorting, Searching, and GraphAlgorithms,Robert Sedgewick

    Course website http://www.irisa.fr/celtique/demange/ens/prog2/

    http://www.amazon.fr/Algorithms-Java-Fundamentals-Structures-Searching/dp/0201775786/http://www.irisa.fr/celtique/demange/ens/prog2/http://www.amazon.fr/Algorithms-Java-Fundamentals-Structures-Searching/dp/0201775786/http://www.amazon.fr/Algorithms-Java-Fundamentals-Structures-Searching/dp/0201775786/http://www.amazon.fr/Algorithmique-programmation-Java-exercices-corrig%C3%A9s/dp/210048463Xhttp://www.amazon.fr/Introduction-programmation-objet-Java-exercices/dp/2100041061http://www.amazon.fr/langage-Java-Concepts-pratique/dp/2746212129http://java.sun.com/docs/books/javatutorial/tutorial-all.htmlhttp://java.sun.com/docs/books/jvms/http://java.sun.com/docs/books/jls/http://www.irisa.fr/celtique/demange/ens/prog2/http://www.irisa.fr/celtique/demange/ens/prog2/http://www.amazon.fr/Algorithms-Java-Fundamentals-Structures-Searching/dp/0201775786/http://www.amazon.fr/Algorithms-Java-Fundamentals-Structures-Searching/dp/0201775786/http://www.amazon.fr/Algorithms-Java-Fundamentals-Structures-Searching/dp/0201775786/http://www.amazon.fr/Algorithms-Java-Fundamentals-Structures-Searching/dp/0201775786/http://www.amazon.fr/Java-2-0-Distribution-dapplications-Internet/dp/2711786471/http://www.amazon.fr/Java-2-0-Distribution-dapplications-Internet/dp/2711786471/http://www.amazon.fr/Algorithmique-programmation-Java-exercices-corrig%C3%A9s/dp/210048463Xhttp://www.amazon.fr/Algorithmique-programmation-Java-exercices-corrig%C3%A9s/dp/210048463Xhttp://www.amazon.fr/Introduction-programmation-objet-Java-exercices/dp/2100041061http://www.amazon.fr/Introduction-programmation-objet-Java-exercices/dp/2100041061http://www.amazon.fr/langage-Java-Concepts-pratique/dp/2746212129http://www.amazon.fr/langage-Java-Concepts-pratique/dp/2746212129http://www.sun.com/books/java_series.htmlhttp://www.sun.com/books/java_series.htmlhttp://java.sun.com/docs/books/javatutorial/tutorial-all.htmlhttp://java.sun.com/docs/books/javatutorial/tutorial-all.htmlhttp://java.sun.com/docs/books/jvms/http://java.sun.com/docs/books/jvms/http://java.sun.com/docs/books/jls/http://java.sun.com/docs/books/jls/
  • 7/30/2019 introduction la programmaion java.pdf

    5/48

    Evaluation

    Small project: 20% Main project: 50%

    Written exam: 30%

  • 7/30/2019 introduction la programmaion java.pdf

    6/48

    Introduction to Javaprogramming language

  • 7/30/2019 introduction la programmaion java.pdf

    7/48

    History

    1991: developed by Sun Microsystems as a smallprogramming language for embedded householddevices

    Initially called Oak

    1995: Java 1.0 released Write Once, Run Anywhere

    Became popular with webpages running applets

    1997: Standard SDK

    JRE

  • 7/30/2019 introduction la programmaion java.pdf

    8/48

    History

    1998: Java 1.2, multiple types of platforms J2EE J2ME

    J2SE 2004: Java 5

    Collections, enumerate concurrent programming

    2006: open source, GPL

    Sun: "Java's evangelist"

    Nowadays, widely accepted as a multi-purpose programminglanguage / technology

    Portable, safe

    Object-oriented, component-oriented

  • 7/30/2019 introduction la programmaion java.pdf

    9/48

    Why Java?

    Easy to use Addresses the weaknesses of older programming languages

    Object-oriented

    Supports good programming styles

    Portability - Interpreter environment Safe

    Data always initialized, references always type-safe Access to "private" or "package private" data and methods is

    rigidly controlled.

    Features

    Built-in multi-threading

  • 7/30/2019 introduction la programmaion java.pdf

    10/48

    Compiling and interpreting

    Program source code compiled into bytecode Bytecode is executed in an interpreter environment

    (Virtual Machine)

    Java

    program.java Compiler

    Javabytecode

    program.class

    Java VM forWindows

    Java VM for

    Linux

    Java VM forMac OS

  • 7/30/2019 introduction la programmaion java.pdf

    11/48

    Types of Java applications

    Desktop application - J2SE Java Application: normal Java application running on

    desktops; console or GUI

    Java Applet: embedded application running within Webbrowsers

    Server application - J2EE

    JSP, Servlets Mobile (embedded) application J2ME Java Card

    Java RMI - distributed programming

  • 7/30/2019 introduction la programmaion java.pdf

    12/48

    Types of Java applications

    Desktop application - J2SE Java Application: normal Java application running on

    desktops; console or GUI

    Java Applet: embedded application running within Webbrowsers

    Server application - J2EE

    JSP, Servlets Mobile (embedded) application J2ME Java Card

    Java RMI - distributed programming

  • 7/30/2019 introduction la programmaion java.pdf

    13/48

    Object Oriented Programming

    Procedural programmingvs. OOP

    Limitations of proceduralprogramming:

    Data are separated from processes

    Passive data, active processes No guarantee of data consistancy

    and constrainsts

    Difficulty in code maintenance

  • 7/30/2019 introduction la programmaion java.pdf

    14/48

    Object Oriented Programming

    Addresses these limitations Data come together with

    related processing code

    Guarantee of data consistency Easier maintenance Define things(objects) which

    can either do something or havesomething done to them

    Create a type(class) for theseobjects so that you dont have toredo all the work in defining an

    objects properties and behavior

  • 7/30/2019 introduction la programmaion java.pdf

    15/48

    Hello World

    Compile:javac TestGreeting.java Run:java TestGreeting

    Result: Hello, world

  • 7/30/2019 introduction la programmaion java.pdf

    16/48

    Classes

    Are the templates to create objects (byinstantiation)

    Each object has the same structure andbehavior as the class from which it was

    created

  • 7/30/2019 introduction la programmaion java.pdf

    17/48

    Declaring a class

    public classCLASSNAME {

    }

  • 7/30/2019 introduction la programmaion java.pdf

    18/48

    Declaring a class

    public classCLASSNAME {

    }

    fields

    methods

  • 7/30/2019 introduction la programmaion java.pdf

    19/48

    Classes

    Definition

    Instance

  • 7/30/2019 introduction la programmaion java.pdf

    20/48

    Constructors

    Every class has a special method(s) called constructor toinitialise objects data members

    A constructor is invoked when an object is to be created/allocated by using the newoperator

    Baby myBaby1 = new Baby();

    A class may have multiple constructors (overloading) Distinguished at compile time by having different parameter lists

    Baby myBaby2 = new Baby("Madonna", false);

    Baby myBaby3 = new Baby("Bono", 2.5);

    When no constructors are defined in source code, adefault constructor that requires no arguments and doesnothingwill be automatically provided.

  • 7/30/2019 introduction la programmaion java.pdf

    21/48

    Constructorspublic class Baby{

    String name;

    boolean isMale;

    double weight;

    public Baby(){

    name = "John Doe";isMale = true;

    weight = 3.1;

    }

    public Baby(String babyName, boolean gender){

    name = babyName;

    isMale = gender;

    weight = 3.1;}

    public Baby(String babyName, double kilos){

    name = babyName;

    isMale = true;

    weight = kilos;

    }

    }

  • 7/30/2019 introduction la programmaion java.pdf

    22/48

    Access modifiers

    public:Accessible anywhere by anyone

    protected:Accessible only to the classitself and to its subclasses or other classes inthe same package

    private: Only accessible within thecurrent class

    default (no keyword): accessible within thecurrent package

  • 7/30/2019 introduction la programmaion java.pdf

    23/48

    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;

    Reference types Arrays and objects Manipulated via references GradeBook myGradeBook = new GradeBook();

  • 7/30/2019 introduction la programmaion java.pdf

    24/48

    Primitive data types

  • 7/30/2019 introduction la programmaion java.pdf

    25/48

    Assignment operator =

    Copy the reference's content, NOT thereferred object

    Baby tom = new Baby("Tom", 2);

    Baby alex = new Baby("Alex", 3);

    tom = alex

    alex.weight = 5;

    System.out.print(tom.weight);// 5

  • 7/30/2019 introduction la programmaion java.pdf

    26/48

    Assignment operator =

    Copy the reference's content, NOT thereferred object

    Baby tom = new Baby("Tom", 2);

    Baby alex = new Baby("Alex", 3);

    tom = alex

    alex.weight = 5;

    System.out.print(tom.weight);// 5

  • 7/30/2019 introduction la programmaion java.pdf

    27/48

    Reference types

    Objects are manipulated via references Object references store object locations in computers 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 objects content

    public class Baby{

    String name;

    boolean isMale;

    double weight;

    public Baby(){

    name = "John Doe";

    isMale = true;

    weight = 3.5;

    }public void eat(double food){

    weight = weight + food;

    }

    Baby tom;

    tom = new Baby();

    tom.eat(2.1);

    Baby tom name

    isMale

    weight

    a Baby object

    Heap memory

  • 7/30/2019 introduction la programmaion java.pdf

    28/48

    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 contentof 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

  • 7/30/2019 introduction la programmaion java.pdf

    29/48

    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 contentof 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

  • 7/30/2019 introduction la programmaion java.pdf

    30/48

    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 contentof 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

  • 7/30/2019 introduction la programmaion java.pdf

    31/48

    Garbage collection

    To reclaim the memory occupied by objects that are nolonger in use

    Programmers dont 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, theres no guarantee when/whether an object isfreed 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

  • 7/30/2019 introduction la programmaion java.pdf

    32/48

    The this reference

    this: the reference that points to the current object(from inside).

    usage ofthis: explicit reference to objects attributes and methods

    parameter passing and return value

    calling constructor from inside constructor

  • 7/30/2019 introduction la programmaion java.pdf

    33/48

    The this reference

    this: the reference that points to the current object(from inside).

    usage ofthis: explicit reference to objects attributes and methods

    parameter passing and return value

    calling constructor from inside constructor

  • 7/30/2019 introduction la programmaion java.pdf

    34/48

    Static types and methods

    Applies to fields and methods Means the field/method

    is defined for the class declaration is not unique for each instance

    Static methods can't access non-static attributes can't call non-static methods

  • 7/30/2019 introduction la programmaion java.pdf

    35/48

    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

  • 7/30/2019 introduction la programmaion java.pdf

    36/48

    Packages Definition

    package path.to.package.foo;

    class Foo{

    ...}

    Usageimport path.to.package.foo.Foo;

    import path.to.package.foo.*;

    Specific packagesjava.lang, java.util, java.io, java.awt,

    java.net, java.applet

  • 7/30/2019 introduction la programmaion java.pdf

    37/48

    Standard I/O

    Three stream objects automatically created when aJava 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 thescreen

    System.in: standard input stream object normally enables a program to input bytes from the keyboard

  • 7/30/2019 introduction la programmaion java.pdf

    38/48

    Arrays

    Indexed list of values: TYPE[] The index starts at 0 and ends at length-1.int[] values;

    values = new int[5];

    int size = values.length;

    int[][] M = new int[3][2];

    int[] primes = {1,2,3,5,7};

  • 7/30/2019 introduction la programmaion java.pdf

    39/48

    Strings

    String - constant strings (non-modifiable)String ch1 = new String("bonjour");

    String ch2 = "au revoir";String ch3 = ch1+ch2;

    int i = ch1.indexOf('j');

    char c = ch2.charAt(3);

    StringBuffer - mutable stringsStringBuffer sb1 = new StringBuffer(ch1);

    sb1.append('x');

    sb1.insert(3,"yyy");

  • 7/30/2019 introduction la programmaion java.pdf

    40/48

    Constant data

    final attribute primitive data types: constant values

    reference types: constant referencesfinal int number = 7;

    number = ...; //NO!

    number++; //NO!

    final Robot R2D2 = new Robot();

    R2D2 = ...; //NO!

    R2D2.positionX = 15; //YES!

    R2D2.positionY = 20; //YES!

  • 7/30/2019 introduction la programmaion java.pdf

    41/48

    Constant data

    final attribute primitive data types: constant values

    reference types: constant referencesfinal int number = 7;

    number = ...; //NO!

    number++; //NO!

    final Robot R2D2 = new Robot();

    R2D2 = ...; //NO!

    R2D2.positionX = 15; //YES!

    R2D2.positionY = 20; //YES!

  • 7/30/2019 introduction la programmaion java.pdf

    42/48

    Constant data

    final attribute primitive data types: constant values

    reference types: constant referencesfinal int number = 7;

    number = ...; //NO!

    number++; //NO!

    final Robot R2D2 = new Robot();

    R2D2 = ...; //NO!

    R2D2.positionX = 15; //YES!

    R2D2.positionY = 20; //YES!

  • 7/30/2019 introduction la programmaion java.pdf

    43/48

    Constant data

    final attribute primitive data types: constant values

    reference types: constant referencesfinal int number = 7;

    number = ...; //NO!

    number++; //NO!

    final Robot R2D2 = new Robot();

    R2D2 = ...; //NO!

    R2D2.positionX = 15; //YES!

    R2D2.positionY = 20; //YES!

  • 7/30/2019 introduction la programmaion java.pdf

    44/48

    Constant data

    final attribute primitive data types: constant values

    reference types: constant referencesfinal int number = 7;

    number = ...; //NO!

    number++; //NO!

    final Robot R2D2 = new Robot();R2D2 = ...; //NO!

    R2D2.positionX = 15; //YES!

    R2D2.positionY = 20; //YES!

  • 7/30/2019 introduction la programmaion java.pdf

    45/48

    Constant data

    final attribute primitive data types: constant values

    reference types: constant referencesfinal int number = 7;

    number = ...; //NO!

    number++; //NO!

    final Robot R2D2 = new Robot();R2D2 = ...; //NO!

    R2D2.positionX = 15; //YES!

    R2D2.positionY = 20; //YES!

  • 7/30/2019 introduction la programmaion java.pdf

    46/48

    Exception handlingIf a method p() uses a method q() susceptible to trigger an exception:

    catch and handle the exception

    void p(){ ...

    try { ... q() ...}

    catch(xxxException e){//handling e}}

    or, propagate the exception

    void p() throws xxxException{ ... q() ...}

    xxxException:derived from Exception or RuntimeExceptionex: IOException, NullPointerException,

    NumberFormatException, IndexOutOfBoundsException

    finally{ ... } associated with a try{...} block, typically forcleanup purposes (closing files, freeing resources)

  • 7/30/2019 introduction la programmaion java.pdf

    47/48

    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;

    }

    publicString toString() {

    return "ExceptionRien : aucune des " + nbChaines + "

    chaines n'est valide";}

    }

    Usage:... throw new ExceptionRien();

  • 7/30/2019 introduction la programmaion java.pdf

    48/48

    To take away

    object oriented programming language

    data centric classes: models; objects: instances

    objects handled through references

    extensive API