JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via...

25
JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dell’Informazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 [email protected] www.dii.unisi.it/ ~rigutini /

Transcript of JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via...

Page 1: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

JDK

Dott. Ing. Leonardo RigutiniDipartimento Ingegneria dell’InformazioneUniversità di SienaVia Roma 56 – 53100 – SIENAUff. [email protected]/~rigutini/

Page 2: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

Libreria standard JAVA

Fornisce una grande varietà di classi per facilitare lo sviluppo di applicazioni

Organizzata come una gerarchia di packages

Disponibile il JavaDOC in rete: http://java.sun.com/j2se/1.5.0/docs/index.html

Vediamo le classi principali che potrebbero essere utili nello sviluppo di applicazioni

Page 3: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

Gerarchia

java.lang

java

java.util

java.io

java.text

java.math

java.awt

javax.swing

java.applet

java.beans

java.sql

java.rmi

java.net

java.security

javax

javax.sql javax.xml

Page 4: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

java.lang

Class Summary

Boolean The Boolean class wraps a value of the primitive type boolean in an object.

Byte The Byte class wraps a value of primitive type byte in an object.

Character The Character class wraps a value of the primitive type char in an object.

Double The Double class wraps a value of the primitive type double in an object.

Float The Float class wraps a value of primitive type float in an object.

Tratto dal javaDoc

Page 5: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

java.lang

Class Summary

Integer The Integer class wraps a value of the primitive type int in an object.

Long The Long class wraps a value of the primitive type long in an object

MathThe class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.

String The String class represents character strings.

System The System class contains several useful class fields and methods.

Thread A thread is a thread of execution in a program.

Throwable The Throwable class is the superclass of all errors and exceptions in the Java language.

Page 6: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

La classe Object

Come già detto la classe Object è la classe root di tutte le classi

Fornisce una serie di funzioni che normalmente devono essere sovrascritte (override)

Vedere JavaDoc

Page 7: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

Classi wrapper

Come si vede esistono nel package molte classi che sembrano avere lo stesso nome dei tipi di dato semplici: Boolean, Double, Float, Integer, ecc …

Queste classi sono dette classi wrapper e sono utilizzate per “wrappare” i tipi di dato semplice in classi:

double indica una variabile che memorizza valori con virgola di tipo double;

Double è un oggetto che rappresenta un double che ha particolari metodi per la lettura, la conversione dei double, ecc …

Vedere il JavaDoc

Page 8: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

Classe String

La classe String rappresenta le stringhe di caratteri. Ogni parola, frase, documento è una stringa di caratteri.

La classe String include metodi per esaminare i singoli caratteri, comparare stringhe, ricercare ed estrarre sottostringhe, portare tutto minuscolo o maiuscolo, concatenare ecc …

JavaDoc

Page 9: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

La classe math

La classe Math mette a disposizioni funzioni matematiche statiche che possono essere quindi utilizzate senza necessità di istanziare oggetti di tipo Math:

Fornisce anche due costanti statiche di tipo double :

Vedere il JavaDoc

double a=1.44;

double b=3;

double c=Math.sqrt(a); c=1.2

double p=Math.pow(a,b); p = 2,9859

Math.E numero di nepero (e=2,71) Math.PI pi greco (pi=3.14)

Page 10: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

La classe System

La classe System contiene alcune variabili e funzioni di sistema: Lo stdout, sterr e stdin sono variabili statiche di questa classe

JavaDoc

Page 11: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

Il package java.io

Questo package fornisce classi per facilitare la lettura e scrittura di dati

L’idea è che ogni operazione di Input/Output avviene tramite uno stream: oggetto che realizza un flusso di dati che possono essere letti o scritti

Per facilitare operazioni più complesse il JDK mette a disposizione classi Reader e Writer: Le classi Reader si agganciano a stream di input e permettono la lettura

dei dati Le classi Writer si agganciano a stream di output e permettono la

scrittura di dati

Page 12: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

I/O

L’idea è quella di creare una pipeline tra stream ed operazione: InputStream->Reader->Lettura OutputStream->Writer->Scrittura

Tale pipeline viene realizzata creando a cascata oggetti che prendono in ingresso gli oggetti a cui si devono agganciare:

FileInputStream fis=new FileInputStream(“c:\\prova.txt”);

InputStreamReader isr=new InputStreamReader(fis);

String carattereletto=isr.read();

isr.close();

fis.close();

Page 13: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

I/O

Per alcuni stream comuni le classi Reader e Writer hanno lo stream nascosto al loro interno:

Per leggere più di un carattere alla volta è necessario utilizzare un BufferedReader che si aggancia ad un Reader:

FileReader fis=new FileReader(“c:\\temp\prova.txt”);

fis.read();

fis.close();

FileReader fis=new FileReader(“c:\\temp\prova.txt”);

BufferedReader br=new BufferedREader(fis);

br.readLine();

br.close();

fis.close();

Page 14: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

Il package java.io

Class Summary

BufferedInputStreamA BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods.

BufferedOutputStream The class implements a buffered output stream.

BufferedReaderRead text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

BufferedWriterWrite text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

File An abstract representation of file and directory pathnames.

FileInputStream A FileInputStream obtains input bytes from a file in a file system.

FileOutputStream A file output stream is an output stream for writing data to a File or to a FileDescriptor.

Page 15: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

Il package java.io

Class Summary

FileReader Convenience class for reading character files.

FileWriter Convenience class for writing character files.

InputStream This abstract class is the superclass of all classes representing an input stream of bytes.

OutputStream This abstract class is the superclass of all classes representing an output stream of bytes.

OutputStreamWriterAn OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset.

PrintStreamA PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently.

PrintWriter Print formatted representations of objects to a text-output stream.

Reader Abstract class for reading character streams.

Page 16: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

Il package java.io

Class Summary

StreamTokenizerThe StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time.

StringReader A character stream whose source is a string.

StringWriter A character stream that collects its output in a string buffer, which can then be used to construct a string.

Writer Abstract class for writing to character streams.

Page 17: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

I Thread

L’esecuzione di una funzione di una classe è bloccante: prima di passare oltre è necessario attendere che la funzione sia

terminata

Quando i compiti da svolgere sono “indipendenti” è possibile eseguire una funzionalità in modalità nascosta: thread

In java esistono due modalità per eseguire una funzionalità in modalità nascosta: La classe Thread La classe Runnable

Tale soluzione può essere utilizzata per eseguire operazioni in parallelo

Page 18: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

La classe Thread

La classe Thread è una classe fornita nel JDK

Per eseguire una funzionalità in modalità thread:1. rendere la classe che implementa la funzionalità come classe derivata di

Thread:

1. implementare la funzione run() della classe realizzando la funzionalità desiderata

1. In esecuzione, creare oggetti di quel tipo e avviarli in modalità thread utilizzando la funzione start():

Esempio e=new Esempio();e.start();

public class Esempio exends Thread

Page 19: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

La classe Runnable

In realtà la classe Thread è una implementazione della classe Runnable

E’ possibile creare un thread:1. implementando l’interface Runnable:

1. Implementando il metodo run()

2. In esecuzione passare la classe Runnable ad un oggetto Thread ed eseguire il metodo start():

public class Esempio implements Runnable

Esempio e=new Esempio();Thread T=new Thread(e);T.start();

Page 20: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

Sincronizzazione di Thread

Quando più thread accedono a funzioni o variabili condivise sussiste un problema di programmazione concorrente: synchronized

Un metodo o una variabile vengono dichiarate synchronized: In tal modo si mette un semaforo per accedere a querl metodo o a quella

funzione

synchronized public void inserisci(String documento) {…inserimento del dato nella variabile condivisa…

}

Page 21: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

Java Generics (o template)

Nella nuova versione del Java sono stati aggiunti i generics

Se abbiamo bisogno di un insieme di Giocatori utilizzando la classe Vector del JDK, il Vector tratta i suoi elementi come Object

Questo vuol dire che quando accediamo ad un elemento, esso è visto come un Object (la superclasse) ed è necessario un DownCasting per riottenere un oggetto Giocatroe e poter utilizzare tutte le variabili e le funzioni di tale classe.

Vector V=new Vecotr();V.add(new Giocatore(“Leonardo”,”Rigutini”);Giocatore G=(Giocatore)V.get(1);

Page 22: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

Java Generics (o template) Il Cast (Giocatore)V.get(0) è molto noioso. Normalmente il

programmatore sa che tipi di oggetti sono contenuti nel vettore.

L'idea dei Generics è che il programmatore possa forzare un vettore a contenere oggetti di tipo Giocatore evitando così il cast.

Le classi nel package java.util sono quasi tutte dei template: Vector, List, HashMap, Map, Tree, ecc...

Vector<Giocatore> V=new Vector<Giocatore>();V.add(new Giocatore(“Leonardo”,”Rigutini”);Giocatore G=V.get(1);

Page 23: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

Il package java.util

Questo package fornisce classi di utilità generale

Le classi più importanti sono quelle che implementano le strutture dati dinamiche, timers e StringTokenizer: Le prime forniscono modi per memorizzare vettori, tabelle hash, liste,

stack di dimensione variabili (dinamici) Le seconde forniscono classi per gestire il tempo nel codice L’ultima invece fornisce una classe lettore di stringhe e permette di

tagliare una stringa nei punti desiderati e quindi estrarre da un flusso continuo di parole dei tokens

Page 24: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

Il package java.util

Class Summary

Collections This class consists exclusively of static methods that operate on or return collections.

Currency Represents a currency.

Date The class Date represents a specific instant in time, with millisecond precision.

HashMap Hash table based implementation of the Map interface.

HashSet This class implements the Set interface, backed by a hash table (actually a HashMap instance).

Hashtable This class implements a hashtable, which maps keys to values.

Random An instance of this class is used to generate a stream of pseudorandom numbers.

Page 25: JDK Dott. Ing. Leonardo Rigutini Dipartimento Ingegneria dellInformazione Università di Siena Via Roma 56 – 53100 – SIENA Uff. 0577233606 rigutini@dii.unisi.it.

Il package java.util

Class Summary

Stack The Stack class represents a last-in-first-out (LIFO) stack of objects.

StringTokenizer The string tokenizer class allows an application to break a string into tokens.

Timer A facility for threads to schedule tasks for future execution in a background thread.

TreeMap Red-Black tree based implementation of the SortedMap interface.

TreeSet This class implements the Set interface, backed by a TreeMap instance.

Vector The Vector class implements a growable array of objects.