2. 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
3. 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
4. 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
7. 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
9. 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
10. 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
12. 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
13. 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
14. 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
15. 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
16. 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
17. 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
18. 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
19. 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
20. 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
22. 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
23. Agenda
• Source File Layout
• The package Statement
• The package and import Statement
• Packages and visibility
www.profesorjava.com
Borrador
24. 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
25. 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
26. 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
27. 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
28. 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
29. 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
30. 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
31. 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
32. 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
33. 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
34. 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
35. 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
36. 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
37. 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
38. 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
39. 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
40. 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
41. 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
42. 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
43. 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
44. 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
45. 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
46. 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
47. 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
48. 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
49. 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
50. 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
53. 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
54. 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
56. 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
57. 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
58. 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
59. 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
60. 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
63. Primitive: Floating Points
• ―General‖ numbers
– Can have fractional parts
• Initialized to zero
www.profesorjava.com
Borrador
64. Primitive: Characters
• Char is any unsigned Unicode character
• Initialized to zero (u0000)
www.profesorjava.com
Borrador
65. 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
66. 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
67. 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
68. 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
69. 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
70. 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
71. 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
72. 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
73. 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
74. 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
75. 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
76. 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
77. 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
78. 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
79. 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
80. 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
81. 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
82. 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
84. 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
85. 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
86. 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
87. 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
88. Logical Operators
• The boolean operators are:
! – NOT & – AND
| – OR ^ – XOR
• The short-circuit boolean operators are:
&& – AND || – OR
www.profesorjava.com
Borrador
89. Bitwise Logical Operators
• The integer bitwise operators are:
~ – Complement & – AND
^ – XOR | – OR
• Byte-sized examples:
www.profesorjava.com
Borrador
90. 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
92. 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
94. 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
95. 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
96. 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
97. 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
98. 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
99. 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
100. 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
102. 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
105. 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
106. 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
107. 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
108. 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
109. 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
110. 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
112. 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
113. 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
114. 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
116. 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
117. 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
118. 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
119. 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
120. 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
122. 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
123. 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
124. 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
125. 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
126. 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
127. 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
128. 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
130. 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
131. 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
132. 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
133. 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
134. 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
139. 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
140. 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
142. 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
143. 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
144. 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
146. 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
147. 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
149. 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
150. The Object Class
• Object doesn't have any instance variables but it does have a
small number of methods.
www.profesorjava.com
Borrador
151. 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
152. 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
153. 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
154. 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
155. 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
158. 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
159. Agenda
• Interfaces
• Interface Example
• Uses of Interfaces
• Nested Classes
• Properties of Nested Classes
• Nested and Inner Classes
www.profesorjava.com
Borrador
160. 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
161. 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
162. 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
163. 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
164. 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
165. 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
166. 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
167. 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
169. 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
170. 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
171. 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
173. 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
177. 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
178. 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
180. 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
181. 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
185. 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
186. 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
190. 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
191. 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
192. 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