Comments: / This Comment Is So Long That It Needs Two Lines
Comments: / This Comment Is So Long That It Needs Two Lines
Comments
C-style comments (multi-lines)
/* this comment is so long that it needs two lines */
Control statements
Same as C
if-else, switch, while, do-while, for, break, continue
Politecnico di Torino
Boolean
Java has an explicit type (boolean) to represent logic values (true, false) Conditional constructs evaluate boolean conditions
Note well - Its not possible to evaluate this condition int x = 7; if(x){} //NO Use relational operators if (x != 0)
Passing parameters
Parameters are always passed by value ...they can be primitive types or object references Note well: only the object reference is copied not the value of the object
Politecnico di Torino
Politecnico di Torino
26/03/2009
Constants
The final modifier
final float PI = 3.14; PI = 16.0; // ERROR, no changes final int SIZE; // ERROR, init missing
Elements in a OO program
Structural elements (types) (compile time) Class Primitive type Dynamic elements (data) (run time) Reference Variable
Politecnico di Torino
Politecnico di Torino
Primitive type
Defined in the language:
int, double, boolean
Instance declaration:
Declares instance name 0 Declares the type Allocates memory space for the reference
int i;
Politecnico di Torino
Politecnico di Torino
10
Class
Defined by developer (eg, Exam) or by the Java environment (eg, String) the following declaration Exam e;
e null
allocates memory space for the reference (pointer) and sometimes it initializes it with null by default Allocation and initialization of the object value are made later by its constructor e = new Exam();
Politecnico di Torino
Primitive types
e 0Xffe1
Object Exam
11
26/03/2009
Primitive types
Have a unique dimension and encoding
Representation is platform-independent
Constants
Constants of type int, float, char, strings follow C syntax
123 256789L 0.12375e+3 a % 0xff34 123.75 prova\n \n prova
type
boolean char byte short int long float double void
Politecnico di Torino
Dimension
1 16 8 16 32 64 32 64 bit bits bits bits bits bits bits bits
Unicode Signed integer 2C Signed integer 2C Signed integer 2C Signed integer 2C IEEE 754 sp IEEE 754 dp
Encoding
13
Politecnico di Torino
14
Logical operators
Logical operators follows C syntax:
&& || ! ^
15
Politecnico di Torino
16
Class
Object descriptor It consists of attributes and methods
Classes
Politecnico di Torino
18
26/03/2009
Class - definition
class Car { Name String color; Car String brand; Attributes boolean turnedOn; color void turnOn() { brand turnedOn = true; turnedOn } turnOn Methods void paint (String newCol) { paint color = newCol; printState } void printState () { System.out.println(Car + brand + + color); System.out.println(the engine is +(turnedOn:on:off)); } }
Politecnico di Torino
Methods
Methods are the messages that an object can accept
turnOn paint printState
19
Politecnico di Torino
20
Overloading
In a Class there may be different methods with class Car { the same name String color; But they have a void paint(){ different signature color = white; A signature is made } by: void paint(int i){} Method name void paint(String Ordered list of newCol){ parameters types color = newCol; the method whose } parameters types list } matches, is then executed
Politecnico di Torino
Overloading
public class Foo{ public void doIt(int x, long c){ System.out.println("a"); } public void doIt(long x, int c){ System.out.println("b"); } public static void main(String args[]){ Foo f = new Foo(); f.doIt( 5 ,(long)7 ); // a f.doIt( (long)5 , 7 ); // b } }
21
Politecnico di Torino
22
Objects
An object is identified by:
Its class, which defines its structure (attributes and methods) Its state (attributes values) An internal unique identifier
Objects
class Car { String color; void paint(){ color = white; } void paint(String newCol) { color = newCol; } } Car a1, a2; a1 = new Car(); a1.paint(green); a2 = new Car();
23
Politecnico di Torino
Politecnico di Torino
24
26/03/2009
Objects Creation
Creation of an object is made with the keyword new It returns a reference to the piece of memory containing the created object
Motorcycle m = new Motorcycle();
25
Politecnico di Torino
26
Heap
It is a part of the memory used by an executing program to store data dynamically created at runtime C: malloc, calloc and free
Instances of types in static memory or in heap
Java: new
Instances (Objects) are always in the heap
27
Politecnico di Torino
28
Constructor
Constructor method contains operations (initialization of attributes etc.) we want to execute on each object as soon as it is created Attributes are always initialized
Attributes are initialized with default values
If a Constructor is not declared, a default one (with no parameters) is defined Overloading of constructors is often used
Politecnico di Torino
30
26/03/2009
Destruction of objects
It is no longer a programmer concern See section on Memory management Before the object is really destroyed if exists method finalize is invoked: public void finalize()
Methods invocation
A method is invoked using dotted notation
objectReference.Method(parameters)
Example:
Car a = new Car(); a.turnOn(); a.paint(Blue);
Politecnico di Torino
31
Politecnico di Torino
32
Caveat
If a method is invoked within another method of the same object
DO NOT need to use dotted notation
class Book { int pages; void readPage(int n) { } void readAll() { for (int i=0; i<pages; i++) readPage(i); } }
Caveat (contd)
In such cases this is implied this is a reference to the current object
class Book { int pages; void readPage(int n){} void readAll() { for() readPage(i); void readAll() { } for() } this.readPage(i); }
33 34
Politecnico di Torino
Politecnico di Torino
Access to attributes
Dotted notation
objectReference.attribute Reference is used like a normal variable
Car a = new Car(); a.color = Blue; //whats wrong here? boolean x = a.turnedOn;
Access to attributes
Methods accessing attributes of the same object do not need using object reference
class Car { String color; void paint(){ color = green; // color refers to current obj } }
Politecnico di Torino
35
Politecnico di Torino
36
26/03/2009
this
It can be useful in methods to distinguish object attributes from local variables
this represents a reference to the current object
class Car{ String color; ... void paint (String color) { this.color = color; } }
Politecnico di Torino
37
Politecnico di Torino
38
Operations on references
Only the relational operators == and != are defined
Note well: the equality condition is evaluated on the values of the references and NOT on the values of the objects ! The relational operators tell you whether the references points to the same object in memory
Strings
Politecnico di Torino
39
String
No primitive type to represent string String literal is a quoted text C
char s[] = literal Equivalence between string and char arrays
Operator +
It is used to concatenate 2 strings
This string + is made by two strings
Java
char[] != String String class in java.lang library
Politecnico di Torino
41
Politecnico di Torino
43
26/03/2009
String
int length()
returns string length
String
String valueOf(int)
Converts int in a String available for all primitive types
boolean equals(String s)
compares the values of 2 strings
String s1, s2; s1 = new String(First string); s2 = new String(First string); System.out.println(s1); System.out.println(Length of s1 = + s1.length()); if (s1.equals(s2)) // true if (s1 == s2) // false
Politecnico di Torino
String toUpperCase() String toLowerCase() String concat(String str) - like + int compareTo(String str)
Compare w.r.t alphabetical order <0 if this < str ==0 if this == str >0 if this > str
44
Politecnico di Torino
45
String
String subString(int startIndex)
String s = Human; s.subString(2) returns man
StringBuffer
insert append delete reverse
46
Politecnico di Torino
47
Character
Utility methods on the kind of char
isLetter(), isDigit(), isSpaceChar()
Politecnico di Torino
48
26/03/2009
Example
Laundry machine, design1
commands:
time, temperature, amount of soap
Example (contd)
Washing machine, design3
command:
Wash!
insert clothes, and the washing machine automatically select the correct program
Hence, there are different solutions with different level of granularity / abstraction
50
Politecnico di Torino
Politecnico di Torino
51
Motivation
Modularity = cut-down inter-components interaction Info hiding = identifying and delegating responsibilities to components
components = Classes interaction = read/write attributes interaction = calling a method
public
attribute / method visible everywhere
protected
attribute / method visible by instance of the same class and sub-classes
Heuristics
attributes invisible outside the Class Visible methods are the ones that can be invoked from outside the Class
Politecnico di Torino
52
Politecnico di Torino
53
Info hiding
class Car { public String color; } Car a = new Car(); a.color = white; // ok class Car { private String color; public void paint(String color) {this.color = color;} } Car a = new Car(); better a.color = white; // error a.paint(green); // ok
Politecnico di Torino
Info hiding
class Car{ private String color; public void paint(); no }
yes
55
26/03/2009
Access
Method in the same class Private (attribute/ method) Public yes Method of another class no
yes
yes
Politecnico di Torino
57
}
Politecnico di Torino
59
61
10
26/03/2009
Array
Politecnico di Torino
Array
An array is an ordered sequence of variables of the same type which are accessed through an index Can contain both primitive types or object references (but no object values) Array dimension can be defined at run-time, during object creation (cannot change afterwards)
Politecnico di Torino
Array declaration
An array reference can be declared with one of these equivalent syntaxes
int[] a; int a[];
In Java an array is an Object and it is stored in the heap Array declaration allocates memory space for a reference, whose default value is null
a null
65 64
Politecnico di Torino
Array creation
Using the new operator
int[] a; a = new int[10]; String[] s = new String[5];
a = new int[6];
heap
0 0 0 0 0 0
primes
heap
2 3 5 7 11 13 67
Politecnico di Torino
11
26/03/2009
Operations on arrays
Elements are selected with brackets [ ] (C-like)
But Java makes bounds checking
heap
null null null null null null
heap
null null null null null
abcd
heap
John Susan
68
Politecnico di Torino
69
Operations on arrays
An array reference is not a pointer to the first element of the array It is a pointer to the array object
For each
New loop construct:
for( Type var : set_expression ) Notation very compact set_expression can be
either an array a class implementing Iterable
The compiler can generate automatically loop with correct indexes Thus less error prone
70
Politecnico di Torino
Politecnico di Torino
71
Homework
Create an object representing an ordered list of integer numbers (at most 100) print()
prints current list
72
Politecnico di Torino
73
12
26/03/2009
Multidimensional array
Implemented as array of arrays
Person[][] table = new Person[2][3]; table[0][2] = new Person(Mary);
table
heap
null null null null null
table[0][2]
Mary
table[0]
Politecnico di Torino
74
Politecnico di Torino
75
Tartaglias triangle
Write an application printing out the following Tartaglias triangle 1 1 1 1 2 1 4=3+1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1
76
Politecnico di Torino
heap
0 0
77
Motivation
Class is a better element of modularization than a procedure But it is still little For the sake of organization, Java provides the package feature
Package
Politecnico di Torino
79
13
26/03/2009
Package
A package is a logic set of class definitions These classes are made of several files, all stored in the same directory Each package defines a new scope (i.e., it puts bounds to visibility of names) Its then possible to use same class names in different package without name-conflicts
Package name
A package is identified by a name with a hierarchic structure (fully qualified name)
E.g. java.lang (String, System, )
Politecnico di Torino
80
Politecnico di Torino
81
Example
java.awt
Window Button Menu
Usage:
Import statement at the beginning of class file (where needed) Import
import packageName.className; import java.awt.*; Import all
classes but not the sub packages single class (class name is in scope)
java.awt.event (sub-package)
MouseEvent KeyEvent
Politecnico di Torino
82
Politecnico di Torino
83
If two packages define a class with the same name, they cannot be both imported If you need both classes you have to use one of them with its fully-qualified name:
import java.sql.Date; Date d1; // java.sql.Date java.util.Date d2 = new java.util.Date();
Politecnico di Torino
84
Politecnico di Torino
85
14
26/03/2009
Package visibility
Package P class A { public int a1; private int a2; public void f1(){} }
yes no
class B { }
No method/attribute of B is visible outside the package
Politecnico di Torino
86
Politecnico di Torino
87
Multiple packages
Package P class A { public int a1; private int a2; public void f1(){} } class B { public int a3; private int a4; }
Multiple packages
Package P public class A { public int a1; private int a2; public void f1(){} } class B { public int a3; private int a4; }
no
no
yes
no
Politecnico di Torino
88
Politecnico di Torino
89
Access rules
Method in the same class Private attribute/ method Yes Method of other Method of other class in the same class in other package package No Yes Yes No No No
Package attribute / Yes method Public attribute / method on package class Public attribute / method on public class Yes
Yes
Yes
Yes
Politecnico di Torino
90
15
26/03/2009
Class variables
Represent properties which are common to all instances of an object But they exist even when no object has been instantiated They are defined with the static modifier Access: ClassName.attribute
class Car { static int numberOfWheels = 4; } int y = Car.numberOfWheels;
Politecnico di Torino
Static methods
Static methods are not related to any instance They are defined with the static modifier Access: ClassName.method()
class HelloWorld { public static void main (String args[]) { System.out.println(Hello World!); } } double y = Math.cos(x); // static method
92 93
Politecnico di Torino
Enum
Defines an enumerative type
public enum Suits { SPADES, HEARTS, DIAMONDS, CLUBS } Suits card = Suits.HEARTS;
Enum
Enum can be declared outside or inside a class, but NOT within a method Enums are not Strings or ints, but more like a kind of class but constructor cant be invoked directly, conceptually like this:
class Suits { public static final Suits HEARTS= new Suits (HEARTS,0); public static final Suits DIAMONDS= new Suits (DIAMONDS,1); public static final Suits CLUBS= new Suits (CLUBS, 2); public static final Suits SPADES= new Suits (SPADES, 3); public Suits (String enumName, int index) {} }
94 95
Variables of enum types can assume only one of the enumerated values They allow much more strict static checking compared to integer constants (used e.g. in C)
Politecnico di Torino
Politecnico di Torino
97
16
26/03/2009
Wrapper Classes
Defined in java.lang package Primitive type
boolean char byte short int long float double void
Politecnico di Torino
Conversions
Wrapper Class
Boolean Character Byte Short Integer Long Float Double Void
98
Integer
intValue()
new Integer(i)
toString()
iint
String
Integer.parseInt(33) String.valueOf(33) +
Politecnico di Torino
99
Example
Integer obj = new Integer(88); String s = obj.toString(); int i = obj.intValue();
Autoboxing
In Java 5 an automatic conversion between primitive types and wrapper classes (autoboxing) is performed.
Integer i= new Integer(2); int j; j = i + 5; //instead of: j = i.intValue()+5; i = j + 2; //instead of: i = new Integer(j+2);
100
Politecnico di Torino
Politecnico di Torino
101
Variable arguments
It is possible to pass a variable number of arguments to a method using the varargs notation method( Object ... args ) The compiler assembles an Object array that can be used to scan the passed parameters
Politecnico di Torino
102
Politecnico di Torino
103
17
26/03/2009
Memory types
Depending on the kind of elements they include: Static memory
elements living for all the execution of a program (class definitions, static variables)
Memory management
Stack
elements created in a code block (local variables and method parameters)
Politecnico di Torino
105
Types of variables
Instance variables (or fields or attributes)
Stored within objects (in the heap)
code
reference
State
Local Variables
Stored in the Stack
Static Variables
Stored in static memory
Politecnico di Torino
106
Politecnico di Torino
107
Instance Variables
Declared within a Class (attributes)
Class Window { boolean visible;
Window1 visible Window2 visible
Local Variables
Declared within a method or a code block Stored in the stack Created at the beginning of the code block where they are declared Automatically destroyed at the end of the code block
Class Window { void resize () { int i; for (i=0; i<5; i++) { } } // here i is destroyed
heap
There is a different copy in each instance of the Class Create/initialized whenever a new instance of a Class is created
Politecnico di Torino
108
Politecnico di Torino
109
18
26/03/2009
Static Variables
Declared in classes or methods with static modifier
ColorWindow
heap
ColorWindow1 ColorWindow2
color
Politecnico di Torino
110
Politecnico di Torino
111
Object destruction
Its not made explicitely but it is made by the JVM when there are no more references to the object
Programmer must not worry about objects destruction
Garbage collector
Is a component of the JVM that has to clean heap memory from dead objects After a period of time it analyzes references and objects in memory ...and then it deallocates objects with no active references
Politecnico di Torino
112
Politecnico di Torino
113
19