Curso de Programación Java Intermedio
Upcoming SlideShare
Loading in...5
×
 

Curso de Programación Java Intermedio

on

  • 4,624 views

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

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

Statistics

Views

Total Views
4,624
Views on SlideShare
4,557
Embed Views
67

Actions

Likes
2
Downloads
300
Comments
0

9 Embeds 67

http://quimiofisis.blogspot.com.es 26
http://profejavaoramas.blogspot.com 20
http://www.profejavaoramas.blogspot.com 7
http://www.slideshare.net 5
http://quimiofisis.blogspot.com 5
http://www.blogger.com 1
http://www.health.medicbd.com 1
http://quimiofisis.blogspot.gr 1
http://www.linkedin.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

CC Attribution License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Curso de Programación Java Intermedio Curso de Programación Java Intermedio Presentation Transcript

  • PJ-060. Curso de Programación Java Intermedio. www.profesorjava.com www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • 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. www.profesorjava.com Atte. ISC Raúl Oramas Bustillos. rauloramas@profesorjava.com Borrador View slide
  • 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. www.profesorjava.com Modulo 07: Diseño de clases II. Modulo 08: Excepciones y asertos. Borrador View slide
  • CONTENIDO Modulo 09: Colecciones. Modulo 10: Threads. www.profesorjava.com Borrador
  • Module 01 • Java Technology
  • Agenda • Introduction • History of Java • What is Java technology? • Why is Java technology important? • What are the Java components technology components? www.profesorjava.com Borrador
  • Objectives • Describe key features of Java www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • History of Java www.profesorjava.com Borrador
  • 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). www.profesorjava.com Borrador
  • 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. www.profesorjava.com Java bytecode is machine code for the Java Virtual Machine (JVM). Borrador
  • 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 www.profesorjava.com A platform is an environment on which programs can be executed Borrador
  • 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. www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • 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). www.profesorjava.com Borrador
  • What are the Java technology components? • Technologies in Java SE: • Java Foundation Classes (Swing) (JFC) • Java Management Extensions (JMX) • JavaHelp • Java Media Framework (JMF) • Java Native Interface (JNI) • Java Naming and Directory Interface (JNDI • Java Platform Debugger Architecture (JPDA) • Java Secure Socket Extensions (JSSE) • Java 2D API • Java Speech API (JSAPI) • Java Web Start • Java 3D is an API • Certification Path API • Metadata Facility • Java Database Connectivity (JDBC) • Java Content Repository API • Java Advanced Imaging (JAI) • Enumerations • Java Authentication and Authorization Service • Generics (JAAS) • Concurrency Utilities www.profesorjava.com • Java Cryptography Extension (JCE) • Java API for XML Processing (JAXP) • Java Data Objects (JDO) • SOAP with Attachments API for Java Borrador
  • What are the Java technology components? • Technologies in J2EE: • Enterprise JavaBeans (EJB) • J2EE Connector Architecture (JCA) • Portlet Specification • J2EE Management Specification (JMX) • JavaMail • Java Transaction API (JTA) • Java Message Service (JMS) • JavaServer Faces (JSF) • JavaServer Pages (JSP) • Standard Tag Library for JavaServer Pages (JSTL) • Java Servlets www.profesorjava.com Borrador
  • 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) www.profesorjava.com Borrador
  • Module 02 • Object Oriented Programming
  • 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 www.profesorjava.com Borrador
  • Agenda • Source File Layout • The package Statement • The package and import Statement • Packages and visibility www.profesorjava.com Borrador
  • Objectives • Define class, member, attribute, method, constructor, and package • Use the access modifiers private and public as appropriate for the 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com setSomething() Borrador
  • 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 www.profesorjava.com Borrador
  • 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. www.profesorjava.com • Attributes describe the class. Borrador
  • 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>] } www.profesorjava.com Borrador
  • 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; //attributes String monitor; //attribute } www.profesorjava.com Borrador
  • 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} <modifiers><return_type><name>([argument_list]) { something • If the method returns nothing, you use the keyword void as return type www.profesorjava.com Borrador
  • Example Methods and Attributes public class Dog { private int weight; //attribute public int getWeight() { //method return weight; } public void setWeight(int newWeight) { //method weight = newWeight; } } www.profesorjava.com Borrador
  • Example Methods and Attributes public class Cat { private String animalType = “feline”; //default value private String catColor”; //attribute public Cat() { //constructor catColor = “black”; } public Cat(String colorIn) { //overloaded constructor setCatColor(colorIn); } public String getCatColor() { //getter return catColor; } www.profesorjava.com public void setCatColor(String color) { //mutator catColor = color; } } Borrador
  • 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]> } www.profesorjava.com Borrador
  • 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) { www.profesorjava.com weight = newWeight; } } Borrador
  • 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(); www.profesorjava.com Circle obj2 = new Circle(5.6); } } Borrador
  • The Default Constructor • There is always at least one constructor in every class. • If the writer does not supply any constructors, the default constructor 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. www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 Packages refer to a file path – For convenience on your file system. Packages • By convention, package names are in names use dot notation to lower case translate that file path into something the Java platform www.profesorjava.com • Different packages can contain classes with the same name understands Borrador
  • 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"); } www.profesorjava.com public static void main(String[] args) { System.out.println("Inside yourstuff.YourStuffClass"); } } Borrador
  • 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"); } } www.profesorjava.com Borrador
  • 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(); www.profesorjava.com osc.callMe(); } } Borrador
  • 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.*; www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • Packages and visibility • Public access: A class, variable, or method declared public can be used by any class in the program. www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • Module 03 • Identifiers, Keywords and Types
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Comments The three permissible styles of comment in a Java program are: www.profesorjava.com Borrador
  • Semicolons, Blocks and White Space • A statement is one or more lines of code terminated by a semicolon (;): System.out.println( This is part of the same line); a = 0; b = 1; c = 2 • 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: { www.profesorjava.com x = y + 1; y = x + 1; } Borrador
  • 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 class www.profesorjava.com HelloWorld { public static void main (String[] args) { System.out.println(“Hellow World!!”); }} Borrador
  • 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_Identifier a_2nd_Identifier  An-Identifier 2nd_Identifier  Go2 goto $10 10$ www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com class float native super while const for new switch Borrador
  • Primitive Types www.profesorjava.com Borrador
  • Primitive: Integers • Signed whole numbers • Initialized to zero www.profesorjava.com Borrador
  • Primitive: Floating Points • ―General‖ numbers – Can have fractional parts • Initialized to zero www.profesorjava.com Borrador
  • Primitive: Characters • Char is any unsigned Unicode character • Initialized to zero (u0000) www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Primitive Literals • A literal is a value • There are five kinds of literals: Literals integer…………..7 – Integer floating point…7.0f – Floating point boolean……….true – Boolean character……….'A' – Character string………….."A" – String www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com • Upper and lower case are equivalent Borrador
  • 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‘ www.profesorjava.com Borrador
  • 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 0 www.profesorjava.com System.out.println(k); //prints 1 System.out.println(j); //compile error Borrador
  • 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 double f; int a, b; int d; long g; short e; www.profesorjava.com short c; f = g; a = b + c; e = (short)d; g = f; //error Borrador
  • 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 www.profesorjava.com Borrador
  • 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 ); } } 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 b = (byte)s www.profesorjava.com 0 0 0 0 0 0 1 1 Borrador
  • 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. www.profesorjava.com Borrador
  • 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 are initialized 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 www.profesorjava.com Borrador
  • 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); } } www.profesorjava.com Borrador
  • Constructing and Initializing Objects public class ShirtTest { public static void main (String args[]) { int counter = 10; Shirt myShirt = new Shirt(); Shirt yourShirt = new Shirt(); } } www.profesorjava.com Borrador
  • Assigning References public class ShirtTest { public static void main (String args[]) { int counter = 10; Shirt myShirt = new Shirt(); Shirt yourShirt = new Shirt(); } } www.profesorjava.com Borrador
  • Pass by value • In a single Virtual Machine, the Java programming language only passes arguments by value. • If the variable passed is a primitive, only a copy of the variable is actually passed to the method. So modifying the variable within the method has no effect on the actual variable. • When you pass an object variable into a method, a copy of the reference variable is actually passed. In this case, both variables refer to the same object. If the object is modified inside the method, the change is visible in the original variable also. • Though the called method can change the object referred by the variable passed, it cannot change the actual variable in the calling method. In other words, you cannot reassign the original reference variable to some other value. www.profesorjava.com Borrador
  • 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() { www.profesorjava.com return a; } } Borrador
  • 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 www.profesorjava.com the original object reference is never changed. Borrador
  • The this reference • Here are a few uses of the this keyword: – Resolving ambiguity: To reference a member within code that has local variables or arguments with the same name as that member – To pass the current object as a parameter to another method or constructor 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; www.profesorjava.com this.month = date.month; this.year = date.year; } } Borrador
  • Module 04 • Expressions and Flow Control
  • 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 www.profesorjava.com • Branching Statements Borrador
  • Objectives • Distinguish between instance and local variables • Recognize, describe, and use Java software operators • Identify boolean expressions and their requirements in control constructs • Use if, switch, for, while, and do constructions and the labeled forms of break and continue as flow control structures in a program www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Operators • Operators are the ―glue‖ of expressions • Precedence – which operator is evaluated first – is determined explicitly by parentheses or implicitly as follows: www.profesorjava.com Borrador
  • Logical Operators • The boolean operators are: ! – NOT & – AND | – OR ^ – XOR • The short-circuit boolean operators are: && – AND || – OR www.profesorjava.com Borrador
  • Bitwise Logical Operators • The integer bitwise operators are: ~ – Complement & – AND ^ – XOR | – OR • Byte-sized examples: www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Right-Shift Operators >> and >>> www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • Left-Shift Operators << • Left-shift works as follows: 128 << 1 returns 128 * 21 = 256 16 << 2 returns 16 * 22 = 64 www.profesorjava.com Borrador
  • 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); } www.profesorjava.com } else { System.out.println(“x is less than 11”); } Borrador
  • 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 switch (day) { case 0: case 1: rule = “weekend”; if (day == 0 || day == 1) { break; rule = “weekend”; case 2: } else if (day > 1 && day <7) { … rule = “weekday”; case 6: } else { rule = “weekday”; rule = error; www.profesorjava.com break; } default: rule = “error”; } Borrador
  • The Ternary Operator • Shortcut for if-else statement: (<boolean-expr> ? <true-choice> : <false- choice>) • Can result in shorter code – Make sure code is still readable if (x>LIMIT) { warning = “Too Big”; } else { VS. warning = null; } www.profesorjava.com warning = (x>LIMIT) ? “Too Big” : null ; Borrador
  • 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++; www.profesorjava.com System.out.println(x); } while (x < 2); Borrador
  • 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 www.profesorjava.com } for (int index = 0; index < 10; index++) { System.out.println(index); } Borrador
  • 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) { www.profesorjava.com sum += index; index++; } Borrador
  • 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 www.profesorjava.com • Type must match method‘s return type • Return type ―void‖ means no value can be returned Borrador
  • Branching Statements www.profesorjava.com Borrador
  • 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; } www.profesorjava.com Borrador
  • Module 05 • Arrays
  • Agenda • Objectives • Declaring Arrays • Creating Arrays • Initializing Arrays • Multidimensional Arrays • Array Bounds • Array Resizing www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • 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; } www.profesorjava.com Borrador
  • 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; } www.profesorjava.com Borrador
  • 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; } www.profesorjava.com Borrador
  • 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; www.profesorjava.com allCircles[1].location.yValue = 6; allCircles[1].radius = 1.3f; allCircles[1].solid = false; Borrador
  • Multidimensional Arrays • Arrays of arrays: www.profesorjava.com Borrador
  • 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]; www.profesorjava.com Borrador
  • 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); www.profesorjava.com Borrador
  • 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; } www.profesorjava.com Borrador
  • Module 06 • Class Design
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Objectives • Define inheritance, polymorphism, overloading, overriding, and virtual method invocation • Use the access modifiers protected and ―package-friendly‖ • Describe the concepts of constructor and method overloading • Describe the complete object construction and initialization operation • 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 www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • Classes Borrador www.profesorjava.com
  • 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. www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • More on variable modifiers www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • Single Inheritance • When a class inherits from only one class, it is called single inheritance. • Interfaces provide the benefits of multiple inheritance without drawbacks. www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Single Inheritance www.profesorjava.com Borrador
  • Access Control www.profesorjava.com Borrador
  • Access Control www.profesorjava.com Borrador
  • Access Control www.profesorjava.com Borrador
  • Overriding Methods • A subclass can modify behavior inherited from a parent class. • A subclass can create a method with different functionality than the parent‘s method but with the same: – Name – Return type – Argument list www.profesorjava.com Borrador
  • The super keyword • Only constructors within the class being instantiated and within the 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 this and the parameter list • The first line of your constructor can be one of: – super(…); – this(…); www.profesorjava.com Borrador
  • The super keyword www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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()) www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Polymorphism www.profesorjava.com Borrador
  • The instance of Operator public class Employee extends Object public class Manager extends Employee public 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 } } www.profesorjava.com Borrador
  • 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 by the compiler. – The object type is checked at runtime when runtime errors can occur. www.profesorjava.com Borrador
  • Casting Objects www.profesorjava.com Borrador
  • 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 { ... } www.profesorjava.com Borrador
  • The Object Class • Object doesn't have any instance variables but it does have a small number of methods. www.profesorjava.com Borrador
  • The == Operator Compared with the equals method • The == operator determines if two references are identical to each other (that is, refer to the same object). • The equals method determines if objects are ―equal‖ but not necessarily identical. • The Object implementation of the equals method uses the == operator. • User classes can override the equals method to implement a domain-specific test for equality. • Note: You should override the hashCode method if you override the equals method. www.profesorjava.com Borrador
  • 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)); } } www.profesorjava.com Borrador
  • 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 wrapper class‘s toString static method. www.profesorjava.com Borrador
  • 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; } www.profesorjava.com } Borrador
  • 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. www.profesorjava.com Borrador
  • Wrapper Classes www.profesorjava.com Borrador
  • Module 07 • Advanced Class Features
  • 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 www.profesorjava.com Borrador
  • Agenda • Interfaces • Interface Example • Uses of Interfaces • Nested Classes • Properties of Nested Classes • Nested and Inner Classes www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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.” www.profesorjava.com Borrador
  • 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 { www.profesorjava.com public void incrementNumber() { Count1.counter++; } } Borrador
  • Class Attributes • You can invoke static method without any instance of the class to 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; www.profesorjava.com } } Borrador
  • 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()); } } www.profesorjava.com Borrador
  • Static Initializers • A class can contain code in a static block that does not exist within 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"). } } public class TestStaticInit { public static void main(String[] args) { www.profesorjava.com System.out.println("counter = "+ Count4.counter); } } Borrador
  • 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. www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • Abstract Classes www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • 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); www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Abstract Class Example www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • Interface Example www.profesorjava.com Borrador
  • Interface Example www.profesorjava.com Borrador
  • Interface Example www.profesorjava.com Borrador
  • 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 */ } } www.profesorjava.com Borrador
  • Nested Classes • Allow a class definition to be placed inside another class definition • Group classes that logically belong together • Have access to their enclosing class‘s scope class OuterClass { ... class NestedClass { ... } } www.profesorjava.com Borrador
  • Nested Classes www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • Nested Classes www.profesorjava.com Borrador
  • Nested Classes www.profesorjava.com Borrador
  • Nested Classes www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • Module 08 • Exceptions and Assertions
  • 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 www.profesorjava.com Borrador
  • Agenda • The throw keyword • Handling runtime exceptions • Assertions www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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]); www.profesorjava.com i++; } } } Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com • Exceptions terminate execution unless they are handled by the program Borrador
  • 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: www.profesorjava.com • ArithmeticException • BufferOverflowException Borrador
  • The exception hierarchy www.profesorjava.com Borrador
  • Handling exceptions • Checked exceptions must be either in the method where they are generated, or delegated to the calling method www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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) www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com thrown, but before execution returns to calling method Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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. www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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) { www.profesorjava.com assert (num>=0); // throws an AssertionError // if this test isn't true useNum(num + x); } Borrador
  • Module 09 • Collections
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Collections Represent Data Structures www.profesorjava.com Borrador
  • 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 www.profesorjava.com Arrays are also considered collections, though they are not part of the collection framework Borrador
  • 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 www.profesorjava.com made up of a set of interfaces and classes for working with group of objects Borrador
  • 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 www.profesorjava.com representing collections. Implementations: concrete implementations of the collection interfaces. Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Interfaces in the Framework Collection Map List Set SortedMap SortedSet Comparable Iterator Enumeration ListIterator Comparator www.profesorjava.com Borrador
  • The Collection Interface • Found in the java.util package • Used to change a collection and pass them from one Collection method to another // Basic Operations • For example: size():int; isEmpty():boolean; – Add to or remove from contains(Object):boolean; a collection add(Object):boolean; // Optional remove(Object):boolean; // Optional – Test membership iterator():Iterator; • Defines methods to // Bulk Operations – Facilitate looping containsAll(Collection):boolean; addAll(Collection):boolean; // Optional through collections removeAll(Collection):boolean; // Optional – Convert collections retainAll(Collecton):boolean; // Optional clear():void; // Optional to arrays www.profesorjava.com // Array Operations toArray():Object[]; toArray(Object[]):Object[]; Borrador
  • Collections, Set and Lists Collection Set List void add(int index, Object element) boolean addAll(int index, Collection c) Object get(int index) SortedSet int lastIndexOf(Object o) ListIterator listIterator(int index) Object remove(int index) Object set(int index, Object element) List subList(int fromIndex, int toIndex) www.profesorjava.com Borrador
  • The Map Interface Map • A Map maps keys to values void clear() – Cannot contain duplicate keys boolean containsKey(Object • Defines the interface needed to manipulate key) boolean such a collection: containsValue(Object value) – Add/remove a key-value pair Set entrySet() boolean equals(Object o) – Given a key, get the value Object get(Object key) – Test membership int hashCode() • A map‘s contents can be viewed in one of boolean isEmpty() Set keySet() three collection views, Object put(Object key) – A set of keys void putAll(Map t) Object remove(Object key) – A collection of values int size() – A set of key-value mappings Collection values() www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 Comparator int compareTo(Object o) int compare(Object o1, Object o2) www.profesorjava.com Borrador
  • 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) www.profesorjava.com Object last() SortedSet subSet(Object fromElement, Object toElement) SortedSet tailSet(Object fromElement) Borrador
  • Iterators • Iterators provide a convenient way Iterator to loop over the entire contents of boolean hasNext() a collection one at a time Object next() void remove() • ListIterator adds methods that expose the sequential nature of the underlying list ListIterator • add and remove operations void add(Object o) ―pass through‖ to the underlying boolean hasPrevious() int nextIndex() collection Object previous() • Iterators of sorted collections int previousIndex() iterate through the collection void set(Object o) according to its underlying order www.profesorjava.com Borrador
  • The Iterator Code Pattern Collection c; Iterator i = c.iterator(); while (i.hasNext()) { Object o = i.next(); // process this object } www.profesorjava.com Borrador
  • Interfaces and Implementations IMPLEMENTATIONS Hash Resizable Balanced Linked List Legacy Table Array Tree I N Set HashSet TreeSet T E R F A List ArrayList LinkedList Vector, C Stack E S www.profesorjava.com Map HashMap TreeMap HashTable, Properties Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com – Stores key-value pairs; the key is the name of a property Borrador
  • 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) Collection1 Stored Objects clone() Collection2 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Module 10 • Threads
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Agenda • Deadlock • Thread Communication • Stopping Threads Safely • Example www.profesorjava.com Borrador
  • Objectives • Define a thread • Create separate threads in a Java program, controlling the code and data that are used by that thread • Control the execution of a thread and write platform independent code with threads • Describe the difficulties that might arise when multiple threads share data • Use wait and notify to communicate between threads • Use synchronized to protect data from corruption www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Multitasking and Multithreading www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Life Cycles of Threads www.profesorjava.com Borrador
  • 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); www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com executes Borrador
  • 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(); www.profesorjava.com Borrador
  • 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(); www.profesorjava.com Borrador
  • 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); www.profesorjava.com Borrador
  • 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(); www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Other Related Threads Methods www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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); www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Grouping Threads www.profesorjava.com Borrador
  • 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(); www.profesorjava.com Borrador
  • 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); www.profesorjava.com Borrador
  • 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); www.profesorjava.com Borrador
  • 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); www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Thread Synchronization www.profesorjava.com Borrador
  • Thread Racing www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Synchronized Methods www.profesorjava.com Borrador
  • Object Monitors and Synchronized Methods www.profesorjava.com Borrador
  • Synchronization and Race Conditions www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador
  • Deadlock Borrador www.profesorjava.com
  • 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() www.profesorjava.com Borrador
  • 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 www.profesorjava.com Borrador