278
Borrador www.profesorjava.com PJ-060. Curso de Programación Java Intermedio. www.profesorjava.com

Curso de Programación Java Intermedio

Embed Size (px)

DESCRIPTION

Curso de Programación Java a nivel intermedio. Creado por ISC Raúl Oramas Bustillos, www.profesorjava.com

Citation preview

Page 1: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

PJ-060.

Curso de Programación

Java Intermedio.

www.profesorjava.com

Page 2: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Esta obra está bajo una licencia Reconocimiento 2.5 México de Creative Commons. Para ver una copia de esta licencia, visite

http://creativecommons.org/licenses/by/2.5/mx/ o envíe una carta a Creative Commons, 171 Second Street, Suite 300, San Francisco,

California 94105, USA.

Page 3: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Acerca de:

En la compilación de esta obra se utilizaron libros conocidos en el ambiente Java, gráficas, esquemas, figuras de sitios de internet, conocimiento adquirido en los cursos oficiales de la tecnología Java. En ningún momento se intenta violar los derechos de autor tomando en cuenta que el conocimiento es universal y por lo tanto se puede desarrollar una idea a partir de otra.

La intención de publicar este material en la red es compartir el esfuerzo realizado y que otras personas puedan usar y tomar como base el material aquí presentado para crear y desarrollar un material mucho más completo que pueda servir para divulgar el conocimiento.

Atte.ISC Raúl Oramas Bustillos.

[email protected]

Page 4: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

CONTENIDO

Modulo 01: La tecnología Java.

Modulo 02: Programación Orientada a Objetos.

Modulo 03: Identificadores, tipos y palabras reservadas.

Modulo 04: Expresiones y control de flujo.

Modulo 05: Arreglos.

Modulo 06: Diseño de clases I.

Modulo 07: Diseño de clases II.

Modulo 08: Excepciones y asertos.

Page 5: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

CONTENIDO

Modulo 09: Colecciones.

Modulo 10: Threads.

Page 6: Curso de Programación Java Intermedio

Module 01• Java Technology

Page 7: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Introduction

• History of Java

• What is Java technology?

• Why is Java technology important?

• What are the Java components technology components?

Page 8: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Objectives

• Describe key features of Java

Page 9: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Introduction

• The Java programming language has a construct similar to that of C++

• The Java programming language has simplified many of the complicated and ambiguous structures present in C++

• Another major advantage that Java brought along with it is the concept of platform independence

Page 10: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

History of Java

• Patrick Naughton, Mike Sheridan and James Gosling of SUN Microsystems started a new project called the Green Project towards the end of 1990

• The team came up with a device called star 7 (*7)

• Star 7 used a processor-independent language called Oak to adapt to a variety of platforms and appliances

• Oak evolved into a language that enabled programmers to write executable code that could be distributed through Internet

• This newly evolved language was called Java

Page 11: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

History of Java

Page 12: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

What is Java technology?

• Java technology is both a high-level, object-oriented programming language and a platform.

• Java technology is based on the concept of a single Java virtual machine (JVM) -- a translator between the language and the underlying software and hardware.

• All implementations of the programming language must emulate the JVM, enabling Java programs to run on any system that has a version of the JVM.

• The Java programming language is unusual because Java programs are both compiled (translated into an intermediate language called Java bytecode) and interpreted (bytecode parsed and run by the JVM).

Page 13: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

What is Java technology?

• Compilation occurs once, and interpretation happens each time the program runs. Compiled bytecode is a form of optimized machine code for the JVM; the interpreter is an implementation of the JVM.

Java bytecode is machine code for the Java Virtual Machine (JVM).

Page 14: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

What is Java technology?

• The Java platform is a software-only platform that runs on top of various hardware-based platforms. It comes in three versions.

• It consists of the JVM and the Java Application Programming Interface (API), a large collection of ready-made software components (classes).

• The Java API is grouped into libraries of related classes and interfaces; the libraries are known as packages

A platform is an environment on whichprograms can be executed

Page 15: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

What is Java technology?

• Along with the Java API, every full implementation of the Java platform includes:

– Development tools for compiling, running, monitoring, debugging, and documenting applications.

– Standard mechanisms for deploying applications to users.

– User interface toolkits that make it possible to create sophisticated graphical user interfaces (GUIs).

– Integration libraries that enable database access and manipulation of remote objects.

Page 16: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Why is Java technology important?

• The main benefit of the Java language is the portability of Java applications across hardware platforms and operating systems -- possible because the JVM installed on each platform understands the same bytecode.

Page 17: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Why is Java technology important?

Three editions of the Java platform

make it easier for software

developers, service providers, and

device manufacturers to target

specific markets:

• Java SE (Java Platform, Standard Edition).

• Java EE (Java Platform, Enterprise Edition).

• Java ME (Java Platform, Micro Edition).

Page 18: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

What are the Java technology components?

• Technologies in Java SE:• Java Foundation Classes (Swing) (JFC)

• JavaHelp

• Java Native Interface (JNI)

• Java Platform Debugger Architecture (JPDA)

• Java 2D API

• Java Web Start

• Certification Path API

• Java Database Connectivity (JDBC)

• Java Advanced Imaging (JAI)

• Java Authentication and Authorization Service (JAAS)

• Java Cryptography Extension (JCE)

• Java Data Objects (JDO)

• Java Management Extensions (JMX)

• Java Media Framework (JMF)

• Java Naming and Directory Interface (JNDI

• Java Secure Socket Extensions (JSSE)

• Java Speech API (JSAPI)

• Java 3D is an API

• Metadata Facility

• Java Content Repository API

• Enumerations

• Generics

• Concurrency Utilities

• Java API for XML Processing (JAXP)

• SOAP with Attachments API for Java

Page 19: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

What are the Java technology components?

• Technologies in J2EE:

• Enterprise JavaBeans (EJB)• Portlet Specification• JavaMail• Java Message Service (JMS)• JavaServer Faces (JSF)• JavaServer Pages (JSP)• Standard Tag Library for JavaServer

Pages (JSTL)• Java Servlets

• J2EE Connector Architecture (JCA)• J2EE Management Specification (JMX)• Java Transaction API (JTA)

Page 20: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

What are the Java technology components?

• Technologies in J2ME:

• Connected Limited Device Configuration (CLDC)

• Mobile Information Device Profile (MIDP)• Connected Device Configuration (CDC)• Mobile 3D Graphics API for J2ME (M3G)

Page 21: Curso de Programación Java Intermedio

Module 02• Object Oriented Programming

Page 22: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Objectives

• What is Object-Oriented Programming?

• Objects

• Classes

• Message and Object Communication

• OO in Java

• Declaring Java Classes

• Declaring Attributes

• Declaring Methods

• Example Methods and Attributes

• Declaring Constructors

• The Default Constructor

Page 23: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Source File Layout

• The package Statement

• The package and import Statement

• Packages and visibility

Page 24: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Objectives

• Define class, member, attribute, method, constructor, andpackage

• Use the access modifiers private and public as appropriate forthe guidelines of encapsulation

• Invoke a method on a particular object

• In a Java program, identify the following:

― The package statement

― The import statements

― Classes, methods, and attributes

― Constructors

Page 25: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

What is Object-Oriented Programming?

• A set of implementation techniques that:

– Can be done in any programming language

– May be very difficult to do in some programming languages• A strong reflection of software engineering

– Abstract data types

– Information hiding (encapsulation)• A way of encouraging code reuse

– Produces more malleable systems• A way of keeping the programmer in touch with the problem

– Real world objects and actions match program objects and actions

Page 26: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Objects

• Objects are:

– Are building blocks for systems

– Contain data that can be used or modified

• Bundle of variables and related methods• An object possesses:

– Identity

• A means of distinguishing it from other objects

– State

• What the object remembers

– Interface

• Messages the object responds to

– Behavior

• What the object can do

Page 27: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Classes

• A class

– Defines the characteristics and variables common to all objects of that class

• Objects of the same class are similar with respect to:

– Interface

– Behavior

– State• Used to instantiate (create an instance of) specific objects

• Provide the ability of reusability

Page 28: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Message and Object Communication

• Objects communicate via messages

• Messages in Java correspond to method calls (invocations)

• Three components comprise a message:

1.The object to whom the message is addressed

2.The name of the method to perform

3.Any parameters needed by the method

sender target

setSomething()

Page 29: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

OO in Java

• The Java language is a mixture of objects and no objects

• The Java language gives every OO programmer the tools necessary to follow all of the OO rules and produce very OO code, but doing so requires discipline

• Language elements:

– Class-based object-oriented programming language with inheritance

– A class is a template that defines how an object will look and behave once instantiated

• Java supports both instance and class (static) variables and methods

Page 30: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

OO in Java

• Nearly everything is an object

– They are accessed via references

– Their behavior can be exposed via public methods

– They are instantiated using the new construct

• Classes in Java may have methods

and attributes.

• Methods define actions that a class

can perform.

• Attributes describe the class.

Page 31: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Declaring Java Classes

• Classes have two types of members: variables (or data members) and methods.

• All of the member‘s of a class are defined within the class‘s body, which exits between a single set of curly braces for the class

• Basic syntax of a Java class:

< modifiers> class < class_name> {[< attribute_declarations>][< constructor_declarations>][< method_declarations>]

}

Page 32: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Declaring Attributes

• A variable has an access specifier, a data type, a name, and (optionally) an initial value

• Basic syntax of an attribute:

<modifiers><type><name>[=<initial_value>]

public class Computer {boolean cpu,keyboard,mouse; //attributesString monitor; //attribute

}

Page 33: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Declaring Methods

• The methods of a class define what it can do

• There are two flavors of method in the Java language:

– Constructors

– Other methods• Basic syntax of a method:

• Every method has a return type, but not every method return something

• If the method returns nothing, you use the keyword void as return type

<modifiers><return_type><name>([argument_list]) { }

Page 34: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Example Methods and Attributes

public class Dog {

private int weight; //attribute

public int getWeight() { //methodreturn weight;

}

public void setWeight(int newWeight) { //methodweight = newWeight;

}}

Page 35: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Example Methods and Attributespublic class Cat {private String animalType = “feline”; //default valueprivate String catColor”; //attribute

public Cat() { //constructorcatColor = “black”;

}public Cat(String colorIn) { //overloaded constructorsetCatColor(colorIn);

}

public String getCatColor() { //getterreturn catColor;

}public void setCatColor(String color) { //mutatorcatColor = color;

}}

Page 36: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Declaring Constructors

• A constructor is used when creating an object from a class.

• The constructor name must match the name of the class and must not have a return type.

• They can be overloaded, but they are not inherited by subclasses.

• Basic syntax of a constructor:

<modifier><class_name><name>([argument_list]) { <[argument_list]>

}

Page 37: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Declaring Constructors

• Example:

public class Dog {private int weight;private String name = "noname";

public Dog(String name) {this.name = name;

}

public int getWeight() { return weight;

}public void setWeight(int newWeight) {weight = newWeight;

}}

Page 38: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Declaring Constructors

• A constructor can be invoked only from other constructors.

• To invoke a constructor in the same class, invoke the this() function with matching arguments.

public class Circle {public double radio;public Circle(double r) { this.radio = r; }public Circle() { this(1.0); }

public double circumferencia() { return 2 * Math.PI; }public double area() { return Math.PI * radio * radio; }

public static void main(String[] args) {Circle obj1 = new Circle();Circle obj2 = new Circle(5.6);

}}

Page 39: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The Default Constructor

• There is always at least one constructor in every class.

• If the writer does not supply any constructors, the defaultconstructor is present automatically:

― The default constructor takes no arguments

― The default constructor body is empty• Enables you to create object instances with new Xxx() without

having to write a constructor.

• A constructor cannot have any return type even void.

• You can't make a new object without invoking a constructor.

• Every class, including abstract classes, must have a constructor.

• Constructors are never inherited, thus cannot be overriden.

Page 40: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Source File Layout

• Logically, Java programs are made up of classes that are grouped into packages. Physically, your program is written in a collection of source code files. Almost every Java compiler in the world forces this organization:

1.package declaration

2. import declaration

3.class declaration

Page 41: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The package statement

• Every Java object exits in a package.

• A package is simply a set of objects,

all of which are related in some way.

• Classes can be grouped:

– Logically, according to the

model you

are building

– As sets designed to be used

together

– For convenience

• By convention, package names are in

lower case

• Different packages can contain

classes with the same name

Packages refer to a file path

on your file system. Packages

names use dot notation to

translate that file path into

something the Java platform

understands

Page 42: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The package statement

package mystuff;public class MyStuffClass {

public void callMe() {System.out.println("MyStuffClass");

}public static void main(String[] args) {System.out.println("Inside mystuff.MyStuffClass");

}}

package yourstuff;public class YourStuffClass {

public void callMe() {System.out.println(“YourStuffClass");

}public static void main(String[] args) {System.out.println("Inside yourstuff.YourStuffClass");

}}

Page 43: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The package statement

package ourstuff;public class OurStuffClass {public void callMe() {

System.out.println("OurStuffClass");}public static void main(String[] args) {System.out.println("Inside ourstuff.OurStuffClass");

}}

Page 44: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The package and import Statement

package mainstuff;import ourstuff.*;import yourstuff.*;import mystuff.*;

public class RunStuff {

public static void main(String[] args) {System.out.println("Inside RunStuff");

MyStuffClass msc = new MyStuffClass();msc.callMe();YourStuffClass ysc = new YourStuffClass();ysc.callMe();OurStuffClass osc = new OurStuffClass();osc.callMe();

}}

Page 45: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The package and import Statement

• When an object makes use of objects in other packages, the Java compiler needs to know where to find them

• An import statement tells the compiler where to find the classes.

• You can have many imports as you need to tell Java where to find all the classes:

import java.util.ArrayList;import java.math.BigInteger;import java.util.*;

Page 46: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Packages and visibility

• Visibility of a class controls the capability of other classes to create objects or gain access to the variables and methods in the class.

• There are various types of visibility, as follows:

– Public

– Protected

– Default, or package

– Private

Page 47: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Packages and visibility

• Private access: The private keyword is not used with classes, only with variables and methods. A private variable or method can be used within a class only.

Page 48: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Packages and visibility

• Public access: A class, variable, or method declared public can be used by any class in the program.

Page 49: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Packages and visibility

• Package access: If none of the visibility keywords is used, the item is said to have package visibility, meaning that only classes in the same package can use it.

Page 50: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Packages and visibility

• Protected access: A variable or method declared protected can be used only by classes in the same package or in a derived class in the same or a different package.

Page 51: Curso de Programación Java Intermedio

Module 03• Identifiers, Keywords and Types

Page 52: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Objectives

• Comments

• Semicolons, Blocks, and White Space

• Identifiers

• Java keywords

• Primitive Types

• Primitive: Integers

• Primitive: Floating Points

• Primitive: Characters

• Primitive: Booleans

• Primitive Literals

• Primitive Literals: Integers

Page 53: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Primitive Literals: Floating Point

• Primitive Literals: Escape Sequences

• Declarations and Initialization

• Casting Primitive Types

• Implicit versus Explicit Casting

• Java Reference Types

• Constructing and Initializing Objects

• Assigning References

• Pass by Value

• The this Reference

Page 54: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Objectives

• Use comments in a source program

• Distinguish between valid and invalid identifiers

• Recognize Java technology keywords

• List the eight primitive types

• Define literal values for numeric and textual types

• Define the terms primitive variable and reference variable

• Declare variables of class type

• Construct an object using new

• Describe default initialization

• Describe the significance of a reference variable

• State the consequences of assigning variables of class type

Page 55: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Comments

The three permissible styles of comment in a Java program are:

Page 56: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Semicolons, Blocks and White Space

• A statement is one or more lines of code terminated by asemicolon (;):

• Several statements can be written on one line, or can be split over several lines

• A block is a collection of statements bound by opening and closing braces:

System.out.println(

This is part of the same line);

a = 0; b = 1; c = 2

{x = y + 1;y = x + 1;

}

Page 57: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Semicolons, Blocks and White Space

• Any amount of white space is allowed in a Java program

• Spaces, blank lines, and tabs are collectively called white space

• White space is used to separate words and symbols in a program

• Extra white space is ignored

• A valid Java program can be formatted many different ways

• Programs should be formatted to enhance readability, using consistent indentation

public classHelloWorld { public static void main

(String[] args) {System.out.println(“Hellow World!!”);

}}

Page 58: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Identifiers

• Are names given to a variable, class, or method

• Can start with a Unicode letter, underscore (_), or dollar sign ($)

• Are case-sensitive and have no maximum length

• Examples:

An-Identifier2nd_Identifiergoto10$

An_Identifiera_2nd_IdentifierGo2$10

Page 59: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Identifiers

• Yourname, yourname, yourName, YourName

– These are four different identifiers• Conventions:

– Package: all lower case

• theexample– Class: initial upper case, composite words with upper case

• TheExample– Method/field: initial lower, composite words with upper case

• theExample– Constants: all upper case

• THE_EXAMPLE

Page 60: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Java Keywords

abstract continue goto package synchronized

assert default if private this

boolean do implements protected throw

break double import public throws

byte else instanceof return transient

case extends int short try

catch final interface static void

char finally long strictfp volatile

class float native super while

const for new switch

Page 61: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Primitive Types

Page 62: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Primitive: Integers

• Signed whole numbers

• Initialized to zero

Page 63: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Primitive: Floating Points

• ―General‖ numbers

– Can have fractional parts• Initialized to zero

Page 64: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Primitive: Characters

• Char is any unsigned Unicode character

• Initialized to zero (\u0000)

Page 65: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Primitive: Booleans

• boolean values are distinct in Java

– Can only have a true or false value

– An int value can NOT be used in place of a boolean• Initialized to false

Page 66: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Primitive Literals

• A literal is a value

• There are five kinds of literals:

– Integer

– Floating point

– Boolean

– Character

– String

Literals

integer…………..7

floating point…7.0f

boolean……….true

character……….'A'

string………….."A"

Page 67: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Primitive Literals: Integers

• Octals are prefixed with a zero:

– 032• Hexadecimals are prefixed with a zero and an x:

– 0x1A• Follow a literal with ―L‖ to indicate a long

– 26L• Upper and lower case are equivalent

Decimal:

26

Page 68: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Primitive Literals: Floating Point

• Float literals end with an f (or F):

– 7.1f

• Double literals end with a d (or D):

– 7.1D

• An ‗e‘ or ‗E‘ is used for scientific notation:

– 7.1e2

• A floating point number with no final letter is a double:

– 7.1 is the same as 7.1d

• Upper and lower case are equivalent

Page 69: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Primitive Literals: Escape Sequences

• Some keystrokes can be simulated with an escape sequence:

– \b backspace

– \f form feed

– \n newline

– \r return

– \t tab

• Some characters may need to be escaped when used in string literals

– \" quotation mark

– \’ apostrophe

– \\ backslash

• Hexadecimal Unicode values can also be written ‗\uXXXX‘

Page 70: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Declaration and Initialization

• Variables must be declared before they can be used

• Single value variables (not arrays) must be

initialized before their first use in an expression

– Declarations and initializations can be combined

– Use ‗=‘ for assignment (including initialization)• Examples:

int i, j;i = 0;int k=i+1;float x=1.0, y=2.0;System.out.println(i); //prints 0System.out.println(k); //prints 1System.out.println(j); //compile error

Page 71: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Casting Primitive Types

• Casting creates a new value and allows it to be treated as a different type than its source

• Java is a strictly typed language

– Assigning the wrong type of value to a variable could result in a compile error or a JVM exception

• The JVM can implicitly promote from a narrower type to a wider type

• To change to a narrower type, you must cast explicitly

int a, b;

short c;

a = b + c;

int d;

short e;

e = (short)d;

double f;

long g;

f = g;

g = f; //error

Page 72: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Implicit versus Explicit Casting

• Implicit casting is automatic when no loss of information is possible

• An explicit cast required when there is a ―potential‖ loss of accuracy

Page 73: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Implicit versus Explicit Casting

public class ExplicitCasting { public static void main( String args[] ) {short s = 259;byte b = (byte)s;System.out.println(" s = " + s + " , b = " + b );

} }

1100000010000000

11000000

b = (byte)s

Page 74: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Java Reference Types

• The three references types provided by Java are array, class and interface.

• A reference is a data element that holds the address of a memory location.

• A reference variable contains a ―handle‖ to an object.

Page 75: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Constructing and Initializing Objects

• Calling new Xxx() to allocate space for the new object results in:memory allocation

• Space for the new object is allocated and instance variables areinitialized to their default values (for example, 0, false, null,and so on)

• Explicit attribute initialization is performed

• A constructor is executed• The reference to the object is assigned to a variable

Page 76: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Constructing and Initializing Objects

public class Shirt {public int shirtID = 0; public String description = "-description required-"; public char colorCode = „U‟;public double price = 0.0; public int quantityInStock = 0;

public void displayShirtInformation() {System.out.println("Shirt ID: " + shirtID);System.out.println("Shirt description:" + description);System.out.println("Color Code: " + colorCode);System.out.println("Shirt price: " + price);System.out.println("Quantity in stock: " + quantityInStock);

}}

Page 77: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Constructing and Initializing Objects

public class ShirtTest {public static void main (String args[]) {

int counter = 10;Shirt myShirt = new Shirt();Shirt yourShirt = new Shirt();

}

}

Page 78: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Assigning References

public class ShirtTest {public static void main (String args[]) {

int counter = 10;Shirt myShirt = new Shirt();Shirt yourShirt = new Shirt();

}}

Page 79: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Pass by value

• In a single Virtual Machine, the Java programming language onlypasses arguments by value.

• If the variable passed is a primitive, only a copy of the variableis actually passed to the method. So modifying the variablewithin the method has no effect on the actual variable.

• When you pass an object variable into a method, a copy of thereference variable is actually passed. In this case, bothvariables refer to the same object. If the object is modifiedinside the method, the change is visible in the original variablealso.

• Though the called method can change the object referred by thevariable passed, it cannot change the actual variable in thecalling method. In other words, you cannot reassign the originalreference variable to some other value.

Page 80: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Pass by value

public class PassByValue {static void change(MyClass x) {

x.setNum(9);}public static void main(String[] args) {

MyClass my = new MyClass();change(my);System.out.println(my.getNum()); //Prints 9

}}class MyClass {int a = 3;void setNum(int a) {

this.a = a; }int getNum() {

return a;}

}

Page 81: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Pass by value

public void foo(Dog d) { d = new Dog(“Fifi”);

}

Dog aDog = new Dog(“Max”);foo(aDog);

The variable passed in (aDog) is not modified! After calling foo,

aDog still points to the "Max" Dog!

When an object instance is passed as an argument to a method, the

value of the argument is a reference to the object.

The contents of the object can be changed in the called method, but

the original object reference is never changed.

Page 82: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The this reference

• Here are a few uses of the this keyword:

– Resolving ambiguity: To reference a member within code that has localvariables or arguments with the same name as that member

– To pass the current object as a parameter to another method orconstructor

public class MyDate {private int day = 1;private int month = 1;private int year = 2000;public MyDate(int day, int month, int year) {this.day = day;this.month = month;this.year = year;

}public MyDate(MyDate date) {this.day = date.day;this.month = date.month;this.year = date.year;

}}

Page 83: Curso de Programación Java Intermedio

Module 04• Expressions and Flow Control

Page 84: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Objectives

• Variables and Scope

• Operators

• Logical Operators

• Bitwise Logical Operators

• Right-Shift Operators >> and >>>

• Left Shift Operator <<

• Conditional Statement Types: switch

• The ternary Operator

• Looping Statement Types: while

• Looping Statement Types: for

• for vs. while

• Branching Statements

Page 85: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Objectives

• Distinguish between instance and local variables

• Recognize, describe, and use Java software operators

• Identify boolean expressions and their requirements in controlconstructs

• Use if, switch, for, while, and do constructions and the labeledforms of break and continue as flow control structures in aprogram

Page 86: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Scope

• A variable's scope is the region of a program within which the variable can be referred to

– Variables declared in:• Methods can only be accessed in that method

• A Loop or a block can only be accessed in that loop or block

Page 87: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Operators

• Operators are the ―glue‖ of expressions

• Precedence – which operator is evaluated first – is determined explicitly by parentheses or implicitly as follows:

Page 88: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Logical Operators

• The boolean operators are:

! – NOT & – AND

| – OR ^ – XOR

• The short-circuit boolean operators are:

&& – AND || – OR

Page 89: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Bitwise Logical Operators

• The integer bitwise operators are:

~ – Complement & – AND

^ – XOR | – OR

• Byte-sized examples:

Page 90: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Right-Shift Operators >> and >>>

• Arithmetic or signed right shift (>>) is used as follows:

• The sign bit is copied during the shift

• 8 >> 1;• Before shifting: 0000 0000 0000 0000 0000 0000 0000 0000 1000

• After Shifting: 0000 0000 0000 0000 0000 0000 0000 0000 0100

Page 91: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Right-Shift Operators >> and >>>

Page 92: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Right-Shift Operators >> and >>>

• A logical or unsigned right-shift operator (>>>) is:

• Used for bit patterns.

• The sign bit is not copied during the shift.

Page 93: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Left-Shift Operators <<

• Left-shift works as follows:

128 << 1 returns 128 * 21 = 256

16 << 2 returns 16 * 22 = 64

Page 94: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Conditional Statement Types: if-else

• An if-else statement is a conditional expression that must return a boolean value

• else clause is optional

• Braces are not needed for single statements but highly recommended for clarity

if(x > 10) {if(x != 20) {

System.out.println(“x is not 20”);}else {

System.out.println(“x = ” + x);}

}else {

System.out.println(“x is less than 11”);}

Page 95: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

if (day == 0 || day == 1) {rule = “weekend”;

} else if (day > 1 && day <7) {rule = “weekday”;

} else {rule = error;

}

switch (day) { case 0: case 1:

rule = “weekend”;break;

case 2:…

case 6:rule = “weekday”;break;

default:rule = “error”;

}

Conditional Statement Types: switch

• Switch statements test a single variable for several alternative values

• Cases without break will ―fall through‖ (next case will execute)

• default clause handles values not explicitly handled by a case

Page 96: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

• Shortcut for if-else statement:

(<boolean-expr> ? <true-choice> : <false-choice>)

• Can result in shorter code

– Make sure code is still readable

warning = (x>LIMIT) ? “Too Big” : null ;

VS.

if (x>LIMIT) {warning = “Too Big”;

} else {warning = null;

}

The Ternary Operator

Page 97: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Looping Statements Types: while

• Executes a statement or block as long as the condition remains true

• while () executes zero or more times‘

• do...while() executes at least once.

int x = 2;while (x < 2) {

x++;System.out.println(x);

}int x = 2;do {

x++; System.out.println(x);

} while (x < 2);

Page 98: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Looping Statements Types: for

• A for loop executes the statement or block { } which follows it

– Evaluates "start expression" once

– Continues as long as the "test expression" is true

– Evaluates "increment expression" after each iteration• A variable can be declared in the for statement

– Typically used to declare a "counter" variable

– Typically declared in the ―start‖ expression

– Its scope is restricted to the loop

for (start expr; test expr; increment expr) {// code to execute repeatedly

} for (int index = 0; index < 10; index++) {

System.out.println(index);}

Page 99: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

for vs while

• These statements provide equivalent functionality

– Each can be implemented in terms of the other• Used in different situations

– while tends to be used for open-ended looping

– for tends to be used for looping over a fixed number of iterations

int sum = 0;for (int index = 1; index <= 10; index++) {

sum += index;}

int sum = 0;int index = 1;while (index <= 10) {

sum += index;index++;

}

Page 100: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Branching Statements

• break

– Can be used outside of a switch statement

– Terminates a for, while or do-while loop

– Two forms:

• Labeled: execution continues at next statement outside the loop

• Unlabeled: execution continues at next statement after labeled loop

• continue

– Like break, but merely finishes this round of the loop

– Labeled and unlabeled form• return

– Exits the current method

– May include an expression to be returned

• Type must match method‘s return type

• Return type ―void‖ means no value can be returned

Page 101: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Branching Statements

Page 102: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Branching Statements

public int myMethod(int x) {int sum = 0;outer: for (int i=0; i<x; i++) {

inner: for (int j=i; j<x; j++) {sum++;if (j==1) continue;if (j==2) continue outer;if (i==3) break;if (j==4) break outer;

}}return sum;

}

Page 103: Curso de Programación Java Intermedio

Module 05• Arrays

Page 104: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Objectives

• Declaring Arrays

• Creating Arrays

• Initializing Arrays

• Multidimensional Arrays

• Array Bounds

• Array Resizing

Page 105: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Objectives

• Declare and create arrays of primitive, class, or array types

• Explain why elements of an array are initialized

• Explain how to initialize the elements of an array

• Determine the number of elements in an array

• Create a multidimensional array

Page 106: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Declaring Arrays

• The primary purpose of an array is to facilitate storing and manipulating large quantities of data.

• An array stores a sequence of values that are all of the same type.

• The method that we use to refer to individual values in an array is to number and then index them - if we have N values, we think of them as being numbered from 0 to N-1. Then, we can unambiguously specify one of them by referring to the ith value for any value of i from 0 to N-1.

Page 107: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Creating Arrays

• Use the new keyword to create an array object.

• For example, a primitive (char) array:

public char[] createArray() { char[] s; s = new char[26]; for (int i=0;i<26;i++) {

s[i] = (char)('A'+i); } return s;

}

Page 108: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Creating Arrays

• Use the new keyword to create an array object.

• For example, a primitive (char) array:

public Point[] createArray() { Point[] p; p = new Point[10]; for (int i=0;i<10;i++){

p[i] = new Point(i, i+1); } return p;

}

Page 109: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Initializing Arrays

• Initialize an array element

• Create an array with initial values:

int [] marks = new int[100];String [][] s = new String[3][];String a[] = {new String(“apple”),new String(“mango”)};int i [][] = {{1,2},{3,4}};

int [] x;x = new int[100];for(int i=0;i<x;i++) {

x[i] = i*i; }

Page 110: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Initializing Arrays

public class Point { public int xValue; public int yValue;

}public class NewCircle { public Point location; public float radius; public boolean solid;

}NewCircle[] allCircles = new NewCircle[10]; allCircles[0] = new NewCircle(); allCircles[0] = myNewCircle; allCircles[1] = new NewCircle(); allCircles[1].location = new Point(); allCircles[1].location.xValue = 6; allCircles[1].location.yValue = 6; allCircles[1].radius = 1.3f;

allCircles[1].solid = false;

Page 111: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Multidimensional Arrays

• Arrays of arrays:

Page 112: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Multidimensional Arrays

• Non-rectangular arrays of arrays:

int [][] twoDim = new int[4][];twoDim[0] = new int[2];twoDim[1] = new int[4];twoDim[2] = new int[6];twoDim[3] = new int[8];

int twoDim[][] = new int[4][5];

Page 113: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Array Bounds

• All array subcripts begin at 0

int [] list = new int[10];

for(int i=0;i<list.length;i++) {System.out.println(list[i]);

}

double[] v;v = new double[5];System.out.println(v.length);

Page 114: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Array resizing

• Cannot resize an array

• Can use the same reference variable to refer to an entirely new array:

int myArray[] = new int[6];myArray = new int[10];

private void resize() { String[] temp = new String[2*N]; for (int i = 0; i < N; i++)

temp[i] = a[i]; a = temp; }

Page 115: Curso de Programación Java Intermedio

Module 06• Class Design

Page 116: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Agenda

• Objectives

• Classes

• Java Keywords Used in Class Declarations

• The class body

• The class members

• Classes with only static members

• Variable initialization

• More on variable modifiers

• Methods

• Java Keywords used with methods

Page 117: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Single Inheritance

• Access Control

• Overriding Methods

• The super Keyword

• Polymorphism

• The instance of Operator

• Casting Objects

• The Object Class

• The == Operator Compared with the equals method

• The toString method

• Wrapper Classes

Page 118: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Objectives

• Define inheritance, polymorphism, overloading, overriding, andvirtual method invocation

• Use the access modifiers protected and ―package-friendly‖

• Describe the concepts of constructor and method overloading

• Describe the complete object construction and initializationoperation

• In a Java program, identify the following:

• Overloaded methods and constructors

• The use of this to call overloaded constructors

• Overridden methods

• Invocation of super class methods

• Parent class constructors

• Invocation of parent class constructors

Page 119: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Classes

• Classes are the core concept of the Java language.

• It is essential to understand how to create a class.

• Java classes are always defined inside a single source code file.

• package and import statements at the start of the file tell the compiler which resources can be used to compile the class.

• A class is defined with a declaration followed by a block of code inside a bracket pair.

• At the start of the declaration, keywords describe where the class fits in the Java class hierarchy and control the accessibility of the class.

Page 120: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Classes

• The components of a class declaration are as follows:

– Class modifiers— An optional set of keywords.

– Class keyword— The word "class" must appear here.

– Class name— A Java name that must be unique within the package.

– Superclass name— Optionally, the word extends followed by the name of the parent class. If this does not appear, the class extends java.lang.Object by default.

– Interfaces implemented— Optionally, the word implements followed by a list of interface names.

– Class body— The code that declares the fields and methods of the class.

Page 121: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Classes

Page 122: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Java Keywords Used in Class Declarations

• public.-This class is visible to all classes in the program. If this word is not used, this class is visible only within the package.

• abstract.-The abstract keyword must be used if a class contains one or more abstract method(s). However, a class may be declared abstract even if it does not contain any abstract method. A class declared abstract cannot be used to create an object.

• final.-This class cannot be subclassed. This word cannot be used with abstract.

Page 123: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Java Keywords Used in Class Declarations

• extends.-The class name following this keyword is the parent of this class. If this word is not used, the Object class is the parent.

• implements.-This class provides for all the methods required by the interfaces that follow this keyword. Any number of interfaces can be implemented.

• Classes cannot be protected, private, native, or synchronized.

• The words "abstract" and "final" cannot appear together because an abstract class, by definition, must be extended before it can be used.

Page 124: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The class body

• The class body contains the declarations of the members of the class.

• These include fields (variables), methods, static initializers, instance initializers, and constructors.

• You can also have class definitions inside a class body.

• These nested classes are considered to be members of the enclosing class and have a special relationship with it.

Page 125: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The class members

• Access to class members of all types is controlled by access modifier keywords and the no-keyword default as follows:

– public— A public member is accessible from any class in the program.

– protected— A protected member can be accessed only by classes in the same package and classes derived from the current class—no matter which package they are in.

– private— A private member can be accessed only from within the class.

– default— If none of the other access modifier keywords appear, the default applies (access only by classes in the same package).

– Other keywords that can be applied to class members are static, final, abstract, native, transient, volatile, strictfp, and synchronized.

Page 126: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Classes with only static members

• It is quite feasible to have classes that have only static members.

• These classes do not have public constructors and cannot be used to create an object.

• An example of this is the Math class in the Java standard library, which is used to provide typical mathematical functions. You address the static variables and methods with notation similar to that used with instance variables but with the name of the class instead of an instance reference, as shown in the following code:

area = Math.PI * rad * rad ; // addressing a static constant

root = Math.sqrt( area ) ; // addressing a static method

Page 127: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Variable initialization

• Both instance variables and class (static) variables have default initialization values that are used if the variable declaration statement does not include initial values.

• Class variables are initialized when the class is loaded by the JVM, and instance variables are initialized when an object is created.

• In contrast, there is no default initialization for variables that are declared inside the scope of methods or smaller code blocks.

– Integer primitives are initialized to 0.

– Floating-point primitives are initialized to 0.0.

– Boolean primitives are initialized to false.

– Reference variables are initialized to null.

Page 128: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

More on variable modifiers

• The modifiers abstract, native, and synchronized are not used with variable declarations.

• The keyword transient is used to indicate variables that do not need to be saved when an object is saved using the object serialization methods.

• The keyword volatile is used to signal to the compiler that the designated variable may be changed by multiple threads and that the compiler cannot take any shortcuts when writing the code responsible for retrieving the value in this variable.

Page 129: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

More on variable modifiers

Page 130: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Methods

• Methods are defined with a method declaration. The elements in a method declaration are access modifier, additional modifiers, return type, method name, parameter list, and exceptions.

• The combination of name and parameter list constitutes the method signature.

• Note that if one of the access modifiers—public, private, or protected—does not appear, the default is visibility within the package.

Page 131: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Java keywords used with Methods

• public.-The method is visible to all classes in the program.

• private.-The method is visible only inside the class.

• protected.-The method is visible to classes inside the package and to subclasses.

• final.-The method cannot be overridden in subclasses.

• abstract.-The method is declared without an implementation.

• static.-The method is independent of any object of the class but can address only static variables.

• native.-The native modifier indicates that the method is not written in the Java language, but in a native language

Page 132: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Java keywords used with Methods

• strictfp.- The strictfp keyword, which is used only for methods and classes, forces floating points to adhere to IEE754 standard

• synchronized.- A Thread entering this method obtains a lock on the object, which prevents other Threads from entering any synchronized code for the object.

• throws.-This word introduces a list of checked exceptions that the method may throw.

• void.-If the method does not return a value, the word void must appear as the return type.

Page 133: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Single Inheritance

• When a class inherits from only one class, it is called singleinheritance.

• Interfaces provide the benefits of multiple inheritance withoutdrawbacks.

Page 134: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Single Inheritance

• Each subclass inherits the fields of its superclass

– These fields in the superclass may have been inherited from classes even further up in the class hierarchy

• Each subclass inherits the methods of its superclass

• –An object will understand all messages which its class has implemented or its superclass has either inherited or implemented

Page 135: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Single Inheritance

Page 136: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Access Control

Page 137: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Access Control

Page 138: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Access Control

Page 139: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Overriding Methods

• A subclass can modify behavior inherited from a parent class.

• A subclass can create a method with different functionality thanthe parent‘s method but with the same:

– Name

– Return type

– Argument list

Page 140: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The super keyword

• Only constructors within the class being instantiated and withinthe immediate superclass can be invoked

• A constructor can call another constructor in its superclass using the keyword super and the parameter list

• The parameter list must match that of an existing constructor in the superclass

• Constructors in the same class are invoked with the keyword thisand the parameter list

• The first line of your constructor can be one of:

– super(…);

– this(…);

Page 141: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The super keyword

Page 142: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The super keyword

• Superclass objects are built before the subclass

– The compiler supplies an implicit super() call for all constructors

– super(…) initializes superclass members• If the first line of your constructor is not a call to another

constructor, super() is called automatically

– Zero-argument constructor in the superclass is called as a result

– This can cause an error if the superclass does not have a zero-argument constructor

Page 143: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The super keyword

• If you do not provide any constructors, a default zero argument constructor is provided for you

– The default zero-argument constructor just makes a call to super()

• If you implement any constructor, Java will no longer provide you with the default zero-argument constructor

– You can write your own zero-argument constructor which behaves like the default constructor (that is, just makes an implicit call to super())

Page 144: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Polymorphism

• Polymorphism means ―any forms‖

• In object oriented programming, it refers to the capability of objects to read differently to the same method

• Polymorphism can be implemented in the Java language in the form of multiple methods having the same name

• Java code uses late-binding technique to support polymorphism; the method to be invoked is decided at runtime

Page 145: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Polymorphism

Page 146: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The instance of Operator

public class Employee extends Objectpublic class Manager extends Employeepublic class Engineer extends Employee----------------------------------------

public void doSomething(Employee e) {if (e instanceof Manager) {

// Process a Manager} else if (e instanceof Engineer) {// Process an Engineer

} else {// Process any other type of Employee

}}

Page 147: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Casting Objects

• Use instanceof to test the type of an object

• Restore full functionality of an object by casting

• Check for proper casting using the following guidelines:

– Casts up hierarchy are done implicitly.

– Downward casts must be to a subclass and checked bythe compiler.

– The object type is checked at runtime when runtimeerrors can occur.

Page 148: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Casting Objects

Page 149: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The Object Class

• The Object class is the root of all classes in Java

• A class declaration with no extends clause, implicitly uses ―extends the Object

public class Employee {

...

}

is equivalent to:

public class Employee extends Object {

...

}

Page 150: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The Object Class

• Object doesn't have any instance variables but it does have a small number of methods.

Page 151: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The == Operator Compared with the equals method

• The == operator determines if two references are identical toeach other (that is, refer to the same object).

• The equals method determines if objects are ―equal‖ but notnecessarily identical.

• The Object implementation of the equals method uses the ==operator.

• User classes can override the equals method to implement adomain-specific test for equality.

• Note: You should override the hashCode method if you overridethe equals method.

Page 152: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Equals Example

public class EqualTest { public static void main(String args[]) {

Double Obj1 = new Double(2.43); Double Obj2 = new Double(2.43); Double Obj3 = Obj1;

System.out.println("These objects are equal: "); System.out.println(Obj1 == Obj2); System.out.println(Obj1 == Obj3); System.out.println(Obj1.equals(Obj2));

} }

Page 153: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The toString method

• Converts an object to a String.

• Used during string concatenation.

• Override this method to provide information about a user-defined object in readable format.

• Primitive types are converted to a String using the wrapperclass‘s toString static method.

Page 154: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The toString method

public class Person { private String name; private int age; private String hobby;

public Person(String name, int age, String hobby) { this.name = name; this.age = age; this.hobby = hobby;

} public String toString() {

String description; description = "Name: " + this.name + ", Age:" + this.age + ", Hobby: " + this.hobby; return description;

}

}

Page 155: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Wrapper Classes

• The wrapper classes in the Java API serve two primary purposes:

– To provide a mechanism to ―wrap‖ primitive values in an object so that the primitives can be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value.

– To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting primitives to and from String objects, and converting primitives and String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.

Page 156: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Wrapper Classes

Page 157: Curso de Programación Java Intermedio

Module 07• Advanced Class Features

Page 158: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Objectives

• Relevance

• The static Keyword

• Class Attributes

• Class Methods

• Static Initializers

• Abstract Classes

• Abstract Modifiers

• Abstract Methods

• Abstract Class and Reference

• Abstract Classes Example

Page 159: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Interfaces

• Interface Example

• Uses of Interfaces

• Nested Classes

• Properties of Nested Classes

• Nested and Inner Classes

Page 160: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Objectives

• Describe static variables, methods, and initializers

• Describe final classes, methods, and variables

• Explain how and when to use abstract classes and methods

• Explain how and when to use nested classes

• Distinguish between static and non-static nested classes

• Explain how and when to use an interface

• In a Java software program, identify:

• static methods and attributes

• final methods and attributes

• Nested classes

• interface and abstract classes

• abstract methods

Page 161: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The static Keyword

• The static keyword is used as a

modifier on variables, methods,

and nested classes.

• The static keyword declares the

attribute or method is associated

with the class as a whole rather

than any particular instance of that

class.

• Thus static members are often

called “class members,” such as

“class attributes” or “class

methods.”

Page 162: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Class Attributes

• Are shared among all instances of a class

• Can be accessed from outside the class without an instance of the class (if marked as public)

public class Count { private int serialNumber; private static int counter = 0;

public Count() {counter++;serialNumber = counter;

}

public class OtherClass {public void incrementNumber() {

Count1.counter++;}

}

Page 163: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Class Attributes

• You can invoke static method without any instance of the classto which it belongs

public class Count2 {private int serialNumber;private static int counter = 0;

public static int getTotalCount() {return counter;

}

public Count2() {counter++;serialNumber = counter;

}}

Page 164: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Class Attributes

public class TestCounter {public static void main(String[] args) {

System.out.println("Number of counter is “ + Count.getTotalCount());Count count1 = new Count();System.out.println( "Number of counter is “ + Count.getTotalCount());

}}

Page 165: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Static Initializers

• A class can contain code in a static block that does not existwithin a method body

• Static block code executes only once, when the class is loaded

• A static block is usually used to initialize static (class) attributes

public class Count4 {public static int counter;static {

counter = Integer.getInteger("myApp.Count4.counter").intValue}}public class TestStaticInit {

public static void main(String[] args) {System.out.println("counter = "+ Count4.counter);

}}

Page 166: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Abstract Classes

• A class must be declared abstract if it has one or more methods

• declared abstract.

• You may declare a class abstract even if it has no abstract methods.

• Language designers use abstract classes to establish a pattern that can be filled out with concrete methods for a specific situation. For example, the java.lang.Number class is abstract because the language designers wanted to specify a set of methods that all the wrapper classes representing numbers, such as Integer, have to implement.

Page 167: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Abstract Classes

• Java designers also like to use abstract classes to define a set of public final static variable values—the nearest thing Java has to constants. This way, all derived classes are forced to use the same set of constants. For example, the Calendar abstract class in the java.util package has int constants for the months of the year.

Page 168: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Abstract Classes

Page 169: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Abstract Modifiers

• The abstract modifier can be used in two ways, with a class and with a method

• When a class uses the abstract modifier with the class declaration, it is called an abstract class

• An abstract modifier is used with a class to indicate that the class cannot be instantiated

• The abstract modifier, when used in a method declaration, gives an abstract method

• The keyword abstract is used before the keyword class to define a class as an abstract class.

Page 170: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Abstract Methods

• The abstract modifier, when used in a method declaration, gives an abstract method

• Abstract methods can be present only inside an abstract class

• The following is the general structure of declaring an abstract method:

abstract returntype methodName(listofarguments);

Page 171: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Abstract Class and Reference

• Although we cannot instantiate an abstract class, we can create a reference to it

• This reference can be assigned references of sub-classes of the class

• This feature is very useful in achieving polymorphism

Page 172: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Abstract Class Example

Page 173: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Interfaces

• A ―public interface‖ is a contract between client code and the class that implements that interface.

• A Java interface is a formal declaration of such a contract in which all methods contain no implementation.

• Many unrelated classes can implement the same interface.

• A class can implement many unrelated interfaces.

Page 174: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Interface Example

Page 175: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Interface Example

Page 176: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Interface Example

Page 177: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Interface Example

public class Bird extends Animal implements Flyer {public void takeOff() { /* take-off implementation */ }public void land() { /* landing implementation */ }public void fly() { /* fly implementation */ }public void buildNest() { /* nest building behavior */ }public void layEggs() { /* egg laying behavior */ }public void eat() { /* override eating behavior */ }

}

Page 178: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Nested Classes

• Allow a class definition to be placed inside another classdefinition

• Group classes that logically belong together

• Have access to their enclosing class‘s scope

class OuterClass { ... class NestedClass {

... }

}

Page 179: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Nested Classes

Page 180: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Nested Classes

• Nested static class— A named class declared static. It can directly access only static variables and methods. It is considered a top-level class, and may be declared with the usual access modifiers for classes.

• Nested interface— A named interface, declared as a static member of a class, typically used for defining methods used to access the enclosing class. As usual with interfaces, it is assumed to be public.

• Inner class (member)— A named class defined as a member of the enclosing class. It must be associated with an instance of the enclosing class. There can be multiple member inner classes in an enclosing class. You can also have an inner class contained in an inner class. Member inner classes can be declared as public, private, protected, final, or abstract, but they cannot have the same name as any enclosing class.

Page 181: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Nested Classes

• Inner class (local)— A named class defined in a code block in a method of the enclosing class. The inner class can access local variables in the method and parameters passed to the method only if the variables are declared final. As with a local variable, the inner class cannot be accessed outside the code block; in other words, the scope of the class is confined to the code block.

• Inner class (anonymous)— A class defined inside a single expression, having no name or constructor method. These classes can access local variables in the method and parameters passed to the method only if they are declared final.

Page 182: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Nested Classes

Page 183: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Nested Classes

Page 184: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Nested Classes

Page 185: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Properties of Nested Classes

• Nested class names must be adequately qualified.

• Nested classes defined in a method are called local.

• Local classes can access final local variables.

• Nested classes can be abstract.

• Interfaces can be nested.

• Nested classes can access static members of enclosing scopes.

• Non-local classes can have any access protection.

• Nested and enclosing classes are compiled together.

Page 186: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Nested and Inner Classes

• Nested classes can be declared static.

• Non-static nested classes are called inner classes.

• Inner classes can access members of their enclosing instance using the this reference.

• Inner classes cannot declare static members except compile time constants.

Page 187: Curso de Programación Java Intermedio

Module 08• Exceptions and Assertions

Page 188: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Objectives

• Exceptions

• Exception Handling

• Exception sources

• The exception hierarchy

• Handling exceptions

• keywords

• try/catch blocks

• The catch clause

• The finally clause

• Nested exception handling

Page 189: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• The throw keyword

• Handling runtime exceptions

• Assertions

Page 190: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Objectives

• Define exceptions

• Use try, catch, and finally statements

• Describe exception categories

• Identify common exceptions

• Develop programs to handle your own exceptions

• Use assertions

• Distinguish appropriate and inappropriate uses of assertions

• Disable assertions at runtime

Page 191: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Exceptions

• An exception is an event or condition that disrupts the normal flow of execution in a program

– Exceptions are errors in a Java program

– The condition causes the system to throw an exception

– The flow of control is interrupted and a handler will catch the exception

public class HelloWorld {public static void main(String[] args) {

int i = 0;String greetings[] = { "Hello world!", "No, I mean it!",

"HELLO WORLD!!" };while (i < 4) {System.out.println(greetings[i]);i++;

}}

}

Page 192: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Exception Handling

• Exception handling is object-oriented

– It encapsulates unexpected conditions in an object

– It provides an elegant way to make programs robust

– It isolates abnormal from regular flow of control

Page 193: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Exception Handling

• JVM can detect unrecoverable conditions

– Examples:

• Class cannot be loaded

• Null object reference used

• Both core classes and code that you write can throw exceptions

– –Examples:

• IO error

• Divide by zero

• Data validation

• Business logic exception• Exceptions terminate execution

unless they are handled by the program

Page 194: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The exception hierarchy

• Throwable is the base class, and provides a common interface and implementation for most exceptions

• Error indicates serious problems that a reasonable application should not try to catch, such as:

– VirtualMachineError

– CoderMalfunctionError

• Exception heads the class of conditions that should usually be either caught or specified as thrown

• A RuntimeException can be thrown during the normal operation of the JVM

– Methods may choose to catch these but need not specify them as thrown

– Examples:

• ArithmeticException

• BufferOverflowException

Page 195: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The exception hierarchy

Page 196: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Handling exceptions

• Checked exceptions must be either in the method where they are generated, or delegated to the calling method

Page 197: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Keywords

• throws

– A clause in a method declaration that lists exceptions that may be delegated up the call stack

– Example: public int doIt() throws SomeException, …• try

– Precedes a block of code with attached exception handlers

– Exceptions in the try block are handled by the exception handlers

• catch

– A block of code to handle a specific exception

Page 198: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Keywords

• finally

– An optional block which follows catch clauses

– Always executed regardless of whether an exception occurs

• throw

– Launches the exception mechanism explicitly

– Example: throw (SomeException)

Page 199: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

try/catch blocks

• To program exception handling, you must use try/catch blocks

• Code that might produce a given error is enclosed in a try block

• The catch clause must immediately follow the try block

Page 200: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The catch clause

• The clause always has one argument that declares the type of exception to be caught

• The argument must be an object reference for the class

• Throwable or one of its subclasses

• Several catch clauses may follow one try block

Page 201: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The finally clause

• Optional clause that allows cleanup and other operations to occur whether an exception occurs or not

– May have try/finally with no catch clauses

• Executed after any of the following:

– try block completes normally

– catch clause executes

• Even if catch clause includes return

– Unhandled exception is thrown, but before execution returns to calling method

Page 202: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Nested exception handling

• It may be necessary to handle exceptions inside a catch or finally clause

– For example, you may want to log errors to a file, but all I/O operations require IOException to be caught.

• Do this by nesting a try/catch (and optional finally) sequence inside your handler

Page 203: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The throw keyword

• Not to be confused with keyword throws

• Can be used in a try block when you want to deliberately throw an exception

• You can throw a predefined Throwable object or your own exception subtype

• Create a new instance of the exception class to encapsulate the condition

• The flow of the execution stops immediately after the throw statement, and the next statement is not reached

– A finally clause will still be executed if present

Page 204: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Handling runtime exceptions

• What happens when something goes wrong in the JVM?

– It throws an error derived from Error depending on the type of problem

• What happens if RuntimeException is thrown?

– Methods are not forced to declare RuntimeException in their throws clauses; the exception is passed to the JVM

• The JVM does the necessary cleaning and terminates the application or applet

Page 205: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Assertions

• The idea behind assertions is that, at critical points in your program, you can insert a single statement that can check for a required condition and produce a message if the condition does not exist.

• It is of course possible to write your own code without the assertion system. You could, for example, use if/else blocks or even exceptions to do this type of checking. The assertion system, however, offers a more concise syntax.

• During the normal run of a program assertions are turned off, so the checking causes no performance overhead.

Page 206: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Assertions

• To take examples from the real world, you might want to ensure that a person's age is always greater than zero, that the sex of a mother is always female, that the reading of a fuel gauge is not a negative number, or that some reference is not null. These are statements that should always be true. When debugging a program, it might be useful to get the program to ensure that these assumptions are still valid.

• You need to specifically tell the compiler you are using JDK 1.4 mode where assert has a special meaning. This is accomplished by adding the following to the command line:

-source 1.4

Page 207: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Assertions

• Thus, if you were compiling a program called Test.java, the command line would be as follows:

javac -source 1.4 Test.java

• Assertion checking is enabled at runtime via the -enableassertions command-line switch. To confirm that everything you have asserted to be true is true during the run of a program called Test, you would type

java -enableassertions Test

Page 208: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Assertions

• Two forms:

– assert <boolean expression> ;

– assert <boolean expression> : <value expression> ;

• If the boolean expression is false:

– Form 1 throws an AssertionError with no message

– Form 2 throws an AssertionError with a message defined by evaluating the second expression

assert(iMonth<13);

assert (iMonth <13):"The value of iMonth has exceeded 12";

private void methodA(int num) {

assert (num>=0); // throws an AssertionError

// if this test isn't true

useNum(num + x);

}

Page 209: Curso de Programación Java Intermedio

Module 09• Collections

Page 210: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Objectives

• What is a Collection?

• Collections Represent Data Structures

• Specific Kinds of Collections

• The Java Collections Framework

• Interfaces and Implementations

• Algorithms

• Benefits of a Collections Framework

• Interfaces in the Framework

• The Collection Interface

• Collections, Sets and Lists

Page 211: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• The Map Interface

• Comparing Objects

• More on Comparing Objects

• Sorted Collections

• Iterators

• The Iterator Code Pattern

• Interfaces and implementations

• Implementation Choices

• Legacy Collections

• Cloning Collections

• The Collection Class

Page 212: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Objectives

• Understand the basic concepts of collections

• Explore the collection interfaces provided by Java

– Interfaces

– Abstract types

– Concrete implementations• Understand how the ―legacy‖ classes and interfaces fit

in with the more modern classes and interfaces

Page 213: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

What is a Collection?

• A collection is an object that groups multiple elements into a single unit

• Collections typically represent data items that form a natural group such as:

– A poker hand

• A collection of cards

– A mail folder

• A collection of letters

– A telephone directory

• A collection of name-to-phone-number mappings

Page 214: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Collections Represent Data Structures

Page 215: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Specific Kind of Collections

• Set

– Cannot contain duplicate elements

• e.g., employees, library books, processes running on a machine

• List

– Ordered collection, can contain duplicates

• e.g., webpage history, student roster• Map

– Objects that maps keys to values, duplicate keys not allowed

• e.g., dictionary, property sheet

– Not a true collection interface

Arrays are also considered collections,

though they are not part of the

collection framework

Page 216: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The Java Collection Framework

• A Collections Framework is a unified architecture for representing and manipulating collections.

• It is comprised of three things:

– Interfaces

– Implementations

– Algorithms

The Java collections framework is

made up of a set of interfaces and

classes for working with group of

objects

Page 217: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Interfaces and Implementations

• Interfaces – abstract data types representing collections

– Allow collections to be manipulated independently of the details of their representations

– Provide extension points

• New collection types can be added which provide different implementations of the same method

• Implementations – concrete implementations of the collection interfaces

– Reusable data structures

Interfaces: abstract data types representing collections. Implementations: concrete implementations of the collection interfaces.

Page 218: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Algorithms

• Algorithms – methods that perform useful computations on objects that implement collection interfaces

– e.g., searching and sorting

– Reusable functionality via polymorphism

• Same method can be used on many different implementations of the appropriate collections interface

Page 219: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Benefits of a Collections Framework

• Reduces

– Programming effort

– Effort to learn and use new APIs

– Effort to design new APIs• Increases program speed and quality

• Allows interoperability among unrelated APIs

• Encourages software reuse

Page 220: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Interfaces in the Framework

Collection

List Set

SortedSet

Map

SortedMap

Iterator

ListIterator

Enumeration

Comparable

Comparator

Page 221: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The Collection Interface

• Found in the java.util package

• Used to change a collection

and pass them from one

method to another

• For example:

– Add to or remove from

a collection

– Test membership

• Defines methods to

– Facilitate looping

through collections

– Convert collections

to arrays

// Basic Operations

size():int;

isEmpty():boolean;

contains(Object):boolean;

add(Object):boolean; // Optional

remove(Object):boolean; // Optional

iterator():Iterator;

// Bulk Operations

containsAll(Collection):boolean;

addAll(Collection):boolean; // Optional

removeAll(Collection):boolean; // Optional

retainAll(Collecton):boolean; // Optional

clear():void; // Optional

// Array Operations

toArray():Object[];

toArray(Object[]):Object[];

Collection

Page 222: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Collections, Set and Lists

Collection

Set Listvoid add(int index, Object element)

boolean addAll(int index, Collection c)

Object get(int index)

int lastIndexOf(Object o)

ListIterator listIterator(int index)

Object remove(int index)

Object set(int index, Object element)

List subList(int fromIndex, int toIndex)

SortedSet

Page 223: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The Map Interface

• A Map maps keys to values

– Cannot contain duplicate keys• Defines the interface needed to manipulate

such a collection:

– Add/remove a key-value pair

– Given a key, get the value

– Test membership• A map‘s contents can be viewed in one of

three collection views,

– A set of keys

– A collection of values

– A set of key-value mappings

Map

void clear()

boolean containsKey(Object

key)

boolean

containsValue(Object value)

Set entrySet()

boolean equals(Object o)

Object get(Object key)

int hashCode()

boolean isEmpty()

Set keySet()

Object put(Object key)

void putAll(Map t)

Object remove(Object key)

int size()

Collection values()

Page 224: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Comparing Objects

• To sort items in a collection, there must be a way to impose a total ordering on the items

– For any two items in the collection, it must be possible to compare the objects and unambiguously determine whether:

• Object A comes before object B

• Object B comes before object A

• Object A and object B are equal

– There are two ways to order objects

• The Comparable interface

• The Comparator interface

Page 225: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

More on Comparing Objects

• The Comparable Interface

– Implements a class whose objects are capable of comparing other objects to themselves

– Such classes are said to have a natural ordering• The Comparator interface

– Implements a class whose purpose is to compare other objects to each other

– The same two objects may compare differently using different comparators

Comparable

int compareTo(Object o)

Comparator

int compare(Object o1, Object o2)

Page 226: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Sorted Collection

• SortedSet is a Set with an intrinsic (and automatically maintained) order

– Additional methods expose this order• SortedMap is a Map with similar properties, based on key order

• In either case, order may be determined by a natural order or a comparator

Set

SortedSet

Comparator comparator()

Object first()

SortedSet headSet(Object toElement)

Object last()

SortedSet subSet(Object fromElement, Object toElement)

SortedSet tailSet(Object fromElement)

Page 227: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Iterators

• Iterators provide a convenient way

to loop over the entire contents of

a collection one at a time

• ListIterator adds methods that

expose the sequential nature of

the underlying list

• add and remove operations

―pass through‖ to the underlying

collection

• Iterators of sorted collections

iterate through the collection

according to its underlying order

Iterator

boolean hasNext()

Object next()

void remove()

ListIterator

void add(Object o)

boolean hasPrevious()

int nextIndex()

Object previous()

int previousIndex()

void set(Object o)

Page 228: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The Iterator Code Pattern

Collection c;

Iterator i = c.iterator();while (i.hasNext()) {

Object o = i.next();// process this object

}

Page 229: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Interfaces and Implementations

IMPLEMENTATIONS

Hash

Table

Resizable

Array

Balanced

Tree

Linked List Legacy

I

N

T

E

R

F

A

C

E

S

Set HashSet TreeSet

List ArrayList LinkedList Vector,

Stack

Map HashMap TreeMap HashTable,

Properties

Page 230: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Implementation Choices

• Set / Map

– HashSet / HashMap

• Very fast, no ordering

• Choice of initial capacity and load factor important for performance

– TreeSet / TreeMap

• Maintains balanced tree, good for sorted interations

• No tuning parameters

– HashTable

• Synchronized

• Be sure to use Map interface

Page 231: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Implementation Choices

• List

– ArrayList

• Very fast

• Can use native method System.arraycopy

– LinkedList

• Good for volatile collection, or adding to front (e.g., queues)

– Vector

• Synchronized

• Be sure to use List interface

Page 232: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Legacy Collections

• The legacy collection classes are still available, but their implementations have changed

• java.util.Vector

– Extendable, shrinkable, indexed list

• java.util.Stack

– Extends Vector to allow push and pop on a LIFO

• java.util.BitSet

– Expandable set of true/false flags

• java.util.Dictionary

– Abstract class now obsolete and replaced by java.util.Map

• java.util.Hashtable

– Efficient storage of objects with no natural organization

• java.util.Properties

– Stores key-value pairs; the key is the name of a property

Page 233: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Cloning Collections

• You can make a copy of most collections with the clone()method

– This creates a new collection but does not clone the objects stored in the collection (called a shallow copy)

clone()

Collection1

Collection2

Stored

Objects

Page 234: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The Collection Class

• java.util.Collections consists exclusively of static methods that operate on or return collections. It contains:

– Polymorphic algorithms that operate on collections, e.g.,• binarySearch

• copy

• min and max

• replace

• reverse

• rotate

• shuffle

• sort

• Swap

– ―Wrappers‖ – returns a new collection backed by a specified collection

• Synchronized collections

• Unmodifiable collections

Page 235: Curso de Programación Java Intermedio

Module 10• Threads

Page 236: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Objectives

• Introduction

• Thread and Multithreading

• Processes and Threads

• Multitasking and Multithreading

• User Threads

• Daemon Threads

• Life Cycle of Threads

• The Thread Class

• Creating Threads

• Sub-classing from the Thread Class

• Start and Stop

Page 237: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Suspend and Resume

• Sleep

• Yield

• Thread Interrupts

• Other Thread Related Methods

• Thread Related Methods

• Thread Scheduling

• Setting Thread Priority

• Thread Groups

• Grouping of Threads

• Usage of Thread Group

Page 238: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Managing Thread Group Priority

• Useful Thread Group Methods

• Methods invoked on a ThreadGroup objec

• Security Features

• Thread Synchronization

• Thread Racing

• Monitors

• Synchronization Methods

• Object Monitors and Synchronized Methods

• Synchronization and Race Conditions

• Synchronization Statements

Page 239: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Agenda

• Deadlock

• Thread Communication

• Stopping Threads Safely

• Example

Page 240: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Objectives

• Define a thread

• Create separate threads in a Java program, controlling the codeand data that are used by that thread

• Control the execution of a thread and write platformindependent code with threads

• Describe the difficulties that might arise when multiple threadsshare data

• Use wait and notify to communicate between threads

• Use synchronized to protect data from corruption

Page 241: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Introduction

• Threads allow programmers to perform multiple tasks simultaneously

• Some important points about threads are:

– Threads are lightweight component

– Threads have a beginning, sequence of steps to be executed, and an ending

– Threads have specific execution at any time

– Threads are not programs and, hence cannot execute by themselves

– Threads operate at the process level

– Many threads may be run in a single program

Page 242: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Threads and Multithreading

• An application in Java may be single, or multithreaded

• In a single threaded application, the main method that the JVM executes does not span other child threads

• In a multithreaded application, the main method spans other child threads

• These child threads will run in parallel to the thread executing the main method

• Each child thread may be performing a different task

Page 243: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Processes and Threads

• Operating systems like Windows 2000 or OS/2 allow us to run many processes simultaneously

• This is called multitasking

• An operating system can have multiple programs running and within each program there can be multiple threads of control

• Each running instance of a program is a process, while each sequence of control within a program is a thread

• Each process has its own address space

• Threads share the same address space allocated for a program

Page 244: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Multitasking and Multithreading

Page 245: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

User Threads

• Threads created by users (programmers) are called user threads

• User threads execute in the foreground

• The JVM will not exit when a user thread is running

• However, when all user threads have finished, the JVM will terminate all daemon threads, including the garbage collector, and exit

• The main thread is a user thread created and made available by JVM

• This thread is launched in the public static void main(String [ ] args) method

• All other user threads are generated from the main thread

Page 246: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Daemon Threads

• Daemon threads are created to perform tasks like garbage collection and AWT implementation

• They usually execute in the background, and are created in order to serve user threads

• Some user-created threads, can be made to run in the background by calling the setDaemon() method

• To check if a particular thread is a daemon thread or not we can use the isDaemon() method

• Daemon threads expire when the last user-created thread expires

Page 247: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Life Cycles of Threads

Page 248: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

The Thread Class

• The different parameters given to the constructors of the Thread class are:

– public Thread();

– public Thread(Runnable target);

– public Thread(Runnable target, String name);

– public Thread(String name);

– public Thread(ThreadGroup group, Runnable target);

– public Thread(ThreadGroup group, Runnable target, String name);

– public Thread(ThreadGroup group, String name);

Page 249: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Creating Threads

• There are two ways of creating threads:

– Inheriting from the Thread class, and overriding its run() method

– Implementing Runnable interface by providing implementation for only its run() method

• Sub classing from the Thread class of Java creates a thread

• This is possible only if the class that intends running as a thread is not already a subclass of some other class

Page 250: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Sub-Classing from Thread Class

• The given steps show us how to create and use a user-defined thread class in Java:

– Create a class that extends from the Thread class

– Override the run() method in the inherited class, by providing the functionality for the task the thread is created for

– Create an instance of the inherited thread class

– Invoke the start() method on the object of the inherited thread class

– When the start() method is invoked, the run() method of the inherited thread class starts executing

– The thread remains alive as long as the run() method executes

Page 251: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Start and Stop

• When we create a Thread object, as in Thread myThread = new Thread();

• An object of Thread is created in memory

• The thread starts running only when the start() method of Thread is invoked

• Starting and stopping of threads is done using the following methods:

– public void start();

– public final void stop();

– public final void stop(Throwable obj);

– public void destroy();

Page 252: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Suspend and Resume

• To suspend a running thread the suspend() method is used, which makes the thread not runnable

• To resume a suspended thread the resume() method is used

• However, invoking resume() method does not guarantee that the thread will be changed to runnable

• The suspend() and resume() methods are defined as follows:

– public final void suspend();

– public final void resume();

Page 253: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Sleep

• To put a thread to sleep for a specified amount of time we can use the sleep() method

• This makes the thread not runnable for a specified amount of time

• After the elapse of the specified time, the thread becomes runnable again

• Look at the following declarations:

– public static void sleep(long millisecond);

– public static void sleep(long millisecond, int nanosecond);

Page 254: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Yield

• The yield() method of Thread class is used to notify the scheduler in the event of multiple threads running

• The thread that is currently running uses the yield() method to notify the other threads

• These threads may in the runnable state can be scheduled to run public static void yield();

Page 255: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Threads Interrupts

• A sleeping or a waiting thread can be interrupted by calling the interrupt() method

• For instance, t.interrupt() interrupts the Thread object t

• Invoking interrupt() causes an InterruptedException to be thrown on a thread, which is checked by the thread by using the isInterrupted() method

• The isInterrupted() method returns a boolean value indicating whether the thread has been interrupted, without changing the interrupted status of the thread

• Invoking interrupted() method instead clears the interrupted status of the thread

• The interrupted() method also returns a boolean value

Page 256: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Other Related Threads Methods

• The currentThread() method returns a reference to the thread currently running

• The getName() method returns the name assigned to this thread

• The setName() method sets the name of a thread

• The wait() method dictates that the calling thread give up the object monitor, and wait until notified by another thread

• The notify() method is used to wake up a single thread that initially called the wait() method

Page 257: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Other Related Threads Methods

Page 258: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Thread Scheduling

• Threads may be assigned priority so that a higher priority thread may interrupt a running lower priority thread

• The mechanism by which runnable threads are allocated the CPU is called scheduling

• Thread scheduling is done in two ways:

– Preemptive

– Non preemptive

Page 259: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Setting Thread Priority

• To change the priority of threads in a program, we can use the setPriority() method

• We can get the priority of a thread using the getPriority() method

• The priority values are integers ranging from MIN_PRIORITY to MAX_PRIORITY

• If we try to set a priority out of this range then an exception is thrown

• The two methods are defined as follows:

– public final int getPriority();

– public final void setPriority(int newPriority);

Page 260: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Threads Groups

• A set of threads can belong to a thread group in Java

• Every thread belongs to exactly one ThreadGroup instance

• ThreadGroup helps us manage a set of threads belonging to a particular category

• A ThreadGroup can contain both threads as well as other ThreadGroup objects, thus forming a hierarchical tree-like structure

• There is a ThreadGroup that has the main thread, which runs the main() method

Page 261: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Grouping Threads

Page 262: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Usage of Thread Group

ThreadGroup eg = new ThreadGroup("example threads");

Thread t1 = new Thread(eg);

Thread t2 = new Thread(eg);

Thread t3 = new Thread(eg);

t1.start();

t2.start();

t3.start();

if (condition)

eg.destroy();

Page 263: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Managing ThreadGroup Priority

• The maximum priority of a thread group can be changed

• Using the setMaxPriority(), we set the new maximum priority

• The getter method getMaxPriority() returns the current maximum priority of a thread group

• The methods are defined as follows:

– public final int getMaxPriority();

– public final void setMaxPriority(int priority);

Page 264: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Useful ThreadGroup Methods

• We can find the number of threads active in a ThreadGroup by using the activeCount() method

• The activeGroupCount() method returns the number of active groups in the thread group

• To get the list of threads or ThreadGroup objects in the current ThreadGroup we can use the enumerate() method

• This is how enumerate() is declared:

– public int enumerate(Thread list[]);

– public int enumerate(Thread list[], boolean recurse);

– public int enumerate(ThreadGroup list[]);

– public int enumerate(ThreadGroup list[], boolean recurse);

Page 265: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Methods Invoked a ThreadGroup Object

• We can find the number of threads active in a ThreadGroup by using the activeCount() method

• The activeGroupCount() method returns the number of active groups in the thread group

• To get the list of threads or ThreadGroup objects in the current ThreadGroup we can use the enumerate() method

• This is how enumerate() is declared:

– public int enumerate(Thread list[]);

– public int enumerate(Thread list[], boolean recurse);

– public int enumerate(ThreadGroup list[]);

– public int enumerate(ThreadGroup list[], boolean recurse);

Page 266: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Security Features

• Threads and thread groups are critical resources that require security features to protect them

• For a Java application we can set SecurityManager using the

• System.setSecurityManager() method

• The SecurityManager installed by the browser environment protects the applets

• When an applet is running in a browser environment, it is allowed to modify only those threads and thread groups that are created by the current applet

• It cannot modify threads or groups created by other applets

Page 267: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Thread Synchronization

• A critical resource is one that can be used only by one thread at a time

• If more than one thread accesses the critical resource simultaneously, then the resource might end up in an inconsistent state

• The method to ensure that a shared resource is used by only one thread at a time is called synchronization

• Synchronization is the use of code to control the flow of concurrent threads and their access to shared resources

Page 268: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Thread Synchronization

Page 269: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Thread Racing

Page 270: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Monitor

• When an object is accessing a shared resource, no other object can access the resource unless the one currently accessing the resource releases control of the resource

• This is called mutual exclusion

• It is used in the process of synchronization, to ensure exclusive use of resources at a given time

• Monitors are special purpose objects that apply the principle of mutual exclusion to groups of objects

Page 271: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Synchronized Methods

• A synchronized method is one that does not permit access to more than one object at a time

• In Java, the synchronized keyword is used to specify that a method is synchronized

• All objects in Java have a monitor attached to them by default, making synchronization easy in Java

• Synchronized methods use the object's monitor to synchronize access to that object

Page 272: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Synchronized Methods

Page 273: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Object Monitors and Synchronized Methods

Page 274: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Synchronization and Race Conditions

Page 275: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Synchronized Statement

• The following is the syntax for the synchronized statement:

synchronized ( object ) {// Statements to be synchronized}//Here, object is a reference to the object to be //synchronized

• The synchronized block ensures that only after the current thread has successfully entered the object's monitor can it access the method that is a member of the object

Page 276: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Deadlock

Page 277: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Thread Communication

• Java provides a method of handling interthread communication using three methods specially designed for this purpose, viz. the wait(), notify(), and notifyAll() methods

• These methods are implemented as final in the Object class, which means that we cannot provide these methods in any user-defined class

• These three methods are defined inside the Object class as follows:

– final void wait()

– final void notify()

– final void notifyAll()

Page 278: Curso de Programación Java Intermedio

Borrador

www.pro

fesorj

ava.c

om

Stopping Threads Safely

• When the stop() method is called by a particular thread, all the monitors that it is holding are released

• These objects may be in an unstable state when the monitor is released, which can have disastrous ramifications for any other part of our application that tries to use these partially modified objects

• A safer way to do this is to have our thread poll on a Boolean value

• When we want to stop the thread, we toggle the Boolean value and the thread will stop at a safe place in the code