curso de programación java básico
DESCRIPTION
Curso Básico de Programación Java desarrollado por ISC Raúl Oramas Bustillos. Visita www.profesorjava.comTRANSCRIPT
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
PJ-050. Curso de Programación
Java Básico.
www.profesorjava.com
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
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.
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Acerca de:
En la compilación de esta obra se utilizaron libros conocidos en el ambiente Java, gráficas, esquemas, figuras de sitios de internet, conocimiento adquirido en los cursos oficiales de la tecnología Java. En ningún momento se intenta violar los derechos de autor tomando en cuenta que el conocimiento es universal y por lo tanto se puede desarrollar una idea a partir de otra.
La intención de publicar este material en la red es compartir el esfuerzo realizado y que otras personas puedan usar y tomar como base el material aquí presentado para crear y desarrollar un material mucho más completo que pueda servir para divulgar el conocimiento.
Atte.ISC Raúl Oramas Bustillos.
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
CONTENIDO
Modulo 01: Introducción al lenguaje Java.
Modulo 02: Crear un programa simple en Java.
Modulo 03: Practica de laboratorio 01.
Modulo 04: Declaración e inicialización de variables.
Modulo 05: Práctica de laboratorio 02.
Modulo 06: Crear y utilizar objetos.
Modulo 07: Práctica de laboratorio 03.
Modulo 08: Operadores y estructuras selectivas.
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
CONTENIDO
Modulo 09: Práctica de laboratorio 04.
Modulo 10: Estructuras repetitivas.
Modulo 11: Práctica de laboratorio 05.
Modulo 12: Métodos.
Modulo 13: Práctica de laboratorio 06.
Modulo 14: Encapsulación y constructores.
Modulo 15: Práctica de laboratorio 07.
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
CONTENIDO
Modulo 16: Arreglos.
Modulo 17: Práctica de laboratorio 08.
Modulo 18: Herencia.
Módulo 19: Práctica de laboratorio 09.
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 01Introduction to the Java Programming Language
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• What is Java?• Java Features• The Java evolution• Java Virtual Machine (JVM)• The Java execution model• Uses of Java• Programs • Components
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Describe the history and properties of the Java programming language
• Explain the Java execution model, including the use of bytecode and the Java virtual machine
• Outline the types of programs and components that can be built using Java
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Java is an object-oriented programming language developed by Sun Microsystems
• Java has a set of standardized class libraries that support predefined reusable functionality
• Java has a runtime environment that can be embedded in Web browsers and operating systems
What is Java?
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Java Features
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Object-oriented– Java supports software development using the notion
of objects– Software developed using Java is composed of classes
and objects
Goals of Java
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Network capable– Java supports the development of distributed
applications– Some types of Java applications are designed to be
accessed through a Web browser
Goals of Java
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Robust– Many aspects of Java promote the development of
reliable software• Java uses a pointer model which does not allow
direct access to memory; memory cannot be overwritten
• Secure– Java authentication is based on public-key encryption
methods– Java’s pointer model protects private data in objects
and prevents unauthorized applications from accessing data structures
Goals of Java
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Multi-threaded– Allows your program to run more than one task at the
same time
Goals of Java
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Compiled and interpreted– Source code is compiled into machine code for the
Java virtual machine (JVM) by the Java compiler– Machine code for the JVM is also known as bytecode– Interpreter of the Java virtual machine interprets and
executes instructions• Architecture neutral
– Bytecode instructions are architecture neutral because they run on the JVM, and are not specific to an architecture
– The same application runs on all platforms, provided the Java virtual machine is installed on that platform
Goals of Java
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Portable at source and binary level– One piece of source code gets compiled into one set of
bytecode instructions for the JVM, and can be run on any platform and architecture without recompiling the code
Goals of Java
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Java is a relatively young language– It has been in use since 1995– It was originally designed for consumer electronic
devices• Java has a huge developer base
– There is a vast collection of libraries (from Sun and other sources)
The Java evolution
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• A platform is a development or deployment environment• The Java platform runs on any operating system
– Other platforms are hardware and vendor specific
• The Java platform provides:– The Java virtual machine (JVM)– Application Programming Interface (API)
The Java platform
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Java Virtual Machine (JVM)
A virtual machine is an executable that represents a genericprocessor on which Java’s bytecodes run
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Java can be used to build programs and software components• Programs are stand-alone entities that can run on the Java Virtual Machine
– Applications– Applets
• Components are building blocks used to create programs
– Servlets– JavaServer Pages (JSPs)– JavaBeans– Enterprise JavaBeans (EJBs)
Uses of Java
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Application– A stand-alone program that can access system
resources such as files– Does not need to run in a Web browser– Is explicitly invoked through the command line or
menu selection– The method main() is the entry point for an application
Programs
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Applet– A Java program that is embedded within a Web page;
almost always graphical– Security limits access to system resources– Code executes on the client inside a Web browser
Programs
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Servlet– Handles requests from the Web browser and returns
responses– Creates dynamic content on the server– Runs inside an application server
• JavaServer Page (JSP)– HTML page embedded with Java code– Creates dynamic content on the server instead of on
the browser– Runs inside an application server
Components
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• JavaBeans– Java code that has its properties, methods, and events
exposed to promote reuse among developers– Reusable software component that can be
manipulated visually in a builder tool
Components
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Enterprise JavaBeans (EJB)– Distributed objects that allow communication between
Java objects in different JVMs– Encapsulate the business logic and model of an
application– Run inside an application server
Components
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 02Developing and Testing a
Java Program
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Identifying the Components of a Class• Structuring Classes• Class Declaration• Variable Declarations and Assignments• Comments• Methods• Creating and Using a Test Class• The main method• Compiling and Executing (Testing) a Program• Executing (Testing) a Program• Debugging Tips
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Identify the four components of a class in the Java programming language
• Use the main method in a test class to run a Java program from the command line
• Compile and execute a Java program
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Classes are the blueprints that you create to define the objects in a program.
Identifying the Components of a Class
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• The class declaration• Attribute variable declarations and initialization (optional)• Methods (optional)• Comments (optional)
//Employee.javapublic class Employee { private String id; private String lastName; public int getId() {…} public void setId() {…} }
Attributes
Methods
Class declaration
Comments
Structuring Classes
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
//Piano.javapublic class Piano {
private int keys = 88;
//this method displays the number of keys of piano public void displayPianoInformation() {
System.out.println(" A piano has " + keys + " keys.");
} //end of display method
} //end of class
It’s a class The name of the class
The class body begin’s here
The class body end’s here
Structuring Classes
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Syntax:[modifier] class class_identifier
• Example:public class Pianopublic class Catpublic class Shirt
Class Declaration
//Piano.javapublic class Shirt {
//write your code here
} //end of class
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Class Declaration
public class Shirt {
public int shirtID = 0; // Default ID for the shirt public String description = "-description required-"; // default // The color codes are R=Red, B=Blue, G=Green, U=Unset public char colorCode = ‘U’; public double price = 0.0; // Default price for all shirts public int quantityInStock = 0; // Default quantity for all shirts
// This method displays the values for an item 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);
} // end of display method
} // end of class
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public int shirtID = 0; // Default ID for the shirtpublic String description = "-description required-"; // default// The color codes are R=Red, B=Blue, G=Green, U=Unsetpublic char colorCode = 'U';public double price = 0.0; // Default price for all shirtspublic int quantityInStock = 0; // Default quantity for all shirts
Shirt id
Description
Color Code
Price
Quantity in stock
Variable Declarations and Assignments
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Comments
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Syntax:[modifiers] return_type method_identifier([arguments])
{ method_code_block}• Example: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);} // end of display method
Methods
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Classes in Java may have methods and attributes.
• Methods define actions that a class can perform.
• Attributes describe the class.
Methods
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Example:
public class ShirtTest { public static void main (String args[]) { Shirt myShirt; myShirt = new Shirt(); myShirt.displayShirtInformation(); }}
public class Shirt { … public void displayShirtInformation() { … }}
Shirt.java
ShirtTest.java
Testing and Using a Test Class
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Syntax:
public static void main (String args[])
• The main() method is the normal entry point for Java applications
• To create an application, you write a class definition that includes a main() method
The main method
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• This is the definition of the class OurFirstProgram. The class definition only
contains the method main
• This is the definition of the method main()• The keyword public indicates it is globally accesible • The keyword static ensures it is accesible even though no objects of
the class exist• The keyword void indicates it does not return value
public class OurFirstProgram { public static void main (String args[]) { System.out.println("Rome wasn’t burned in a day!"); }}
The main method
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Compiling and Executing (Testing) a Program
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Go the directory where the source code files are stored.2. Enter the following command for each .java file you want
to compile.
• Syntax:javac filename
• Example:javac Shirt.java
Compiling and Executing (Testing) a Program
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Go the directory where the class files are stored.2. Enter the following for the class file that contains the
main method.
• Syntax
java classname
• Example
java ShirtTest
Executing (Testing) a Program
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Check line referenced in error message• Check for semicolons• Check for even number of braces
Debugging Tips
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 03Writing, Compiling, and
Testing a Basic Program Lab
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Lab Exercise 1• Lab Exercise 2• Lab Exercise 3
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Become familiar with the structure and parts of a basic Java Program.
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Create a new public class, HelloWorld, with a main method. The main method should output the string “Hello, World!”.
2. Enter the following source code:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); }}
3. Compile and run the source code.
Lab Exercise 1
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Create a new public class,Quotation.2. Enter the following source code:
public class Quotation { String quote = "Welcome to Sun!";
public void display() { System.out.println(quote); }
}
3. Create a new class QuotationTest , with a main method.
Lab Exercise 2 (1 of 2)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
4. Enter the following source code:
public class QuotationTest {public class HelloWorld { public static void main(String[] args) { Quotation obj = new Quotation(); obj.display(); }}
5. Compile and execute the source code.
Lab Exercise 2 (2 of 2)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Create a new class Car with the following methods: – public void start() – public void stop() – public int drive(int howlong) – The method drive() has to return the total distance
driven by the car for the specified time. Use the following formula to calculate the distance:
distance = howlong*60;
2. Write another class CarOwner and that creates an instance of the object Car and call its methods. The result of each method call has to be printed using System.out.println().
Lab Exercise 3
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 04Declaring, Initializing, and
Using Variables
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Identifying Variable Use and Syntax• Uses for variables• Variable Declaration and Initialization• Describing Primitive Data Types• Integral Primitive Types• Floating Primitive Types• Textual Primitive Types• Logical Primitive Types• Naming a Variable• Assigning a Value to a Variable• Declaring and Initializing Several Variables in One Line
of Code• Additional Ways to Declare Variables and Assign Values to Variables
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Constants• Storing Primitive and Constants in Memory• Standard Mathematical Operators• Increment and Decrement Operators (++ and --)• Operator Precedence• Using Parenthesis• Casting Primitive Types• Implicit versus explicit casting• Examples (Casting)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Identify the uses for variables and define the syntax for a variable
• List the eight Java programming language primitive data types
• Declare, initialize, and use variables and constants according to Java programming language guidelines and coding standards
• Modify variable values using operators• Use promotion and type casting
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class PianoKeys { public static void main(String[] args) { int keys = 88; System.out.println("A piano has " + keys + " keys."); }}
Identifying Variable Use and Syntax
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class Geometry { public static void main(String[] args) { int sides = 7; // declaration with initialization System.out.println("A heptagon has " + sides + " sides."); sides = 10; // assignment statement System.out.println("A decagon has " + sides + " sides."); sides = 12; System.out.println("A dodecagon has " + sides + " sides."); }}
Identifying Variable Use and Syntax
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class Circle { public double radio;
public Circle(double r) { int tmp = 0; radio = r; }}
Identifying Variable Use and Syntax
• Instance variables of a class are initialized with default values for the particular
datatype• Local variables are never given a default value, they have to be
explicitily initialized before use
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Holding unique data for an object instance• Assigning the value of one variable to another• Representing values within a mathematical expression• Printing the values to the screen• Holding references to other objects
Uses for variables
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Syntax (attribute or instance variables):
[modifiers] type identifier = value;
• Syntax (local variables):
type identifier;
• Syntax (local variables)
type identifier = value;
Variable Declaration and Initialization
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Integral types (byte, short, int, and long)• Floating point types (float and double)• Textual type (char)• Logical type (boolean)
Describing Primitive Data Types
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Signed whole numbers• Initialized to zero
Integral Primitive Types
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class IntegralType { public static void main( String args[] ) { byte age = 12; short idCourse = 1230; int javaProgrammers = 2300000; long worldPeople = 5000000000L; System.out.println(worldPeople); }}
Integral Primitive Types
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• “General” numbers (can have fractional parts)• Initialized to zero
Floating Primitive Types
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class Tax { public static void main( String args[] ) { double price = 20; float tax = 0.15f; double total;
total = price * tax; System.out.println( total ); } }
Floating Primitive Types
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Any unsigned Unicode character is a char primitive data type
• A character is a single Unicode character between two single quotes
• Initialized to zero (\u0000)
Textual Primitive Types
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class PrintChar { public static void main( String args[] ) { char c = 'x'; int i = c; System.out.println( "Print: " + c ); System.out.println( "Print: " + i ); c = 88; System.out.println( "Print: " + c ); }}
Textual Primitive Types
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• boolean values are distinct in Java• An int value can NOT be used in place of a boolean• A boolean can store either true or false• Initialized to false
Logical Primitive Types
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class CatDog { public static void main( String args[] ) { boolean personWithDog = true; boolean personWithCat = false; System.out.println( "personWithDog is " + personWithDog ); System.out.println( "personWithCat is " + personWithCat );
} }
Logical Primitive Types
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Rules:– Variable identifiers must start with either an uppercase or lowercase letter, an underscore (_), or a dollar sign ($).– Variable identifiers cannot contain punctuation, spaces, or dashes.– Java keywords cannot be used.
• Guidelines:– Begin each variable with a lowercase letter; subsequent words should be capitalized, such as myVariable.– Chose names that are mnemonic and that indicate to the casual observer the intent of the variable.
Naming a Variable
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Example:
double price = 12.99;
• Example (boolean):
boolean isOpen = false;
Assigning a Value to a Variable
You can assign a primitive variable using a literal or the result of an expression. The result of an expression involving integers (int, short or byte) is always at least of type int.
A boolean cannot be assigned any type other than boolean.
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Syntax:
type identifier = value [, identifier = value];
• Example:
double price = 0.0, wholesalePrice = 0.0;
int miles = 0, //One mile is 8 furlong furlong = 0, //One furlong is 220 yards yards = 0, //One yard is 3 feet feet = 0;
Declaring and Initializing Several Variables in One Line of Code
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Assigning literal values:
int ID = 0;float pi = 3.14F;char myChar = ’G’;boolean isOpen = false;
• Assigning the value of one variable to another variable:
int ID = 0;int saleID = ID;
Additional Ways to Declare Variables and Assign Values to Variables
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Assigning the result of an expression to integral, floating point, or Boolean variables
float numberOrdered = 908.5F;float casePrice = 19.99F;float price = (casePrice * numberOrdered);int hour = 12;boolean isOpen = (hour > 8);
• Assigning the return value of a method call to a variable
Additional Ways to Declare Variables and Assign Values to Variables
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Variable (can change):
double salesTax = 6.25;
• Constant (cannot change):
final double SALES_TAX = 6.25;final int FEET_PER_YARD = 3;final double MM_PER_INCH = 25.4;
• A final variable may not modified once it has been assigned a value.
• Guideline – Constants should be capitalized with words separated by an underscore (_).
Constants
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Storing Primitive and Constants in Memory
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Standard Mathematical Operators
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Standard Mathematical Operators
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Increment and Decrement Operators (++ and --)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Increment and Decrement Operators (++ and --)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Initial value of x
Expression Final value of y
Final value of x
5 y = ++x 6 6
5 y = x++ 6 5
5 y = --x 4 4
5 y = x-- 4 5
Increment and Decrement Operators (++ and --)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Rules of precedence:1. Operators within a pair of parentheses2. Increment and decrement operators3. Multiplication and division operators, evaluated from
left to right4. Addition and subtraction operators, evaluated from
left to right
• Example of need for rules of precedence (is the answer 34 or 9?):
c = 25 - 5 * 4 / 2 - 10 + 4;
Operator Precedence
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Operator Precedence
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Examples:
c = (((25 - 5) * 4) / (2 - 10)) + 4;c = ((20 * 4) / (2 - 10)) + 4;c = (80 / (2 - 10)) + 4;c = (80 / -8) + 4;c = -10 + 4;c = -6;
Using Parenthesis
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• 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• Casting a value allows it to be treated as another type• The JVM can implicitly promote from a narrower type to a
wider type• To change to a narrower type, you must cast explicitly
Casting Primitive Types
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Casting is automatically done when no loss of information is possible
• An explicit cast is required when there is a "potential" loss of accuracy
Implicit versus explicit casting
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
byte b = 3;int x = b;
byte a;int b = 3;a = (byte)b;
int num1 = 53; // 32 bits of memory to hold the valueint num2 = 47; // 32 bits of memory to hold the valuebyte num3; // 8 bits of memory reservednum3 = (num1 + num2); // causes compiler error
Examples (Casting)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
int num1 = 53; // 32 bits of memory to hold the valueint num2 = 47; // 32 bits of memory to hold the valuebyte num3; // 8 bits of memory reservednum3 = (byte)(num1 + num2); // no data loss
Examples (Casting)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
short s = 259;byte b = s; // Compiler errorSystem.out.println(“s = ” + s + “, b = ” + b);
short s = 259;byte b = (byte)s; // Explicit castSystem.out.println(“s = ” + s + “, b = ” + b);
1100000010000000
11000000
b = (byte)s
Examples (Casting)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class ExplicitCasting { public static void main( String args[] ) {
byte b; int i = 266; //0000000100001010 b = (byte)i; // 00001010
System.out.println("byte to int is " + b ); } }
Examples (Casting)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 05Using Primitive Types, Operators and Type Casting, in a Program
Lab
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Lab Exercise 1• Lab Exercise 2• Lab Exercise 3
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Write the code to declare, assign values to, and use variables in a program
• Practice using operators and type-casting
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Create a class called Rectangle.java, define a variable called length of type int and define another variable called width of type int.
2. Assign length equals to 10 and width equals to 2. 3. In the main method create an instance of the Rectangle
object. Define a variable called area of type int, compute and print the area of the rectangle.
public class Rectangle { int width = 2; int length = 10;
public static void main(String[] args) { Rectangle rectangle = new Rectangle(); int area = rectangle.length * rectangle.width; System.out.println("Area : " + area); }}
4. Compile an run the program.
Lab Exercise 1
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Write a program to create a class called Calculator that uses arithmetic operators. Initialize the variables to any acceptable value of your choice, and demonstrate the usage of these operators.
• Useful Tips:– Create a class called Calculator.– Declare two integer variables, and initialize them to
two integer values (e.g. 10 and 5).– Add these two variables, and print the result to the
standard output.– Subtract the second variable from the first, and print
the result to the standard output.– Multiply these two variables, and print the result to the
standard output.– Divide the first variable by the second variable, and
print the result to the standard output.
Lab Exercise 2
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Write a program called Temperature containing a temperature in Fahrenheit and a method called calculateCelsius. Follow these steps to create a Temperature class:
1. Write a calculateCelsius method that converts a Fahrenheit value to a Celsius value and prints the Celsius value.
2. Use the following information to convert Farenheit values to Celsius values: (To convert from Fahrenheit to Celsius, subtract 32, multiply by 5, and divide by 9.)
3. Test the program using the TemperatureTest class.
Lab Exercise 3
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 06Creating and Using
Objects
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Introduction• Declaring Object References, Instantiating Objects,
and Initializing Object References• Declaring Object Reference Variables• Instantiating an Object• Initializing Object Reference Variables• Using an Object Reference Variable to Manipulate
Data• Storing Object Reference Variables in Memory• Assigning an Object Reference From One Variable to
Another• Strings• Concatenating Strings• Comparing Strings• String Messages• StringBuffer
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Declare, instantiate, and initialize object reference variables
• Compare how object reference variables are stored in relation to primitive variables
• Use a class (the String class) included in the Java SDK
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Introduction
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
The phrase "to create an instance of an object“ means to create a copy of this object in the computer's memoryaccording to the definition of its class.
Introduction
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Class Object (Instance)
Introduction
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
A primitive variable holds the value of the data item, while a reference variable holds thememory address where the data item (object) is stored.
Declaring Object References, Instantiating Objects, and Initializing Object References
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class ShirtTest { public static void main (String args[]) { Shirt myShirt = new Shirt(); myShirt.displayShirtInformation(); }}
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); }}
Declaring Object References, Instantiating Objects, and Initializing Object References
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Syntax:
Classname identifier;
• Example:
Shirt myShirt;Circle x;Cat gardfiel;
Declaring Object Reference Variables
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Syntax:
new Classname();
Instantiating an Object
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
The assignment operator
• Examples:myShirt = new Shirt();
Initializing Object Reference Variables
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class ShirtTest2 { public static void main (String args[]) { Shirt myShirt; myShirt = new Shirt(); myShirt.size = ‘L’; myShirt.price = 29.99F; myShirt.longSleeved = true; myShirt.displayShirtInformation(); }}
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); }}
1. Declare a reference.2. Create the object.3. Assign values.
Using an Object Reference Variable to Manipulate Data
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class ShirtTestTwo { public static void main (String args[]) { Shirt myShirt = new Shirt(); Shirt yourShirt = new Shirt();
myShirt.displayShirtInformation(); yourShirt.displayShirtInformation(); myShirt.colorCode=’R’; yourShirt.colorCode=’G’;
myShirt.displayShirtInformation(); yourShirt.displayShirtInformation(); } }
Using an Object Reference Variable to Manipulate Data
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class Circle { private int radius; }
public class ShapeTester { public static void main(String args[]) { Circle x; x = new Circle(); System.out.println(x); } }
Using an Object Reference Variable to Manipulate Data
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class Circle { private int radius; }
public class ShapeTester { public static void main(String args[]) { Circle x; Rectangle y; x = new Circle(); y = new Rectangle(); System.out.println(x + " " + y); } }
public class Rectangle { public double width = 10.128; public double height = 5.734; }
Using an Object Reference Variable to Manipulate Data
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public static void main (String args[]) { int counter; counter = 10; Shirt myShirt = new Shirt(); Shirt yourShirt = new Shirt();}
Storing Object Reference Variables in Memory
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1 Shirt myShirt = new Shirt();2 Shirt yourShirt = new Shirt();3 myShirt = yourShirt;
Assigning an Object Reference From One Variable to Another
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class Cat { … …} Cat A = new Cat();
Cat B = A;
Assigning an Object Reference From One Variable to Another
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Assigning an Object Reference From One Variable to Another
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Any number of characters between double quotes is a String:
• String can be initialized in other ways:
Strings
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Strings are objects. These objects are inmmutable. Their value, once assigned, can never be changed. For instance:
String msg = “Hello”;mgs += “ World”;
• Here the original String “Hello” is not changed. Instead, a new String is created with the value “Hello World” and assigned to the variable msg.
Strings
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• The + operator concatenates Strings:
String a = “This” + “ is a ” + “String”;
• Primitive types used in a call to println are automatically converted to Strings
System.out.println("answer = " + 1 + 2 + 3); System.out.println("answer = " + (1+2+3));
If one of the operands is a String and the other not, the Java code tries to convert the other operand to a String representation.
Concatenating Strings
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• oneString.equals(anotherString)– Tests for equivalence– Returns true or false
• oneString.equalsIgnoreCase(anotherString)– Case insensitive test for equivalence– Returns true or false
• oneString == anotherString is problematic
String name = "Joe";if("Joe". equals(name)) name += " Smith";
boolean same = "Joe".equalsIgnoreCase("joe");
Comparing Strings
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Strings are objects; objects respond to messages– Use the dot (.) operator to send a message– String is a class
String name = “Johny Flowers”;name.toLowerCase(); //”johny flowers”name.toUpperCase(); //”JOHNY FLOWERS”“ Johny Flowers ”.trim(); //”Johny Flowers”“Johny Flowers”.indexOf(‘h’); //2“Johny Flowers”.lenght(); //13“Johny Flowers”.charAt(2); //’h’“Johny Flowers”.substring(5); //Flowers“Johny Flowers”.substring(6,8); //”fl”
String Messages
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• StringBuffer is a more efficient mechanism for building strings– String concatenation
• Can get very expensive• Is converted by most compilers into a StringBuffer implementation
– If building a simple String, just concatenate – If building a String through a loop, use a StringBuffer
StringBuffer buffer = new StringBuffer(15);buffer.append(“This is”);buffer.append(“String”);buffer.insert(7,“a”);buffer.append(“.”);System.out.println(buffer.length()); //17String output = buffer.toString();System.out.println(output); //”This is a String”
StringBuffer
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 07Objects and Strings Lab
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Lab Exercise 1
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Create instances of a class and manipulate these instances in several ways.
• Make use of the String class and its methods
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Create a class called BankAccount.2. Enter the following code:
public class BankAccount { // these are the instance variables private int balance; private int accountNumber; private String accountName; // this is the constructor public BankAccount(int num, String name) { balance = 0; accountNumber = num; accountName = name; }
Lab Exercise 1 (1 of 5)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
// the code for the methods starts here public int getBalance() { return balance;} public void credit(int amount)
{balance=balance+amount; } public void debit(int amount) {balance = balance -
amount;} public String toString() { return ("#######################\n" + "Account
number: “ + accountNumber + "\nAccount name: " + accountName + "\nBalance: $" + balance + "\n#######################"); }}
Lab Exercise 1 (2 of 5)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
3. Create a BankAccount in another Test program (BankTest). The instance is named savings. For example:
BankAccount savings = new BankAccount(121,"John Doe");
4. Create another BankAccount instance named cheque. For example:
BankAccount cheque = new BankAccount(122,"John Perez");
Lab Exercise 1 (3 of 5)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
5. Call methods of the objects and see what effect they have.
savings.credit(1000); System.out.println(savings);
cheque.credit(500); System.out.println(cheque);
cheque.credit(1500); System.out.println(cheque);
cheque.debit(200); System.out.println(cheque);
Lab Exercise 1 (4 of 5)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
6. Assign one object reference to another object reference by assigning savings to a new instance named myAccount
BankAccount myAccount;myAccount = cheque;System.out.println(myAccount);
7. Make sure that you understand what is happening here!
Lab Exercise 1 (5 of 5)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 08Using Operators and Decision Constructs
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Using Relational and Conditional Operators• Creating if and if/else Constructs• Using the switch Construct
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Identify relational and conditional operators• Examine if and if/else constructs• Use the switch constructs
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Using Relational and Conditional Operators
The Java language provides several means of altering the sequential flow of a program
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Relational operators are used for comparing two values stored in a variable.
Relational operators
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Usually conditional operators are used in combination with relational operators to determine if a condition is true of false
• These operators require two operators. Hence they are called binary operators
Conditional operators
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• An if construct lets you perform certain statements if a condition is true
• Syntax:
if (boolean_expression) { code_block;} // end of if construct// program continues here
The if Construct
We cannot use numerica values to represent true and false as we do in C/C++
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class Coffee { private static int hour=9; public static void main(String args[]) { if(hour>=8 && hour<12) { System.out.println(“Drink coffee”);
} }}
The if Construct
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Syntax:
if (boolean_expression) { code_block;} // end of if constructelse { code_block;} // end of else construct// program continues here
• The curly braces are optional if the body is limited to a single statement.
• We cannot use numeric values to represent true and false
if(x==5) {} // compiles, executes body id x is equals to 5if(x=0) {} // does not compilesif(x=true) {} // compile
The if/else Construct
The else part in the if/else statement is optional. The curly braces are optional if the body is limited to a single statement
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class CoffeeIfElse { private static int hour=9; public static void main(String args[]) {
if(hour>=8 && hour<12) { System.out.println(“Drink coffee”); } else { System.out.println(“Drink tea”); } //continue here }}
The if/else Construct
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class IfElseDemo { public static void main(String[] args) {
int testscore = 76; char grade;
if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); }}
The if/else Construct
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Tests a single variable for several alternative values and executes the corresponding case• Any case without break will “fall through”
– Next case will also be executed• default clause handles values not explicitly handled by a case
Using the switch Construct
switch (day) { case 0: case 1: rule = “weekend”; break; case 2: … case 6: rule = “weekday”; break; default: rule = “error”;}
if (day == 0 || day == 1) { rule = “weekend”;} else if (day > 1 && day <7) { rule = “weekday”;} else { rule = error;}
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• The argument passed to the switch and case statements should be int, short, char, or byte.• Syntax:
switch (variable) {case literal_value:
code_block;[break;]
case another_literal_value:code_block;[break;]
[default:]code_block;
}
• Note that the control comes to the default statement only if none of the cases match.
Using the switch Construct
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class SwitchDemo { public static void main(String[] args) { int month = 8; switch (month) { case 1:System.out.println("January");break; case 2:System.out.println("February");break; case 3:System.out.println("March");break; case 4:System.out.println("April");break; case 5:System.out.println("May");break; case 6:System.out.println("June");break; case 7:System.out.println("July");break; case 8:System.out.println("August");break; case 9:System.out.println("September");break; case 10:System.out.println("October");break; case 11:System.out.println("November");break; case 12:System.out.println("December");break; default:System.out.println("Invalid month.");break; } }}
Using the switch Construct
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 09if/switch Lab
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Lab Exercise 1• Lab Exercise 2• Lab Exercise 3
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Create classes that use if and if/else constructs.• Using the switch construct in decision-making
programs
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Write a program called Division that does the following:1. Takes three command-line arguments2. Divides the third number by the first and prints the
result3. Divides the third number by the second and prints
the result4. Checks to be sure the first and the second
numbers are not equal to zero.
Lab Exercise 1
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Create a class called DayOfWeek with one variable that can only contain a value from 1 to 7. Where:
– The number 1 represents Monday (beginning of the week).
– The number 7 represents Sunday (end of the week).
2. In the DayOfWeek class, create a displayDay method that uses if/else constructs to inspect the value of the number of days and displays the corresponding day of the week. The displayDay method should also display an error message if an invalid number is used.
3.
Lab Exercise 2
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Create a class called DayOfWeek02 with one variable containing a value from 1 to 7, where:
– The number 1 represents Monday (beginning of the week).
– The number 7 represents Sunday (end of the week).
2. In the DayOfWeek02 class, create a displayDay method that uses a switch construct to inspect the value for the number of days and displays the corresponding day of the week. The displayDay method should also display an error message if an invalid number is used.
Lab Exercise 3
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 10Using Loop Constructs
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Creating while loops• Nested while loops• Developing a for loop• Nested for loops• Coding a do/while loop• Nested do/while loops• Comparing loop constructs
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Create while loops• Develop for loops• Create do/while loops
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• The while loop is used to perform a set of operations repeateadly till some condition is satisfied, or to perform a set of operations infinitely• Syntax:
while(boolean_expression) { code_block;} // end of while construct// program continues here
Creating while loops
The body of the while loop is executed only if the expression is true
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class WhileCountDown { public static void main(String args[]) { int count = 10; while(count>=0) { System.out.println(count); count--; } System.out.println(“Blast Off.”); }}
Creating while loops
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class WhileRectangle { public int height = 3; public int width = 10; public void displayRectangle() { int colCount = 0; int rowCount = 0; while (rowCount < height) {
colCount=0; while (colCount < width) { System.out.print(“@”);
colCount++;}
System.out.println(); rowCount++; }
}}
Nested while loops
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• The for loop is used to perform a set of operations repeatdly until some condition is satisfied, or to perform a set of operations infinitely
• Syntax:
for (initialize[,initialize]; boolean_expression; update[,update]) {code_block;
}
Developing a for loop
There can be more than one initialization expression and more than one iteration expression, but only one test expression
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class ForLoop {
public static void main(String[] args) { int limit = 20; // Sum from 1 to this value int sum = 0; // Accumulate sum in this variable // Loop from 1 to the value of limit, adding 1 each cycle for(int i = 1; i <= limit; i++) { sum += i; // Add the current value of i to sum } System.out.println(“sum = “ + sum); }}
Developing a for loop
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class ForRectangle { public int height = 3; public int width = 10;
public void displayRectangle() { for (int rowCount = 0; rowCount < height; rowCount++) { for (int colCount = 0; colCount < width; colCount++){ System.out.print(“@”);
}System.out.println();
} }}
Nested for loops
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• The do-while loop is used to perform a set of operations repeatedly until some condition is satisfied, or to perform a set of operations infinitely• Syntax:
do { code_block;}while(boolean_expression);// Semicolon is // mandatory.
Coding a do/while loop
The body of the do/while is executed at least once because the test expression is evaluated only after executing the loop body.
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class DoWhileRectangle { public int height = 3; public int width = 10; public void displayRectangle() { int rowCount = 0; int colCount = 0; do {
colCount = 0; do { System.out.print(“@”);
colCount++; }while (colCount < width); System.out.println(); rowCount++; }while (rowCount < height); }}
Nested do/while loops
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Use the while loop to iterate indefinitely through statements and to perform the statements zero or more times.• Use the do/while loop to iterate indefinitely through statements and to perform the statements one or more times.• Use the for loop to step through statements a predefined number of times.
Comparing loop constructs
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 11Loops Constructs Lab
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Lab Exercise 1• Lab Exercise 2• Lab Exercise 3
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Write classes that use while loops. • Write classes that use for loops.• Write classes that use do/while loops.
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Write a class called Counter that contains a method called displayCount that:
– Counts from 1 to MAX_COUNT, where MAX_COUNT is a variable that you must declare and initilize to any number by using a while loop
– Displays the count
2. Compile your program.3. Use the CounterTest.class file to test your program.
Lab Exercise 1
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Write a class called CounterTwo that contains a method called displayCount that:
– Counts from 1 to the value of the MAX_COUNT constant, where the MAX_COUNT constant is a variable that you must declare and initilize to any number, using a for loop.
– Displays the count
2. Compile your program.3. Use the CounterTwoTest.class file to test your program.
Lab Exercise 2
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Write a class called CounterThree containing a method called displayCount that:
– Counts from 1 to the value of the MAX_COUNT constant, where the MAX_COUNT constant is a variable that you must declare and initilize to any number, using a do/while loop
– Displays the count
2. Compile your program.3. Use the CounterThreeTest.class file to test your program.
Lab Exercise 3
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 12Developing and Using
Methods
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Introduction• Creating and Invoking Methods• Invoking a Method From a Different Class• Calling and Worker Methods• Invoking a Method in the Same Class• Guidelines for Invoking Methods• Passing Arguments and Returning Values• Declaring Methods With Arguments• Invoking a Method With Arguments• Declaring Methods With Return Values• Returning a Value• Receiving Return Values• Advantages of Method Use
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Creating Static Methods and Variables• Statics Methods and Variables in the Java API• When to declare a static method or variable• Uses for Method Overloading• Using Method Overloading• Method Overloading and the Java API
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Describe the advantages of methods and define worker and calling methods
• Declare and invoke a method• Compare object and static methods• Use overloaded methods
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Objects are self-contained entities that are made up of both data and functions that operate on the data– An object often models the real world
• Data is encapsulated by objects– Encapsulation means enclosing, hiding, or containing– Implementation details of functions are also encapsulated
Introduction
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Objects communicate by sending messages– getMoneyTotal and getName are examples of messages that can be sent to the person object, Jim
• Sending messages is the only way that objects can communicateIntroduction
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
colour = anUmbrella.getColour();
anUmbrella.setColour("blue");
homer.eat(donuts);
Introduction
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Sending a message is a different concept than calling a function– Calling a function indicates that you have identified the actual implementation code that you want to run at the time of the function call– Sending a message is just a request for a service from an object; the object determines what to do– Different objects may interpret the same message differently
Introduction
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Message– A message is a request for a service.
• Method– A method is the implementation of the service requested by the message– In procedural languages, these are known as procedures or functions
• A message is typically sent from one object to another; it does not imply what actual code will be executed• A method is the code that will be executed in response to a message that is sent to an object
Introduction
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public double getMoneyTotal() { double totalMoney = 0.0; totalMoney = totalMoney +
(.25*quarters); totalMoney = totalMoney + (.10*dimes); totalMoney = totalMoney + (.05*nickels); totalMoney = totalMoney + (.01*pennies); return totalMoney;}
Introduction
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Methods define how an object responds to messages• Methods define the behavior of the class• Syntax:
[modifiers] return_type method_identifier ([arguments]){
method_code_block}
Creating and Invoking Methods
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
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);} // end of display method
modifier keyword return type method name method arguments
Creating and Invoking Methods
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class ShirtTest {
public static void main (String args[]) { Shirt myShirt; myShirt = new Shirt();
myShirt.displayShirtInformation(); }
}
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);} // end of display method
Invoking a Method From a Different Class
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Calling and Worker Methods
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class One { public static void main(String args[]) { Two twoRef = new Two(); twoRef.workerMethod(); }}
public class Two { public void workerMethod() { int i = 42; int j = 24; }}
Calling method
Worker method
Calling and Worker Methods
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class CallingClass { public static void main(String args[]) { WorkerClass workerObject = new WorkerClass(); workerObject.worker1(); workerObject.worker2(); }}
public class WorkerClass { public void worker1() { int id = 44559; System.out.println(“The id is ” + id); } public void worker2() { float price = 29.99f; System.out.println(“The price is ” + price); }}
Calling and Worker Methods
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Calling a method in the same class is quite simple; write the calling method declaration code and include the name of the worker method and its arguments, if any.
public class DisclaimerOneFile { public void callMethod() { //calls the printDisclaimer method printDisclaimer(); } public void printDisclaimer() { System.out.println(“Hello Culiacan”); }}
Invoking a Method in the Same Class
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class Elevator { //instance variables public void openDoor() {…} public void closeDoor() {…} public void goUp() {…} public void goDown() {…} public void setFloor(int desiredFloor) { while (currentFloor != desiredFloor) if (currentFloor < desiredFloor) { goUp();
} else { goDown();
} } public int getFloor() {…} public boolean checkDoorStatus() {…}}
Invoking a Method in the Same Class
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• There is no limit to the number of method calls that a calling method can make.
• The calling method and the worker method can be in the same class or in different classes.
• The way you invoke the worker method is different, depending on whether it is in the same class or in a different class from the calling method.
• You can invoke methods in any order. Methods do not need to be completed in the order in which they are listed in the class where they are declared (the class containing the worker methods).
Guidelines for Invoking Methods
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Passing Arguments and Returning Values
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Passing Arguments and Returning Values
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Example:public void setFloor(int desiredFloor) { while (currentFloor != desiredFloor) { if (currentFloor < desiredFloor) { goUp();
} else { goDown();
}}
}
• Example:public void multiply(int NumberOne, int NumberTwo)
Declaring Methods With Arguments
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class GetInfo2 { public static void main(String args[]) { //makes a Shirt object Shirt2 theShirt = new Shirt2(); //calls the printInfo method theShirt.printInfo(44339,’L’);}
public class Shirt2 { int id; char size;public void printInfo(int shirtId, char shirtSize) { id = shirtId; //assign arguments to variables size = shirtSize; System.out.println(id); System.out.println(size); }}
Invoking a Method With Arguments
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class Arguments { public void passArguments() {
subtract( 3.14159f, 9f ); }
public void subtract( float first , float second ) { if((first-second)>=0) { System.out.println(“Positive”); } else { System.out.println(“Negative”); } }}
Invoking Methods With Arguments
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Declaration:public int sum(int numberOne, int numberTwo)
Declaring Methods With Return Values
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Example:
public int sum(int numberOne, int numberTwo) { int sum = numberOne + numberTwo; return sum;}• Example:
public int getFloor() { return currentFloor;}
Returning a Value
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Receiving Return Values
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class ReceiveValues { public static void main(String args[]) { AddsValues adder = new AddsValues(); int sum = adder.returnSum(); }}
public class AddsValues { public int returnSum() { int x = 4; int y = 17; return(x + y); }}
Receiving a Return Values
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Methods make programs more readable and easier to maintain.
• Methods make development and maintenance quicker.• Methods are central to reusable software.• Methods allow separate objects to communicate and to
distribute the work performed by the program.• Remember:
Advantages of Method Use
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Variables having the same value for all instances of a class are called class variables• Class variables are also sometimes referred to as static variables
public class Student { //class variables static int maxIdAssigned; //instance variable private int id;
//constructor public Student() { this.id = maxIdAssigned; maxIdAssigned++; }}
Creating Static Methods and Variables
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Certain methods defined in a class can operate only on class variables• We can invoke these methods directly using the class name without creating an instance• Such methods are known as class methods, or static methods• The main method of a Java program must be declared with the static modifier; this is so main can be executed by the interpreter without instantiating an object from the class that contains main.
In general, static refers to memory allocated at load time(when the program is loaded into RAM just before it starts running)
Creating Static Methods and Variables
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Example:
public class CountInstances { public static void main (String[] args) { Slogan obj; obj = new Slogan ("Remember the Alamo."); System.out.println (obj); obj = new Slogan ("Don't Worry. Be Happy."); System.out.println (obj); obj = new Slogan ("Live Free or Die."); System.out.println (obj); obj = new Slogan ("Talk is Cheap."); System.out.println (obj); obj = new Slogan ("Write Once, Run Anywhere."); System.out.println (obj); System.out.println(); System.out.println ("Slogans created: " + Slogan.getCount()); }}
Creating Static Methods and Variables
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Example:
public class Slogan { private String phrase; private static int count = 0;
public Slogan (String str) { phrase = str; count++; } public String toString() { return phrase; } public static int getCount () { return count; }}
Creating Static Methods and Variables
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Creating Static Methods and Variables
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Examples:
– The Math class• The Math class provides the important mathematical constants E and PI which are of type double.• The Math class also provides many useful math functions as methods.
– The System class• The System class provides access to the native operating system's environment through the use of static methods.
Statics Methods and Variables in the Java API
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Examples:
•
public class Get { public static void main (String[] args) { StaticExample ex = new StaticExample(); ex.getNumber();}
public class StaticExample { public void getNumber() { System.out.println(“A random number: ” + Math.random()); }}
Statics Methods and Variables in the Java API
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Examples:
•// Determines the roots of a quadratic equation.public class Quadratic { public static void main (String[] args) { int a, b, c; // ax^2 + bx + c a = 5; // the coefficient of x squared b = 7; // the coefficient of x c = 2; // the constant // Use the quadratic formula to compute the roots. // Assumes a positive discriminant. double discriminant = Math.pow(b, 2) - (4 * a * c); double root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a); double root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a); System.out.println ("Root #1: " + root1); System.out.println ("Root #2: " + root2); }}
Statics Methods and Variables in the Java API
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Performing the operation on an individual object or associating the variable with a specific object type is not important.• Accessing the variable or method before instantiating an object is important.• The method or variable does not logically belong to an object, but possibly belongs to a utility class, such as the Math class, included in the Java API.
When to declare a static method or variable
• A static method can only change static variables
• Instance variables can only be changed by non-static methods
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Java allows us to have two or more methods with the same name inside the same class
• As with constructors, the overloaded methods should also have different number of parameters, or have different data types for the parameters
• This feature of Java is called method overloading• The compiler will detect errors at the compilation time if two
methods in a class have the same name and have the same number and type of parameters
Uses for Method Overloading
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Example overloaded methods:
public class OverloadTest { public static void main(String args[]) { MethodOverloadingDemo md = new MethodOverloadingDemo(); md.printToScreen(53,8965); md.printToScreen(68, 'g'); md.printToScreen('f', 74); md.printToScreen(64, 36, 'h'); md.printToScreen(85, 'd', (float)745.3, "true");
}}
Using Method Overloading
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Example overloaded methods:
public class MethodOverloadingDemo { public void printToScreen(int a, int b) { System.out.println(a); System.out.println(b); } public void printToScreen(int a, char c) { System.out.println(a); System.out.println(c); } public void printToScreen(char c, int a) { System.out.println(c); System.out.println(a); }
Using Method Overloading
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Example overloaded methods:
public void printToScreen(int a, int b, int c) { System.out.println(a); System.out.println(b); System.out.println(c); } public void printToScreen(int a, char c, float f, String s) { System.out.println(a); System.out.println(c); System.out.println(f); System.out.println(s); }}
Using Method Overloading
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Method Overloading and the Java API
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Examples:
public int sum(int numberOne, int numberTwo)public int sum(int numberOne, int numberTwo, int numberThree)public int sum(int numberOne, int numberTwo,int numberThree, intnumberFour)
Uses for Method Overloading
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class ShirtTwo { public int shirtID = 0; // Default ID for the shirt public String description = “-description required-”; // default // The color codes are R=Red, B=Blue, G=Green, U=Unset public char colorCode = ‘U’; public double price = 0.0; // Default price for all items public int quantityInStock = 0; // Default quantity for all items public void setShirtInfo(int ID, String desc, double cost, char color){ shirtID = ID; description = desc; price = cost; colorCode = color; }
Uses for Method Overloading
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public void setShirtInfo(int ID, String desc, double cost, char color, int quantity){
shirtID = ID;description = desc;price = cost;colorCode = color;quantityInStock = quantity;
} // This method displays the values for an item public void display() { System.out.println(“Item ID: “ + shirtID); System.out.println(“Item description:” + description); System.out.println(“Color Code: “ + colorCode); System.out.println(“Item price: “ + price); System.out.println(“Quantity in stock: “ + quantityInStock); } // end of display method} // end of class
Uses for Method Overloading
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class ShirtTwoTest { public static void main (String args[]) { ShirtTwo shirtOne = new ShirtTwo(); ShirtTwo shirtTwo = new ShirtTwo(); ShirtTwo shirtThree = new ShirtTwo(); shirtOne.setShirtInfo(100, “Button Down”, 12.99); shirtTwo.setShirtInfo(101, “Long Sleeve Oxford”, 27.99, ‘G’); shirtThree.setShirtInfo(102, “Shirt Sleeve T-Shirt”, 9.99, ‘B’, 50); shirtOne.display(); shirtTwo.display(); shirtThree.display();
}}
Uses for Method Overloading
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 13Methods Lab
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Lab Exercise 1• Lab Exercise 2• Lab Exercise 3
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Create classes and objects• Invoke methods of a class• Overload methods in a class
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Write a Shirt class that has a price, item ID, and type (such as Oxford or polo). Declare methods that return those three values. (These are get methods).
2. Write another class that calls and prints those values.3. You will need to create two files, one called Shirt.java
that declares the shirt variables and methods, and one called CreateShirt.java that calls the methods and prints the values.
Lab Exercise 1
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Define a method called sayHello in class Methodcall, provided in the skeleton code, that has no arguments and no return value. Make the body of the method simply print "Hello."
public class Methodcall { public static void main(String[] args) { new Methodcall().start(); // students: ignore this } public void start() { // a test harness for two methods // } // Define method sayHello with no arguments and no return value // Make it print "Hello". // Define method addTwo with an int parameter and int return type // Make it add 2 to the parameter and return it.}
Lab Exercise 2 (1 of 2)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Make the start method of Methodcall call sayHello().• Define a method called addTwo that takes an integer
argument, adds 2 to it, and returns that result.• In the start method of Methodcall, define a local
integer variable and initialize it to the result of calling addTwo(3). Print out the variable; that is, print out the result of the method call. Define another local integer variable initialize it to the result of calling addTwo(19). Print out its result.
Lab Exercise 2 (2 of 2)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Write a Java program that has the classes Area and User. Area has overloaded static methods by the name area() that can be used to calculate the area of a circle, triangle, rectangle and a cylinder. User uses the methods of Area to calculate the area of different geometric figures and prints it to the standard output.
2. Write a class called Area.3. Write four overloaded methods named area that take
different numbers and type of data types as parameters. These methods are used to calculate the area of a circle, triangle, rectangle and cylinder.
Lab Exercise 3 (1 of 2)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
4. Write a class called User that invokes the different versions of area() in Area class with sample values as parameters. The return value is printed on to the standard output.
• Area of circle = 3.14 * radius * radius• Area of triangle = 0.5 * base * height• Area of rectangle = length * breadth• Area of cylinder = 3.14 * radius * radius *
height
Lab Exercise 3 (2 of 2)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 14Implementing Encapsulation
and Constructors
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Using Encapsulation• The public Modifier• The private Modifier• Describing Variable Scope• How Instance Variables and Local Variables Appear in
Memory• Constructors of a Class• Creating Constructors• Default Constructors• Overloading Constructors
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Use encapsulation to protect data• Create constructors to initialize objects
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Encapsulation separates the external aspects of an object from the internal implementation details• Internal changes need not affect external interface
Hide implementation from clients.Clients depend on interface
Using Encapsulation
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Using Encapsulation
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Using Encapsulation
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• You can put the public modifier in front of a member variable or method to mean that code in any other class can use that part of the object.
public class PublicExample { public static void main(String args[]) { PublicClass pc = new PublicClass(); pc.publicInt = 27; pc.publicMethod(); }} public class PublicClass {
public int publicInt; public void publicMethod() { System.out.println(publicInt); }}
The public Modifier
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public int currentFloor=1;public void setFloor(int desiredFloor) {...}
The public Modifier
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Put the private modifier in front of a member variable or method if you do not want any classses outside the object’s class to use that part of an object.
public class PrivateExample { public static void main(String args[]) { PrivateClass pc = new PublicClass(); pc.privateInt = 27; pc.privateMethod(); }} public class PrivateClass {
private int privateInt; private void privateMethod() { System.out.println(privateInt); }}
X
X
The private Modifier
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.comprivate int currentFloor=1;
private void calculateCapacity() {...}
The private Modifier
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• All variables are not available throughout a program• Variable scope means where a variabe can be used
public class Person2 { // begin scope of int age private int age = 34; public void displayName() { // begin scope of String name String name = “Peter Simmons”; System.out.println(“My name is “+ name + “ and I am “ + age ); } // end scope of String name public String getName () { return name; // this causes an error }} // end scope of int age
Describing Variable Scope
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Local variables are:– Variables that are defined inside a method and are
called local, automatic, temporary, or stack variables– Variables that are created when the method is
executed are destroyed when the method is exited– Local variables require explicit initialization– Member and class variables are automatically
initialized
Describing Variable Scope
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
How Instance Variables and Local Variables Appear in Memory
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• The constructor is essentially used to initialize a newly created object of that particular type
• All classes written in Java have at least one constructor• If the programmer does not define any constructor for a
class, then the class will have the default constructor created by the Java runtime system
• The default constructor accepts no arguments• It has an empty implementation, and does nothing• Java allow us to have as many constructors as required
with the same name, the only difference being the number or the type of arguments for a class. This is called constructor overloading
Constructors of a Class
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• To define a constructor use the same name as the class and give no return type
public class Hat { private String type; public Hat(String hatType) { type = hatType; }
public class Hat { private String type; public Hat(String hatType) { type = hatType; }
public class Order { Hat hat1 = new
Hat(“Fedora”);}
public class Order { Hat hat1 = new
Hat(“Fedora”);}
Creating Constructors
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class MyClass { int x;
MyClass() { x = 10; }}
public class ConstructorDemo { public static void main(String[] args ) { MyClass t1 = new MyClass(); MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x); }}
Default Constructors
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class MyClassTwo { int x; MyClassTwo() { x = 10; } MyClassTwo(int i) { x = i; }}
public class ParametrizedConstructorDemo { public static void main(String[] args) { MyClassTwo t1 = new MyClassTwo(10); MyClassTwo t2 = new MyClassTwo(88);
System.out.println(t1.x + " " + t2.x); }}
Overloading Constructors
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class Student { private int id = 0; private String name;
public Student() { } public Student(int a) { id = a; } public Student(int a, String aName) { id = a; name = aName; } public void setValues(int sid, String sName) { id = sid; name = sName; } public static void main(String[] args) { Student s = new Student(1,"John"); }
}
Overloading Constructors
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 15Implementing Encapsulation and
Constructors Lab
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Lab Exercise 1• Lab Exercise 2
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Practice implementing encapsulation.
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Declare a Customer class with variables for a salutation (such as Ms.), first name, middle name, last name, and address, with three constructors:
• One creates a new customer with no values• One takes a salutation (such as Ms.), first name,
middle name, and last name
2. Test the program with a CustomerTest.java program
Lab Exercise 1
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Make a class called Rectangle that represents a rectangle using private width and height variables. Make the following public methods:• getHeight returns the height of the rectangle• getWidth returns the witdh of the rectangle• setHeight verifies the data and assigns the new value to
the height• setWidth verifies the data and assigns the new value to
the width• getArea returns the area of the rectangle• getPerimeter returns the perimeter of rectangle• draw draws the rectangle using asterisks(*’s) as the
drawing character2. Write the main method in another class TestRectangle to test
the Rectangle class (call the methods, and so on).
Lab Exercise 2
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 16Creating and Using Arrays
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Creating One-Dimensional Arrays• Declaring a One-Dimensional Array• Instantiating a One-Dimensional Array• Declaring, Instantiating, and Initializing One-
Dimensional Arrays• Accessing a Value Within an Array• Storing Primitive Variables and Arrays of Primitives in
Memory• Storing Reference Variables and Arrays of References
in Memory• Setting Array Values Using the length Attribute and a
Loop• Using the args Array in the main method• Converting String arguments to Other Types• Describing Two-Dimensional Arrays
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Declaring a Two-Dimensional Array• Instantiating a Two-Dimensional Array• Initializing a Two-Dimensional Array
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Code one-dimensional arrays• Set array values using the length attribute and a loop• Pass arguments to the main method for use in a
program• Create two-dimensional arrays
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• An array is an ordered list of values.• Arrays are dynamically created objects in Java code. An array can hold a number of variables of the same type. The variables can be primitives or object references; an array can even contain other arrays. Creating One-Dimensional Arrays
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• When we declare an array variable, the code creates a variable that can hold the reference to an array object. It does not create the array object or allocate space for array elements. It is illegal to specify the size of an array during declaration.
• Syntax:
type [] array_identifier;
• Examples:
char [] status;int [] ages;Shirt [] shirts;String [] names;
Declaring a One-Dimensional Array
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• You can use the new operator to construct an array. The size of the array and type of elements it will hold have to be included.
• Syntax:
array_identifier = new type [length];
• Examples:
status = new char[20];ages = new int[5];names = new String[7];shirts = new Shirt[3];
Instantiating a One-Dimensional Array
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Arrays are indexed beginning with 0 and ending with n-1. where n is the array size. To get the array size, use the array instance variable called length
• Once an array is created, it has a fixed size• Syntax:
array_identifier[index] = value;
• A particular value in an array is referenced using the array name followed by index in brackets.
Initializing a One-Dimensional Array
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Examples:
int[] height = new int[11]; height[0] = 69; height[1] = 61;height[2] = 70;height[3] = 74;height[4] = 62;height[5] = 69;height[6] = 66;height[7] = 73;height[8] = 79;height[9] = 62;height[10] = 70;
Initializing a One-Dimensional Array
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• An array initializer is written as a comma separated list of expressions, enclosed within curly braces.
• Syntax:
type [] array_identifier = {comma-separated list of values or expressions};
• Examples:
int [] ages = {19, 42, 92, 33, 46};
Shirt [] shirts = { new Shirt(), new Shirt(121,”Work Shirt”, ‘B’, 12.95), new Shirt(122,”Flannel Shirt”, ‘G’, 22.95)};
double[] heights = {4.5, 23.6, 84.124, 78.2, 61.5};boolean[] tired = {true, false, false, true}; char vowels[] = {'a', 'e', 'i', 'o', 'u'}
Declaring, Instantiating, and Initializing One-Dimensional Arrays
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• To access a value in an array, we use the name of the array followed by the index in square brackets• An array element can be assigned a value, printed, or used in calculation• Examples:
status[0] = ’3’;names[1] = "Fred Smith";ages[1] = 19;prices[2] = 9.99F;char s = status[0];String name = names [1];int age = ages[1];double price = prices[2];
Accessing a Value Within an Array
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Examples:
height[2] = 72;height[count] = feet * 12;average = (height[0] + height[1] + height[2]) / 3;System.out.println (“The middle value is “ + height[MAX/2]);pick = height[rand.nextInt(11)];
Accessing a Value Within an Array
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Storing Primitive Variables and Arrays in Memory
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Storing Reference Variables and Arrays in Memory
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class Primes { public static void main (String[] args) { int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19}; System.out.println ("Array length: " + primeNums.length); System.out.println ("The first few prime numbers are:"); for (int scan = 0; scan < primeNums.length; scan++) System.out.print (primeNums[scan] + " "); System.out.println (); }}
Setting Array Values Using the length Attribute and a loop
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Command Line Arguments can be used to supply inputs to a program during its execution.
• The general construct used for the command line arguments is as follows:
java classFileName argument1 argument2 etc…
We can give any number of command line arguments. These
command line arguments are stored in the string array passed to
the main() method.
Using the args Array in the main Method
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
java ArgTest Hello Java
The output is:args[0] is Helloargs[1] is Java
• All command line arguments are interpreted as strings in Java.
public class ArgsTest { public static void main (String args[]) {
System.out.println(“args[0] is “ + args[0]); System.out.println(“args[1] is “ + args[1]); }}
Using the args Array in the main Method
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Example:
int ID = Integer.parseInt(args[0]);
• The Integer class is one of Java's "wrapper" classes that provides methods useful for manipulating primitive types. Its parseInt() method will convert a String into an int, if possible.
Converting String Arguments to Other Types
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• A one dimensional array stores a list of elements• A two-dimensional array can be thought of as a table of elements, with rows and columns• We must use two indexes to refer to a value in a two-dimensional array, one specifying the row and another the column.
Describing Two-Dimensional Arrays
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• A two-dimensional array element is declared by specifying the size of each dimension separately• Syntax:
type [][] array_identifier;
• Example:
int [][] yearlySales;
Declaring a Two-Dimensional Array
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Syntax:
array_identifier = new type [number_of_arrays] [length];
• Example:
// Instantiates a two-dimensional array: 5 arrays of 4 elements each yearlySales = new int[5][4];
Instantiating a Two-Dimensional Array
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Example:
yearlySales[0][0] = 1000;yearlySales[0][1] = 1500;yearlySales[0][2] = 1800;yearlySales[1][0] = 1000;yearlySales[2][0] = 1400;yearlySales[3][3] = 2000;
Instantiating a Two-Dimensional Array
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
int myTable[][] = {{23, 45, 65, 34, 21, 67, 78}, {46, 14, 18, 46, 98, 63, 88}, {98, 81, 64, 90, 21, 14, 23}, {54, 43, 55, 76, 22, 43, 33}};
for (int row=0;row<4; row++) { for (int col=0;col<7; col++) System.out.print(myTable[row][col] + " "); System.out.println(); }
Instantiating a Two-Dimensional Array
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 17Arrays Lab
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Lab Exercise 1• Lab Exercise 2• Lab Exercise 3
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Create and Initialize an array
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Make an array of 5 integers• Use a for loop to set the values of the array to the index
plus 10• Use a for loop to print out the values in the array• Make an arrays of strings initialized to Frank, Bob, and Jim
using the variable initializer syntax• Use a for loop to print out the string in the array• Set the last element of the array to Mike• Print out the last element in the array
Lab Exercise 1
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Write an Ages program that will fill an array of ten positions with the ages of ten people you know. (Hard-core the ages into your program, do not try to use user input). Calculate and print the oldest age, the youngest age, and the average age.
Lab Exercise 2
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Write a program that creates and assigns values to an array of Shirt objects. In the Shirt class, declare at least two variables such as size and price.
2. Create another class that create the arrays of shirts.
Lab Exercise 3
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 18Implementing Inheritance
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Inheritance• What is Inherited in Java?• Single vs. Multiple Inheritance• Declaring a subclass• Overriding Methods• Overloading vs. Overriding
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Define and test your use of inheritance
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Inheritance allows a software developer to derive a new class from an existing one• The existing class is called the
parent class or superclass, or base class
• The derived class is called the child class or subclass.
Inheritance
Inheritance is the backbone of object-oriented programming. It enables programmers to create a hierarchy among a group of classes that have similar characteristics
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• As the name implies, the child inherits characteristics of the parent• That is, the child class inherits the methods and data defined for the parent class• To tailor a derived class, the programmer can add new variables or methods, or can modify the inherited ones
What is Inherited in Java?
Animal
Mammal
Cat
class Animal eat() sleep() reproduce()
class Mammal reproduce()
class Cat sleep() huntMice() purr()
Cat Gardfield eat() reproduce() sleep() huntMice() purr()
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
• Java does not support multiple inheritance– Every Java class except Object has exactly one immediate superclass (Object does not have a superclass)
• You can force classes that are not related by inheritance to implement a common set of methods using interfacesSingle vs. Multiple Inheritance
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Declaring a subclass
• In Java, we use the reserved word extends to establish an inheritance relationship
• Syntax:
[class_modifier] class class_identifier extendssuperclass_identifier
public class Animal {…}
public class Mammal extends Animal { //code specific to a Mammal}
public class Cat extends Mammal { //code specific to a Cat}
Animal
Mammal
Cat
Here Mammal extends Animal means that Mammal inherits from Animal, or Mammal isa type of Animal
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class Animal { public void speak() { System.out.println("I am a generic animal"); } }
public class Dog extends Animal { public void speak() { System.out.println("Woof!!"); } }
public class Cat extends Animal { public void speak() { System.out.println(“Meow!!"); } }
Declaring a subclass
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Overriding Methods
• When a child class defines a method with the same name and signature as a method in the parent class, we say that the child’s version overrides the parent’s version in favor of its own
• The new method must have the same signature as the parent’s method, but can have a different body
• The type of the object executing the method determines which version of the method is invoked
class Animal eat() sleep() reproduce()
class Mammal reproduce()
class Cat sleep() huntMice() purr()
Cat Gardfield eat() reproduce() sleep() huntMice() purr()
overriding
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Overriding Methods
public class MoodyObject { // return the mood protected String getMood() { return "moody"; }
// ask the object how it feels public void queryMood() { System.out.println("I feel " + getMood() + "
today!"); }
}
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Overriding Methods
public class HappyObject extends MoodyObject {
// redefine class’s mood protected String getMood() { return "happy"; }
// specialization public void laugh() { System.out.println("hehehe... hahaha...
HAHAHAHAHAHA!!!!!"); }
}
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
public class MoodyDriver { public final static void main(String[] args) { MoodyObject moodyObject = new MoodyObject(); HappyObject happyObject = new HappyObject(); System.out.println("How does the moody object feel today?"); moodyObject.queryMood(); System.out.println(""); System.out.println("How does the happy object feel today?"); happyObject.queryMood(); //overriding changes the mood happyObject.laugh(); System.out.println(""); }}
Overriding Methods
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Overloading vs. Overriding
Overloading deals with multiples methods in the same class with the same name but different signatures
Overloading lets you define a similar operation in different ways for different data
Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature
Overriding lets you define a similar operation in different ways for different object types
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Overloading vs. Overriding
Inheritance
Polymophism: Override, Overload
Method(x)
Method(x)
……Method(x)
Method(x,y)
Method(x)
Method(x,y)
Method(x)
Method(x)
…………
superclass
subclass
Sub-subclass
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Module 19Inheritance Lab
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Agenda
• Objectives• Lab Exercise 1• Lab Exercise 2
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Objectives
• Work with inheritance• Invoke methods in a super class
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
Design and implement a set of classes that define the following
class hierarchy. Include methods in each class that are named
according to the services provided by that class and that print an
appropriate message. Create a main driver class to instantiate and
exercise several of the classes.
Lab Exercise 1
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
1. Write a Java program that has a class called Color. Color has an attribute called colorName that is private. Color also has the following methods:
final void setColor(String color);String getColor(); // returned string gives the color
2. The class White inherits from Color, and has its (private) attribute colorName set to White. The classes Violet, Indigo, Blue, Green, Yellow, Orange, and Red inherit from the White class. All these classes have a private variable each, called colorName, initialized to ’violet’, ’indigo’, ’blue’, ’yellow’, ’orange’, and ’red’ respectively. The class Prism has the following method:
void activatePrism(Color c);
Lab Exercise 2 (1 of 2)
BorradorPlumónPlumónPlumón
ww
w.p
rofe
sorj
ava
.com
3. This method checks if the getColor() method returns ’white’. If true, it creates instances of Violet, Indigo, Blue, Green, Yellow, Orange, and Red classes, and prints their colorName attribute to the standard output. If the above check results in a false, the method returns. The class AntiPrism has a method as shown below:
void activateAntiPrism(Red r, Blue b, Green g);
4. This method checks if the colorName attribute of r, b, and g are ’red’, ’blue’, and ’green’ respectively. If true, it creates a new White object, and prints the value of its attribute colorName on to the standard output.
5. A class Scientist uses the Prism and AntiPrism classes.
Lab Exercise 2 (2 of 2)