introduction   la programmation java - irisa

48
Programmation 2 Introduction à la programmation Java

Upload: others

Post on 09-Feb-2022

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction   la programmation Java - Irisa

Programmation 2Introduction à la programmation Java

Page 2: Introduction   la programmation Java - Irisa

Course information

• Lectures: 6 x 2 hours

• TPs: 6 x 2 hours

• Lecturer: Alexandru Costan alexandru.costan at inria.fr

• TP instructor: Delphine Demange delphine.demange at irisa.fr

Page 3: Introduction   la programmation Java - Irisa

Contents

• Introduction to Java programming language

• Inheritance and applications

• Introduction to Swing

• Swing interactions

• Threads

• Perspectives

Page 4: Introduction   la programmation Java - Irisa

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, 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/celtique/demange/ens/prog2/

Page 5: Introduction   la programmation Java - Irisa

Evaluation

• Small project: 20%

• Main project: 50%

• Written exam: 30%

Page 6: Introduction   la programmation Java - Irisa

Introduction to Java programming language

Page 7: Introduction   la programmation Java - Irisa

History• 1991: developed by Sun Microsystems as a small

programming language for embedded household devices

• Initially called Oak

• 1995: Java 1.0 released

• “Write Once, Run Anywhere”

• Became popular with webpages running applets

• 1997: Standard

• SDK

• JRE

Page 8: Introduction   la programmation Java - Irisa

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 programming language / technology

• Portable, safe

• Object-oriented, component-oriented

Page 9: Introduction   la programmation Java - Irisa

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

Page 10: Introduction   la programmation Java - Irisa

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

Page 11: Introduction   la programmation Java - Irisa

Types of Java applications

• Desktop application - J2SE

• Java Application: normal Java application running on desktops; console or GUI

• Java Applet: embedded application running within Web browsers

• Server application - J2EE

• JSP, Servlets

• Mobile (embedded) application – J2ME

• Java Card

• Java RMI - distributed programming

Page 12: Introduction   la programmation Java - Irisa

Types of Java applications

• Desktop application - J2SE

• Java Application: normal Java application running on desktops; console or GUI

• Java Applet: embedded application running within Web browsers

• Server application - J2EE

• JSP, Servlets

• Mobile (embedded) application – J2ME

• Java Card

• Java RMI - distributed programming

Page 13: Introduction   la programmation Java - Irisa

Object Oriented Programming

• Procedural programming vs. OOP

• Limitations of procedural programming:

• Data are separated from processes

• Passive data, active processes

• No guarantee of data consistancy and constrainsts

• Difficulty in code maintenance

Page 14: Introduction   la programmation Java - Irisa

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 have something done to them

• Create a “type”(class) for these objects so that you don’t have to redo all the work in defining an objects properties and behavior

Page 15: Introduction   la programmation Java - Irisa

Hello World

• Compile: javac TestGreeting.java

• Run: java TestGreeting

• Result: Hello, world

Page 16: Introduction   la programmation Java - Irisa

Classes

• Are the templates to create objects (by instantiation)

• Each object has the same structure and behavior as the class from which it was created

Page 17: Introduction   la programmation Java - Irisa

Declaring a class

public class CLASSNAME {

}

Page 18: Introduction   la programmation Java - Irisa

Declaring a class

public class CLASSNAME {

}

fields

methods

Page 19: Introduction   la programmation Java - Irisa

Classes

• Definition

• Instance

Page 20: Introduction   la programmation Java - Irisa

Constructors• Every class has a special “method”(s) called constructor to

initialise objects’ data members

• A constructor is invoked when an object is to be “created”/ “allocated” by using the new operator

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, a default constructor that requires no arguments and does nothing will be automatically provided.

Page 21: Introduction   la programmation Java - Irisa

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;

}}

Page 22: Introduction   la programmation Java - Irisa

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

Page 23: Introduction   la programmation Java - Irisa

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

Page 24: Introduction   la programmation Java - Irisa

Primitive data types

Page 25: Introduction   la programmation Java - Irisa

Assignment operator “=“

• Copy the reference's content, NOT the referred object

Baby tom = new Baby("Tom", 2);Baby alex = new Baby("Alex", 3);

tom = alex

alex.weight = 5;

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

Page 26: Introduction   la programmation Java - Irisa

Assignment operator “=“

• Copy the reference's content, NOT the referred object

Baby tom = new Baby("Tom", 2);Baby alex = new Baby("Alex", 3);

tom = alex

alex.weight = 5;

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

Page 27: Introduction   la programmation Java - Irisa

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

Page 28: Introduction   la programmation Java - Irisa

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

Page 29: Introduction   la programmation Java - Irisa

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

Page 30: Introduction   la programmation Java - Irisa

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

Page 31: Introduction   la programmation Java - Irisa

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

Page 32: Introduction   la programmation Java - Irisa

The this reference• this: the reference that points to the current object

(from inside).

• usage of this:

• explicit reference to object’s attributes and methods

• parameter passing and return value

• calling constructor from inside constructor

Page 33: Introduction   la programmation Java - Irisa

The this reference• this: the reference that points to the current object

(from inside).

• usage of this:

• explicit reference to object’s attributes and methods

• parameter passing and return value

• calling constructor from inside constructor

Page 34: Introduction   la programmation Java - Irisa

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

Page 35: Introduction   la programmation Java - Irisa

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

Page 36: Introduction   la programmation Java - Irisa

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

Page 37: Introduction   la programmation Java - Irisa

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

Page 38: Introduction   la programmation Java - Irisa

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

Page 39: Introduction   la programmation Java - Irisa

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 strings

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

Page 40: Introduction   la programmation Java - Irisa

Constant data

• final attribute

• primitive data types: constant values

• reference types: constant references

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

Page 41: Introduction   la programmation Java - Irisa

Constant data

• final attribute

• primitive data types: constant values

• reference types: constant references

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

Page 42: Introduction   la programmation Java - Irisa

Constant data

• final attribute

• primitive data types: constant values

• reference types: constant references

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

Page 43: Introduction   la programmation Java - Irisa

Constant data

• final attribute

• primitive data types: constant values

• reference types: constant references

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

Page 44: Introduction   la programmation Java - Irisa

Constant data

• final attribute

• primitive data types: constant values

• reference types: constant references

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

Page 45: Introduction   la programmation Java - Irisa

Constant data

• final attribute

• primitive data types: constant values

• reference types: constant references

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

Page 46: Introduction   la programmation Java - Irisa

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 RuntimeException

ex: IOException, NullPointerException, NumberFormatException, IndexOutOfBoundsException

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

Page 47: Introduction   la programmation Java - Irisa

Create your own exceptions• By extending the java.lang.Exception class

• Typically define constructor(s) and redefine the toString() methodpublic 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();

Page 48: Introduction   la programmation Java - Irisa

To take away

• object oriented programming language

• data centric

• classes: models; objects: instances

• objects handled through references

• extensive API