Java 101 - Magistère BFA - Lesson 1airiau/Teaching/BFA/lesson1.pdf · Lesson 1– (Stéphane...

Post on 04-Jun-2020

6 views 0 download

Transcript of Java 101 - Magistère BFA - Lesson 1airiau/Teaching/BFA/lesson1.pdf · Lesson 1– (Stéphane...

Java 101 - Magistère BFALesson 1

Stéphane Airiau

Université Paris-Dauphine

Lesson 1– (Stéphane Airiau) Java 1

Evaluationsmall project mainly to make you implement a small application

Slides (in English) will be posted at this webpage.

There are also lecture notes, used in my course for L3 (in French, coveringmore material).

http://www.lamsade.dauphine.fr/~airiau/Teaching/L3-Java/2018.pdf

Lesson 1– (Stéphane Airiau) Java 2

Object Oriented Programming in Java

Lesson 1– (Stéphane Airiau) Java 3

Objects and Classes

An object can be defined by its states and its behaviours

A car seen as an objectStates Behavioursbrand acceleratemodel gear uppower gear downfuel level turn wheeloil level opening doortires pressure closing doorrpm break

A class can be seen as a blue print used for creating objectsstates are represented by variablesbehaviours are represented by methods.

An object is a class instance.

The state of an object can only be changed by the behaviour of the objectë using the methods of the object.

Lesson 1– (Stéphane Airiau) Java 4

Object

An object is an instance of a class.

The running example for the course will be a class of characters of comicbooks such as Astérix.

We will create a class Character. When we will create a particular cha-racter, say Astérix, we will instantiate the class Character to create theinstance / the object Astérix.

By convention, the name of a class always start by an upper case letter.The instances/objects and everything else will start by a lower case letter.

We will write a class MyClass in a file MyClass.java. We will write thecode of the class starting with the keyword class

class Character {. . .

}

to be saved in a file Character.java

Lesson 1– (Stéphane Airiau) Java 5

Java comes with many classes!

Java comes with a large class library. The library is organised in differentpackages.

http://docs.oracle.com/javase/8/docs/api/overview-summary.html

For instance, the package java.lang contains all the basic classes ofJava. The class to manipulate strings of characters is located in that pa-ckage and is called String.

Lesson 1– (Stéphane Airiau) Java 6

Instance variables

instance variables :these variables define the characteristics of the objects.• initialisation is optional.access : <name object>.<instance variable name>

Character asterix;. . .asterix.name;

class variables : these variables are common to all the instances of theclass,• declaration with the keyword static• initialisation is compulsoryaccess : <class name>.<class variable name>

example : the class Float encapsulates a floating point number float.class variables : MAX_VALUE, MAX_EXPONENT, NaN, etc.

Lesson 1– (Stéphane Airiau) Java 7

Class method and Instance methods

Instance methods : these methods allows to access or modify the stateof an instance/objectClass methods : these methods do not modify the state of an object.Usually, there are utility methods to work with object of the class.

For now, class methods may not appear so useful, just remember theyexist.

Example : Float class

instance method String toString()ë returns a representation of the current object as a character string

class method static String toString(Float f)

ë returns a representation of an object passed in parameter

1 Float f;2 . . .3 System.out.println(f.toString());4 System.out.println(Float.toString(3.1419));

Lesson 1– (Stéphane Airiau) Java 8

Encapsulation

The behaviour or the state of an object can be known by every other objectë public

Any class canexecute a public methodaccess or modify a public variable

hidden to other classes ë privateone can call a private method, access or modify a private variable only ifit is inside the class

ë goal is to hide what is "under the hood"(one will be able to change code without affecting any other class).

ë protection

Lesson 1– (Stéphane Airiau) Java 9

Creating an object : call a constructor

A class is just a blue print to create instances.To create an object, we use a special method called a constructor.In the class, we need to implement a constructorsignature of the constructor

the name of the method is the name of the classthere is not return type nor void

The default constructor is the constructor with no argument :

1 public class <class name> {2 // declare variables3 // (class or instance)... . . .

5 // default constructor6 public <class name>(){7 // body8 }9 }

Lesson 1– (Stéphane Airiau) Java 10

Example

In Java, we can use the same name for a method but with different ordersand/or numbers of parameters. We can have many constructors to makeit easier to build an object.

1 public class Character {2 public String name;34 // default constructor5 public Character(){6 name = ”unknown";7 }89 public Character(String my_name){

10 name = my_name;11 }12 }

In the example, we have two constructors.

Lesson 1– (Stéphane Airiau) Java 11

Declaring and Creating an Object

DeclarationIn Java, we can declare and object telling Java the nature of anobject : every time Java will see the variable name, Java will knowits declared nature.In Java, any variable must be declared !

ë <class name> <object name>

Creationwe use the keyword new and we call the constructor :new <class name>(<arguments list>);

we can declare and affect the object in the same instruction

1 Character asterix = new Character("Astérix");2 Character obelix = new Character("Obelix"),3 idefix = new Character(”Idéfix”),4 romain = new Character();

Lesson 1– (Stéphane Airiau) Java 12

Ready to build a class

we know how to create a classwe know how to create objectsto build a class, we need to define

instance variables : they can be other objects (so we know how todeclare them and create them),or "primitive types" such as int, double (we’ll talk about this soon).instance methods : these methods access or modify the state of theobject. (we’ll talk about creating method soon).class variables and methods if needed.and we need to define at least one constructor (we already know howto do that !)

Write your first class :1- Code a class that represent students. Each students has a name and

3 grades : one for each subject : bank, finance, insurance.2- What instance methods would be usefull ?

Lesson 1– (Stéphane Airiau) Java 13

Some basic knowledge

ë The basicsAll about writing basic code without using the concept of object.

Variables, operators, typesTests, loopsArraysmethods

Lesson 1– (Stéphane Airiau) Java 14

Instructions and comments

1 // This is a comment

1 /* this is a2 comment3 using different lines */

An instruction must satisfy the grammar of the langage Java.

Most of the instructions finish with a ;

Lesson 1– (Stéphane Airiau) Java 15

Elementary Types

These types are not objects, they are primitive/elementary types that canbe used to build/work with objects.

The "number of bits" denotes the size (in bits) needed to encode one ele-ment of each type.

ElementaryTypes

numberof bits value interval

boolean 1 true and falsebyte 8 an integer between -128 and 127short 16 an integer between -215=−32768 et 215 −1=32767int 32 an integer between -231 ≈−2.1 ·109 and 231 −1≈ 2.1 ·109

long 64 an integer between -263 ≈−9.2 ·1018 and 263 −1≈ 9.2 ·1018

char 16 unicode characters, there are 65536 codesfloat 32 a floating point number following theIEEE normdouble 64 a floating point number following the IEEE norm

similar types are used for instance in VBA.

Lesson 1– (Stéphane Airiau) Java 16

Variables : declaration and initialisation

simple declaration :<type> <nom>;

declaration with affectation :<type> <name> = <value in the type> | <variable> |<expression> ;

multiple declarations :<type> <name1>, <name2>, . . ., <namek>;

multiple declaration with partial affectation :<type> <name1>, <name2>= <value in the type>, . . .,<namek>;

Lesson 1– (Stéphane Airiau) Java 17

Cast : when types do not match

Here is the situation :1 <type1> <nom1> = <valeur1>;2 <type2> <nom2> = <nom1>;3 <type2> <nom2> = <valeur1>;

Implicit cast : when type2 is « stronger » than type1

1 int i = 10;2 double x = 10;3 double y = i;

an int « fits » inside a double.Explicit cast when <type1> is « strictly stronger » than <type2> :we need to tell the compiler to do something

1 double x= 3.1416;2 int i = (int)x;

We need to tell Java to « cut » the double to make it fit inside anint.

Lesson 1– (Stéphane Airiau) Java 18

Unary operator

Operator degree of priority action examples+ 1 positive sign +a; +7- 1 negative sign -a; -(a-b); -7! 1 logical negation !(a<b);++ affectation and increment by one n++;++n;−− increment by one then affectation n++; −−i;

Lesson 1– (Stéphane Airiau) Java 19

Binary operator

Operator degree of priority action examples* 2 multiplication a * i/ 2 division n/10% 3 remainder of integer division k%n+ 3 addition 1+2- 3 substraction x-5< 5 strictly smaller than i<n<= 5 smaller or equal to i <= n> 5 strictly greater i < n>= 5 greater or equal i >= n== 6 equality i==j!= 6 different i!=j& 7 conjunction (logical and) (i<j) & (i<n)| 9 disjunction (logical or) (i<j) | (i<n)&& 10 optimised conjunction (i<j) && (i<n)|| 11 optimised disjunction (i<j) || (i<n)= affectation x = 10; x=n;

+=, -= affectation and increment i += 2; j-=4

Warning : do not use = for equality test!

Lesson 1– (Stéphane Airiau) Java 20

Expression type

Is the following code correct ?

1 int i = 5,j;2 double x = 5.0;3 j=i/2;4 j=x/2;

1 double x=2.75;2 int y = (int) x * 2;3 int z = (int) (x *2);

What are the values of y and z?

Lesson 1– (Stéphane Airiau) Java 21

Expression type

Is the following code correct ?

1 int i = 5,j;2 double x = 5.0;3 j=i/2;4 j=x/2;

1 double x=2.75;2 int y = (int) x * 2;3 int z = (int) (x *2);

What are the values of y and z?

Lesson 1– (Stéphane Airiau) Java 22

Equality between object

1 Character asterix = new Character("Astérix");2 Character asterixBis = asterix;3 Character asterixTer = new Character("Astérix");4 if (asterix == asterixBis)5 System.out.println("Red");6 else7 System.out.println("Green");8 if (asterix == asterixTer)9 System.out.println("Blue");

10 else11 System.out.println("Yellow");

What is written in the output?

a variable is a reference to an object in memoryand not the object !== is the equality between references :two references are equal if they refer to the same object in memoryFor testing the equality between properties of an objectwe use a special method boolean equals(Object o).

Lesson 1– (Stéphane Airiau) Java 23

Equality between object

1 Character asterix = new Character("Astérix");2 Character asterixBis = asterix;3 Character asterixTer = new Character("Astérix");4 if (asterix == asterixBis)5 System.out.println("Red");6 else7 System.out.println("Green");8 if (asterix == asterixTer)9 System.out.println("Blue");

10 else11 System.out.println("Yellow");

What is written in the output?

a variable is a reference to an object in memoryand not the object !== is the equality between references :two references are equal if they refer to the same object in memoryFor testing the equality between properties of an objectwe use a special method boolean equals(Object o).

Lesson 1– (Stéphane Airiau) Java 24

Let’s repeat again

Declaration of an object

Character asterix;

one tells that an object of a given type is known with a given name :The object named as asterix is of type CharacterCreation of an object

asterix = new Character("Astérix";)

The variable asterix refers to an object in memory that is aCharacter

asterix = new Character("Idéfix");

The variable asterix now refers to a different object that is also aCharacter.What happens to the previous object ?

Lesson 1– (Stéphane Airiau) Java 25

Arrays

How to declare an array :

1 <type> [] line;2 <type> [][] rectangle;3 <type> [][][] cube;

How to create an array : you must tell the array size !

1 <type> [] line = new <type>[<taille1>];2 <type> [][] rectangle = new <type>[<taille2>][<taille3>];

How to get the size of the array : cube.length

Warning : in computer Science,the first entry of an array is indexed by 0.

ë the last entry of an array is then length-1.How to use the array : use brackets [] :

rectangle[3][4] + cube[1][2][5];

Lesson 1– (Stéphane Airiau) Java 26

Examples

It is possible to initialise an array using a « list » notation :

primes : 2 3 5 7 11 13 17 19 triangle :

1 1 1 10 1 1 10 0 1 10 0 0 1

1 int[] premiers = {2, 3, 5, 7, 11, 13, 17, 19 };2 int[][] triangle = {{1,1,1,1}, { 0,1,1,1},3 { 0, 0, 1, 1}, {0, 0, 0, 1} } ;

A 2-dimensional array is a 1-dimensional array of 1-dimensional array...so

1 int[][][] cube = new int[3][4][5];2 int[][] rectangle = cube[2];3 int n1 = cube.length;4 int n2 = cube[0].length;5 int n3 = cube[0][0].length;

Lesson 1– (Stéphane Airiau) Java 27

Instruction Blocks

A block gathers together instructions.The variables that are declared inside a block are only known inside ablock.i.e. outside the block, the variable does not exist !

1 int a,b=10;2 {3 int d=2*b;4 {5 int e=b+d;5 a=e*d;6 {5 int g= b+ d*e;6 }6 }7 }

a and b are known everywhere.d only exists in the red part.e only exists in the blue part.g only exists in the green part

Lesson 1– (Stéphane Airiau) Java 28

Conditionnals : if . . . then . . . else

1 if ( <boolean expression> )2 <block to execute3 when the condition is satisfied>4 else5 <block to execute6 if the condition is not satisfied>

The else block is optional.

1 int gains,payment,withdraw,invest;2 // some code that modify the gains3 . . .4 if (gains<0)5 payment = gains;6 else if (gains > 10) {7 withdraw = 10;8 invest = gains-10;9 }

10 else11 withdraw = gains;

Lesson 1– (Stéphane Airiau) Java 29

Multiple choices

1 int choice;2 . . .3 // something is done with choice4 . . .5 switch(choice) {6 case 1:7 //instruction block for case 18 . . .9 break;

10 case 2:11 //instruction block for case 212 . . .13 break;14 default15 // default instruction block16 . . .17 }

Inside a switch we can use a variable with types int, char,and String

Lesson 1– (Stéphane Airiau) Java 30

Loop : for loop

1 for (<initialisation>2 <continuing condition> ;3 <update>)4 <instruction block>

What happens in that case? Is this valid?

1 for ( ; ; ){2 // instructions3 }

a classical example :

0 int n=10;1 for (int i=0; i< n; i++ ){2 // instructions3 }

Lesson 1– (Stéphane Airiau) Java 31

Another example

0 int n=10;1 for (int i=0, j=n; i< j; i++; j−− ){2 // instructions3 }

Lesson 1– (Stéphane Airiau) Java 32

Loop : while loop

1 while(<condition>)2 <instruction block>

The instruction block is execute as long as the condition is met.

Example for checking convergence of a series u : n→ rn :

1 double epsilon = 0.0000001;2 double r = 0.75, u=1;3 while( u-u*r <= -epsilon && u - u* r >= epsilon)4 u = u * r ;

Lesson 1– (Stéphane Airiau) Java 33

Loop do . . . while

1 do2 <Instruction block>3 while(<condition>);

Warning ! Do not forget the semi column ; right after the condition !

1 double epsilon = 0.0000001;2 double r = 0.75, u=1;3 do4 u = u * r ;5 while ( -epsilon >= u-u*r || u - u* r >= epsilon);

choosing a while loop or a do while loop is a matter of elegance, oneusually comes easier than the other.

Lesson 1– (Stéphane Airiau) Java 34

Choosing between a while loop or a for loop

if we know exactly how many times we iterate : use a for loopotherwise, use a while loop.what is more expected?

ex :search an element in an array?search for the largest element in an array?

Lesson 1– (Stéphane Airiau) Java 35

Methods

It is the term used for function in a Object Oriented Programming Lan-guage.

Goal : Factorise/gather together a sequence of instruction that could beused multiple times.The code becomes

more readable (if a pertinent name is used !)shorterimportant If one wants/needs to modify the code, one just need toupdate the code in one location !

Lesson 1– (Stéphane Airiau) Java 36

Method

1 <static or ∅> <public or private> <type of what is returned> <name>2 ( <parameter list>) {3 body of the method4 }

Choose an illustrative name!the order of the parameters is significant :Java does not match the parameters using names, it uses the order !

If the method does not return something (it is a procedure), we usethe return type void.when the method returns something, the instruction return<result> is used to terminate the method and to output result.

Lesson 1– (Stéphane Airiau) Java 37

Example

1 public static int max( int[] tab) {2 int m= tab[0];3 for (int i=1;i<tab.length; i++){4 if (tab[i] > m)5 m = tab[i];6 }7 return m;8 }

Calling the method :1 int tab = {7, 12, 15, 9, 11, 17, 13};2 int m = max(tab);

Lesson 1– (Stéphane Airiau) Java 38

Overloading

We call signature the name of the method with its list of argument.

The signature of a method must be unique to avoid ambiguities.

ë We can have two methods with the same name but different lists ofparameters !

1 public static double max( double[] tab) {2 double m= tab[0];3 for (int i=1;i<tab.length; i++){4 if (tab[i] > m)5 m = tab[i];6 }7 return m;8 }

Lesson 1– (Stéphane Airiau) Java 39

Passing arguments of primitive types

1 public int f(int n){2 n = 3 * n * n -2 *n + 13 if (n > 0)4 return n;5 else6 return 0;7 }

1 int i=13;2 int j= f(i);

What is the value of i?

We pass the argument of primitive type by value.

Lesson 1– (Stéphane Airiau) Java 40

Compilation, execution, virtual machine

Java is not only a langage and a library of classesJava has tools for generating and executing code.

Source code .java

Compilation javac

Bytecode .classso

usw

indo

ws sous

linux

sousm

acO

S

Exécution javavirtual

machine

windows machine linux machine apple machine android smartphone

Lesson 1– (Stéphane Airiau) Java 41

Compilation

A class <MyClass> is saved in a file <MyClass>.java : the name of theclass must match the name of the file with the extension .java.

If the class is named Character, it must be stored in a file calledCharacter.java.

To compile, we use a program called javac that translate your code intomachine readable code.

The compiler translates your code into a langage that the virtual machineunderstands.

For Java it produces bytecode.

The result of the compilation is a file name <MyClass>.class

Lesson 1– (Stéphane Airiau) Java 42

Compilation

Roughly, there are two stages in the compilation process :

syntaxic analysis : we check the grammar of the codesemantic analysis : translation of the code in bytecodeand we check if everything is well known (other classes)

Lesson 1– (Stéphane Airiau) Java 43

Execution

What is executed is a special method called main.Each class can have one main.If a method main is implemented in a class MyClass, we lauch the virtualJavamachine, which runs the main :java MaClass(on linux or mac os, you can run this command)

The main method has a well specified signature

1 public static void main(String[] args)

public : it must be called from outside the classstatic : we have not yet been able to create an object !void : lthe method does not return anything (to whom should itreturn something?)String[] args : when we start the execution, we can add sometext, which will be accessible in this array of string. This is usefulwhen we want to launch an application with some options.

Lesson 1– (Stéphane Airiau) Java 44

Your turn : back to the student class!

String toString() that returns a representation of the studenta method to add each gradea method that compute the average of the grades. If one note ismissing, write a message. As you must return a value, choose anappropriate one.a method that tells whether the student passes.

Use a main method to test your code.

PS : to write a message on the console, use the following instruction :System.out.println(<a string>)

PPS : for Strings, the binary operator + appends the two strings

Lesson 1– (Stéphane Airiau) Java 45