Programmation 2. Introduction à la programmation Java



Similar documents
Fundamentals of Java Programming

Java Interview Questions and Answers

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

AP Computer Science Java Subset

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

Java Programming. Binnur Kurt Istanbul Technical University Computer Engineering Department. Java Programming. Version 0.0.

Chapter 1 Fundamentals of Java Programming

An Overview of Java. overview-1

Java Programming Language

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Java Application Developer Certificate Program Competencies

Crash Course in Java

Java Programming Fundamentals

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

java Features Version April 19, 2013 by Thorsten Kracht

Habanero Extreme Scale Software Research Project

CS 111 Classes I 1. Software Organization View to this point:

CS506 Web Design and Development Solved Online Quiz No. 01

Java (12 Weeks) Introduction to Java Programming Language

Mobile Application Languages XML, Java, J2ME and JavaCard Lesson 04 Java

Web Development in Java

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

INTRODUCTION TO JAVA PROGRAMMING LANGUAGE

Java CPD (I) Frans Coenen Department of Computer Science

Java SE 7 Programming

Habanero Extreme Scale Software Research Project

Syllabus for CS 134 Java Programming

TYLER JUNIOR COLLEGE School of Continuing Studies 1530 SSW Loop 323 Tyler, TX

Android Application Development Course Program

CS 209 Programming in Java #1

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE. CISY 105 Foundations of Computer Science

Java SE 8 Programming

Java EE Web Development Course Program

DIPLOMADO DE JAVA - OCA

Objectif. Participant. Prérequis. Remarque. Programme. C# 3.0 Programming in the.net Framework. 1. Introduction to the.

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

2 Introduction to Java. Introduction to Programming 1 1

JAVA IN A NUTSHELL O'REILLY. David Flanagan. Fifth Edition. Beijing Cambridge Farnham Köln Sebastopol Tokyo

Chapter 13 - Inheritance

Java SE 7 Programming

Java SE 7 Programming

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Lecture 5: Java Fundamentals III

Chapter 1 Java Program Design and Development

Computing Concepts with Java Essentials

Java and Java Virtual Machine Security

Quick Introduction to Java

CSC 551: Web Programming. Fall 2001

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

The Java Virtual Machine and Mobile Devices. John Buford, Ph.D. Oct 2003 Presented to Gordon College CS 311

Online Recruitment System 1. INTRODUCTION

CSC 551: Web Programming. Spring 2004

Glossary of Object Oriented Terms

PLV Goldstein 315, Tuesdays and Thursdays, 6:00PM-7:50PM. Tuesdays and Thursdays, 4:00PM-5:30PM and 7:50PM 9:30PM at PLV G320

History OOP languages Year Language 1967 Simula Smalltalk

Programming Languages

Java from a C perspective. Plan

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

No no-argument constructor. No default constructor found

JAVA INTERVIEW QUESTIONS

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Java applets. SwIG Jing He

A Comparison of the Object-Oriented Features of Ada 95 and Java

Developing Embedded Software in Java Part 1: Technology and Architecture

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Characteristics of Java (Optional) Y. Daniel Liang Supplement for Introduction to Java Programming

02 B The Java Virtual Machine

Contents. Java - An Introduction. Java Milestones. Java and its Evolution

Applets, RMI, JDBC Exam Review

CSE 452: Programming Languages. Acknowledgements. Contents. Java and its Evolution

1. Overview of the Java Language

The C Programming Language course syllabus associate level

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Java the UML Way: Integrating Object-Oriented Design and Programming

What Perl Programmers Should Know About Java

Lecture 1 Introduction to Android

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Tutorial on Writing Modular Programs in Scala

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Génie Logiciel et Gestion de Projets. Object-Oriented Programming An introduction to Java

Application-only Call Graph Construction

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Course Number: IAC-SOFT-WDAD Web Design and Application Development

El Dorado Union High School District Educational Services

Basic Programming and PC Skills: Basic Programming and PC Skills:

RMI Client Application Programming Interface

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

Konzepte objektorientierter Programmierung

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

To Java SE 8, and Beyond (Plan B)

Transcription:

Programmation 2 Introduction à 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 2014: Java 8 2004: Java 5 - Collections, Enumerate, Concurrent James Gosling - designer of Java 7

Easy to use Why Java? 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-threading 8

Java vs. C based OOP C++ pointers machine dependent no memory management support C# different support for generics no checked exceptions no anonymous inner classes 9

Compiling and interpreting Program source code compiled into bytecode Bytecode is executed in an interpreter environment (Virtual Machine) Java VM for Windows Java program.java Compiler Java bytecode program.class Java VM for Linux Java VM for Mac OS 10

Hello World Compile: javac TestGreeting.java Run: java TestGreeting Result: Hello, world 11

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 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 Heap memory a Baby object name ismale weight 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 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 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, typically for cleanup purposes (closing files, freeing resources) 24

Exception handling 25 Credits: Eric Anquetil

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 constructor 31

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.classcastexception 35

Method polymorphism Animal 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 binding 36

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