PJ-050. <br />Curso de Programación Java Básico.<br />www.profesorjava.com<br />
Esta obra está bajo una licencia Reconocimiento 2.5 México de CreativeCommons. Para ver una copia de esta licencia, visite...
Acerca de:<br />En la compilación de esta obra se utilizaron libros conocidos en el ambiente Java, gráficas, esquemas, fig...
CONTENIDO<br />Modulo 01: Introducción al lenguaje Java. <br />Modulo 02: Crear un programa simple en Java.<br />Modulo 03...
CONTENIDO<br />Modulo 09: Práctica de laboratorio 04.<br />Modulo 10: Estructuras repetitivas.<br />Modulo 11: Práctica de...
CONTENIDO<br />Modulo 16: Arreglos.<br />Modulo 17: Práctica de laboratorio 08.<br />Modulo 18: Herencia.<br />Módulo 19: ...
Module 01Introduction to the Java Programming Language<br />
Agenda<br />Objectives<br />What is Java?<br />Java Features<br />The Java evolution<br />Java Virtual Machine (JVM)<br />...
Objectives<br />Describe the history and properties of the Java programming language<br />Explain the Java execution model...
What is Java?<br />Java is an object-oriented programming language developed by Sun Microsystems<br />Java has a set of st...
Java Features<br />
Goals of Java<br />Object-oriented<br />Java supports software development using the notion of objects<br />Software devel...
Goals of Java<br />Network capable<br />Java supports the development of distributed applications<br />Some types of Java ...
Goals of Java<br />Robust<br />Many aspects of Java promote the development of reliable software<br />Java uses a pointer ...
Goals of Java<br />Multi-threaded<br />Allows your program to run more than one task at the same time<br />
Goals of Java<br />Compiled and interpreted<br />Source code is compiled into machine code for the Java virtual machine (J...
Goals of Java<br />Portable at source and binary level<br />One piece of source code gets compiled into one set of bytecod...
The Java evolution<br />Java is a relatively young language<br />It has been in use since 1995<br />It was originally desi...
The Java platform<br />A platform is a development or <br />    deployment environment<br />The Java platform runs on any ...
Java Virtual Machine (JVM)<br />A virtual machine is an executable that represents a generic<br />processor on which Java’...
Uses of Java<br />Java can be used to build <br />    programs and software <br />    components<br />Programs are stand-a...
Programs<br />Application<br />A stand-alone program that can access system resources such as files<br />Does not need to ...
Programs<br />Applet<br />A Java program that is embedded within a Web page; almost always graphical<br />Security limits ...
Components<br />Servlet<br />Handles requests from the Web browser and returns responses<br />Creates dynamic content on t...
Components<br />JavaBeans<br />Java code that has its properties, methods, and events exposed to promote reuse among devel...
Components<br />Enterprise JavaBeans (EJB)<br />Distributed objects that allow communication between Java objects in diffe...
Module 02Developing and Testing a Java Program<br />
Agenda<br />Objectives<br />Identifying the Components of a Class<br />Structuring Classes<br />Class Declaration<br />Var...
Objectives<br />Identify the four components of a class in the Java programming language<br />Use the main method in a tes...
Identifying the Components of a Class<br />Classes are the blueprints that you create to define the objects in a program.<...
Comments<br />//Employee.java<br />public class Employee {<br />private String id;<br />private String lastName;<br />publ...
Structuring Classes<br />//Piano.java<br />publicclassPiano{<br />privateint keys = 88;<br />//this method displays the nu...
Class Declaration<br />Syntax:<br />[modifier] class class_identifier<br />Example:<br />public class Piano<br />public cl...
Class Declaration<br />public class Shirt {<br />public int shirtID = 0; // Default ID for the shirt<br />public String de...
Shirt id<br />Description<br />Color Code<br />Price<br />Quantity in stock<br />Variable Declarations and Assignments<br ...
Comments<br />
Methods<br />Syntax:<br />[modifiers] return_type method_identifier([arguments]){<br />  method_code_block<br />}<br />Exa...
Methods<br /><ul><li>Classes in Java may have methods and attributes.
Methods define actions that a class can perform.
Attributes describe the class. </li></li></ul><li>Testing and Using a Test Class<br />public classShirt {<br />  …<br />  ...
The main method<br />Syntax:<br />public static void main (String args[])<br />The main() method is the normal entry point...
The main method<br />This is the definition of the class OurFirstProgram.  The class definition only <br />contains the me...
Compiling and Executing (Testing) a Program<br />
Compiling and Executing (Testing) a Program<br />1. Go the directory where the source code files are stored.<br />2. Enter...
Executing (Testing) a Program<br />1. Go the directory where the class files are stored.<br />2. Enter the following for t...
Debugging Tips<br />Check line referenced in error message<br />Check for semicolons<br />Check for even number of braces<...
Module 03Writing, Compiling, and Testing a Basic Program Lab<br />
Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />Lab Exercise 3<br />
Objectives<br />Become familiar with the structure and parts of a basic Java Program. <br />
Lab Exercise 1<br />Create a new public class, HelloWorld, with a main method. The main method should output the string “H...
Lab Exercise 2 (1 of 2)<br />Create a new public class,Quotation.<br />Enter the following source code:<br />publicclassQu...
Lab Exercise 2 (2 of 2)<br />Enter the following source code:<br />publicclassQuotationTest {<br />publicclassHelloWorld {...
Lab Exercise 3<br />1. Create a new class Car with the following methods: <br />public void start() <br />public void stop...
Module 04Declaring, Initializing, and Using Variables<br />
Agenda<br />Objectives<br />Identifying Variable Use and Syntax<br />Uses for variables<br />Variable Declaration and Init...
Agenda<br />Constants<br />Storing Primitive and Constants in Memory<br />Standard Mathematical Operators<br />Increment a...
Objectives<br />Identify the uses for variables and define the syntax for a variable<br />List the eight Java programming ...
Identifying Variable Use and Syntax<br />public class PianoKeys {<br />public static void main(String[] args) {<br />    i...
Identifying Variable Use and Syntax<br />public class Geometry {<br />public static void main(String[] args) {<br />int si...
Identifying Variable Use and Syntax<br />public class Circle {<br />public double radio;<br />public Circle(double r) {<br...
Uses for variables<br />Holding unique data for an object instance<br />Assigning the value of one variable to another<br ...
Variable Declaration and Initialization<br />Syntax (attribute or instance variables):<br />[modifiers] type identifier = ...
Describing Primitive Data Types<br />Integral types (byte, short, int, and long)<br />Floating point types (float and doub...
Integral Primitive Types<br />Signed whole numbers<br />Initialized to zero<br />
Integral Primitive Types<br />public class IntegralType {    <br />public static void main( String args[] ) {   <br />byte...
Floating Primitive Types<br />“General” numbers (can have fractional parts)<br />Initialized to zero<br />
Floating Primitive Types<br />public class Tax {    <br />public static void main( String args[] ) {<br />double price = 2...
Textual Primitive Types<br />Any unsigned Unicode character is a char primitive data type<br />A character is a single Uni...
Textual Primitive Types<br />public class PrintChar {<br />public static void main( String args[] ) {<br />char c = &apos;...
Logical Primitive Types<br />boolean values are distinct in Java<br />An int value can NOT be used in place of a boolean<b...
Logical Primitive Types<br />public class CatDog {<br />public static void main( String args[] ) {<br />boolean personWith...
Rules:<br />Variable identifiers must start with either an uppercase or lowercase letter, an underscore (_), or a dollar s...
Assigning a Value to a Variable<br />Example:<br />double price = 12.99;<br />Example (boolean):<br />boolean isOpen = fal...
Declaring and Initializing Several Variables in One Line of Code<br />Syntax:<br />type identifier = value [, identifier =...
Additional Ways to Declare Variables and Assign Values to Variables<br />Assigning literal values:<br />int ID = 0;<br />f...
Additional Ways to Declare Variables and Assign Values to Variables<br />Assigning the result of an expression to integral...
Constants<br />Variable (can change):<br />double salesTax = 6.25;<br />Constant (cannot change):<br />final double SALES_...
Storing Primitive and Constants in Memory<br />
Standard Mathematical Operators<br />
Standard Mathematical Operators<br />
Increment and Decrement Operators (++ and --)<br />
Increment and Decrement Operators (++ and --)<br />
Increment and Decrement Operators (++ and --)<br />
Operator Precedence<br />Rules of precedence:<br />1. Operators within a pair of parentheses<br />2. Increment and decreme...
Operator Precedence<br />
Using Parenthesis<br />Examples:<br />c = (((25 - 5) * 4) / (2 - 10)) + 4;<br />c = ((20 * 4) / (2 - 10)) + 4;<br />c = (8...
Casting Primitive Types<br />Java is a strictly typed language<br />Assigning the wrong type of value to a variable could ...
Implicit versus explicit casting<br />Casting is automatically done when no loss of information is possible<br />An explic...
Examples (Casting)<br />byte b = 3;<br />int x = b;<br />byte a;<br />int b = 3;<br />a = (byte)b;<br />int num1 = 53; // ...
Examples (Casting)<br />int num1 = 53; // 32 bits of memory to hold the value<br />int num2 = 47; // 32 bits of memory to ...
1<br />1<br />0<br />0<br />0<br />0<br />0<br />0<br />1<br />0<br />0<br />0<br />0<br />0<br />0<br />0<br /> b = (byte...
Examples (Casting)<br />public class ExplicitCasting {    <br />public static void main( String args[] ) {<br />byte b;<br...
Module 05Using Primitive Types, Operators and Type Casting, in a Program Lab<br />
Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />Lab Exercise 3<br />
Objectives<br />Write the code to declare, assign values to, and use variables in a program<br />Practice using operators ...
Lab Exercise 1<br />1. Create a class called Rectangle.java, define a variable called length of type int and define anothe...
Lab Exercise 2<br />Write a program to create a class called Calculator that uses arithmetic operators.  Initialize the va...
Lab Exercise 3<br />Write a program called Temperature containing a temperature in Fahrenheit and a method called calculat...
Module 06Creating and Using Objects<br />
Agenda<br />Objectives<br />Introduction<br />Declaring Object References, Instantiating Objects, and Initializing Object ...
Objectives<br />Declare, instantiate, and initialize object reference variables<br />Compare how object reference variable...
Introduction<br />
The phrase &quot;to create an <br />instance of an object“ means <br />to create a copy of this object <br />in the comput...
Introduction<br />            Class                       Object (Instance)<br />
Declaring Object References, Instantiating Objects, and Initializing Object References<br />A primitive variable holds the...
Declaring Object References, Instantiating Objects, and Initializing Object References<br />publicclassShirtTest {<br />pu...
Declaring Object Reference Variables<br />Syntax:<br />Classname identifier;<br />• Example:<br />Shirt myShirt;<br />Circ...
Instantiating an Object<br />Syntax:<br />new Classname();<br />
Initializing Object Reference Variables<br />The assignment operator<br />• Examples:<br />myShirt = new Shirt();<br />
Using an Object Reference Variable to Manipulate Data<br />public class Shirt {<br />public int shirtID = 0; <br />public ...
Using an Object Reference Variable to Manipulate Data<br />public class ShirtTestTwo {<br />public static void main (Strin...
Using an Object Reference Variable to Manipulate Data<br />public class Circle {<br />privateint radius; <br />}<br />publ...
Using an Object Reference Variable to Manipulate Data<br />public class Circle {<br />privateint radius; <br />}<br />publ...
Storing Object Reference Variables in Memory<br />public static void main (String args[]) {<br />intcounter;<br />  counte...
Assigning an Object Reference From One Variable to Another<br />1 Shirt myShirt = new Shirt();<br />2 Shirt yourShirt = ne...
Assigning an Object Reference From One Variable to Another<br />public class Cat {<br />    …<br />    …<br />}<br />Cat A...
Assigning an Object Reference From One Variable to Another<br />
Any number of characters between double quotes is a String:<br />String can be initialized in other ways:<br />Strings<br />
Strings are objects.  These objects are inmmutable.  Their value, once assigned, can never be changed.  For instance:<br /...
The + operator concatenates Strings:<br />String a = “This” + “ is a ” + “String”;<br />Primitive types used in a call to ...
oneString.equals(anotherString)<br />Tests for equivalence<br />Returns true or false<br />oneString.equalsIgnoreCase(anot...
Strings are objects; objects respond to messages<br />Use the dot (.) operator to send a message<br />String is a class<br...
StringBuffer is a more efficient mechanism for building strings<br />String concatenation <br />Can get very expensive<br ...
Module 07Objects and Strings Lab<br />
Agenda<br />Objectives<br />Lab Exercise 1<br />
Objectives<br />Create instances of a class and manipulate these instances in several ways.<br />Make use of the String cl...
Lab Exercise 1 (1 of 5)<br />Create a class called BankAccount.<br />Enter the following code:<br />public class BankAccou...
Lab Exercise 1 (2 of 5)<br /> // the code for the methods starts here<br />public int getBalance() { return balance;}<br /...
Lab Exercise 1 (3 of 5)<br />3. Create a BankAccount in another Test program (BankTest).  The instance is named savings.  ...
Lab Exercise 1 (4 of 5)<br />5. Call methods of the objects and see what effect they have. <br />savings.credit(1000); <br...
Lab Exercise 1 (5 of 5)<br />6. Assign one object reference to another object reference by assigning savings to a new inst...
Module 08Using Operators and Decision Constructs<br />
Agenda<br />Objectives<br />Using Relational and Conditional Operators<br />Creating if and if/else Constructs<br />Using ...
Objectives<br />Identify relational and conditional operators<br />Examine if and if/else constructs<br />Use the switch c...
Using Relational and Conditional Operators<br />The Java language provides several means of altering the sequential flow o...
Relational operators<br /><ul><li>Relational operators are used for comparing two values stored in a variable.</li></li></...
These operators require two operators.  Hence they are called binary operators</li></li></ul><li>The if Construct<br />An ...
The if Construct<br />public class Coffee {<br />private static inthour=9;<br />public static void main(String args[]) {<b...
The if/else Construct<br />Syntax:<br />if (boolean_expression) {<br />  code_block;<br />} // end of if construct<br />el...
The if/else Construct<br />public class CoffeeIfElse {<br />private static inthour=9;<br />public static void main(String ...
The if/else Construct<br />public class IfElseDemo {<br />public static void main(String[] args) {<br />int testscore = 76...
Tests a single variable for several alternative values and executes the corresponding case<br />Any case without break wil...
The argument passed to the switch and case statements should be int, short, char, or byte.<br />Syntax:<br />switch (varia...
Using the switch Construct<br />public class SwitchDemo {<br />public static void main(String[] args) {<br />int month = 8...
Module 09if/switch Lab<br />
Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />Lab Exercise 3<br />
Objectives<br />Create classes that use if and if/else constructs.<br />Using the switch construct in decision-making prog...
Lab Exercise 1<br />Write a program called Division that does the following:<br />Takes three command-line arguments<br />...
Lab Exercise 2 <br />Create a class called DayOfWeek with one variable that can only contain a value from 1 to 7. Where:<b...
Lab Exercise 3<br />Create a class called DayOfWeek02 with one variable containing a value from 1 to 7, where:<br />The nu...
Module 10Using Loop Constructs<br />
Agenda<br />Objectives<br />Creating while loops<br />Nested while loops<br />Developing a for loop<br />Nested for loops<...
Objectives<br />Create while loops<br />Develop for loops<br />Create do/while loops<br />
The while loop is used to perform a set of operations repeateadly till some condition is satisfied, or to perform a set of...
Creating while loops<br />public class WhileCountDown {<br />public static void main(String args[]) {<br />int count = 10;...
Nested while loops<br />public class WhileRectangle {<br />public int height = 3;<br />public int width = 10;<br />public ...
Developing a for loop<br />The for loop is used to perform a set of operations repeatdly until some condition is satisfied...
Developing a for loop<br />public class ForLoop {<br />public static void main(String[] args) {<br />int limit = 20; // Su...
Nested for loops<br />public class ForRectangle {<br />public int height = 3;<br />public int width = 10;<br />public void...
The do-while loop is used to perform a set of operations repeatedly until some condition is satisfied, or to perform a set...
Nested do/while loops<br />public class DoWhileRectangle {<br />public int height = 3;<br />public int width = 10;<br />pu...
Use the while loop to iterate indefinitely through statements and to perform the statements zero or more times.<br />• Use...
Module 11Loops Constructs Lab<br />
Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />Lab Exercise 3<br />
Objectives<br />Write classes that use while loops. <br />Write classes that use for loops.<br />Write classes that use do...
Lab Exercise 1<br />1. Write a class called Counter that contains a method called displayCount that:<br />Counts from 1 to...
Lab Exercise 2<br />1. Write a class called CounterTwo that contains a method called displayCount that:<br />Counts from 1...
Lab Exercise 3<br />1. Write a class called CounterThree containing a method called displayCount that:<br />Counts from 1 ...
Module 12Developing and Using Methods<br />
Agenda<br />Objectives<br />Introduction<br />Creating and Invoking Methods<br />Invoking a Method From a Different Class<...
Agenda<br />Creating Static Methods and Variables<br />Statics Methods and Variables in the Java API<br />When to declare ...
Objectives<br />Describe the advantages of methods and define worker and calling methods<br />Declare and invoke a method<...
Objects are self-contained entities that are made up of both data and functions that operate on the data<br />An object of...
Objects communicate by sending messages<br />getMoneyTotal and getName are examples of messages that can be sent to the pe...
Introduction<br />colour = anUmbrella.getColour();       <br />anUmbrella.setColour(&quot;blue&quot;);<br />homer.eat(donu...
Sending a message is a different concept than calling a function<br />Calling a function indicates that you have identifie...
Message<br />A message is a request for a service.<br />Method<br />A method is the implementation of the service requeste...
Introduction<br />public double getMoneyTotal() {<br />  double totalMoney = 0.0;<br />  totalMoney = totalMoney + (.25*qu...
Methods define how an object responds to messages<br />Methods define the behavior of the class<br />Syntax:<br />[modifie...
Creating and Invoking Methods<br />modifier keyword<br />return type<br />method name<br />method arguments<br />public vo...
Invoking a Method From a Different Class<br />public class ShirtTest {<br />public static void main (String args[]) {<br /...
Calling and Worker Methods<br />
Calling and Worker Methods<br />public class One {<br />public static void main(String args[]) {<br />    Two twoRef = new...
Calling and Worker Methods<br />public class CallingClass {<br />public static void main(String args[]) {<br />    WorkerC...
Calling a method in the same class is quite simple; write the calling method declaration code and include the name of the ...
Invoking a Method in the Same Class<br />public class Elevator {<br />  //instance variables<br />public void openDoor() {...
Guidelines for Invoking Methods<br />There is no limit to the number of method calls that a calling method can make.<br />...
Passing Arguments and Returning Values<br />
Passing Arguments and Returning Values<br />
Declaring Methods With Arguments<br />Example:<br />public void setFloor(int desiredFloor) {<br />while (currentFloor != d...
Invoking a Method With Arguments<br />public class GetInfo2 {<br />public static void main(String args[]) {<br />//makes a...
Invoking Methods With Arguments<br />public class Arguments {<br />public void passArguments() {<br />    subtract(  3.141...
Declaring Methods With Return Values<br />Declaration:<br />public int sum(int numberOne, int numberTwo)<br />
Example:<br />public int sum(int numberOne, int numberTwo) {<br />int sum = numberOne + numberTwo;<br />return sum;<br />}...
Receiving Return Values<br />
Receiving a Return Values<br />public class ReceiveValues {<br />public static void main(String args[]) {<br />    AddsVal...
Advantages of Method Use<br />Methods make programs more readable and easier to maintain.<br />Methods make development an...
Variables having the same value for all instances of a class are called class variables<br />Class variables are also some...
Certain methods defined in a class can operate only on class variables<br />We can invoke these methods directly using the...
Example:<br />Creating Static Methods and Variables<br />public class CountInstances {<br />public static void main (Strin...
Example:<br />Creating Static Methods and Variables<br />public class Slogan {<br />private String phrase;<br />private st...
Creating Static Methods and Variables<br />
• Examples:<br />The Math class<br />The Math class provides the important mathematical constants E and PI which are of ty...
• Examples:<br />	•<br />Statics Methods and Variables in the Java API<br />public class Get {<br />public static void mai...
• Examples:<br />	•<br />Statics Methods and Variables in the Java API<br />// Determines the roots of a quadratic equatio...
Performing the operation on an individual object or associating the variable with a specific object type is not important....
Instance variables can only be changed by non-static methods</li></li></ul><li>Uses for Method Overloading<br />Java allow...
Example overloaded methods:<br />Using Method Overloading<br />public class OverloadTest {<br />public static void main(St...
Example overloaded methods:<br />Using Method Overloading<br />public class MethodOverloadingDemo {<br />public void print...
Example overloaded methods:<br />Using Method Overloading<br />public void printToScreen(int a, int b, int c) {<br />    S...
Method Overloading and the Java API<br />
Examples:<br />public int sum(int numberOne, int numberTwo)<br />public int sum(int numberOne, int numberTwo, int numberTh...
Uses for Method Overloading<br />public class ShirtTwo {<br />public int shirtID = 0; // Default ID for the shirt<br />pub...
Uses for Method Overloading<br />public void setShirtInfo(int ID, String desc, double cost, char color,<br />int quantity)...
Uses for Method Overloading<br />public class ShirtTwoTest {<br />public static void main (String args[]) {<br />    Shirt...
Module 13Methods Lab<br />
Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />Lab Exercise 3<br />
Objectives<br />Create classes and objects<br />Invoke methods of a class<br />Overload methods in a class<br />
Lab Exercise 1<br />Write a Shirt class that has a price, item ID, and type (such as Oxford or polo).  Declare methods tha...
Lab Exercise 2 (1 of 2)<br />Define a method called sayHello in class Methodcall, provided in the skeleton code, that has ...
Lab Exercise 2 (2 of 2)<br />Make the start method of Methodcall call sayHello().<br />Define a method called addTwo that ...
Lab Exercise 3 (1 of 2)<br />Write a Java program that has the classes Area and User. Area has overloaded static methods b...
Lab Exercise 3 (2 of 2)<br />4. Write a class called User that invokes the different versions of area() in Area class with...
Module 14Implementing Encapsulation and Constructors<br />
Agenda<br />Objectives<br />Using Encapsulation<br />The public Modifier<br />The private Modifier<br />Describing Variabl...
Objectives<br />Use encapsulation to protect data<br />Create constructors to initialize objects<br />
Encapsulation separates the external aspects of an object from the internal implementation details<br />Internal changes n...
Using Encapsulation<br />
Using Encapsulation<br />
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 ...
The public Modifier<br />public int currentFloor=1;<br />public void setFloor(int desiredFloor) {<br />...<br />}<br />
Put the private modifier in front of a member variable or method if you do not want any classses outside the object’s clas...
private int currentFloor=1;<br />private void calculateCapacity() {<br />...<br />}<br />The private Modifier<br />
Describing Variable Scope<br />All variables are not available throughout a program<br />Variable scope means where a vari...
Describing Variable Scope<br />Local variables are:<br />Variables that are defined inside a method and are called local, ...
How Instance Variables and Local Variables Appear in Memory<br />
Constructors of a Class<br />The constructor is essentially used to initialize a newly created object of that particular t...
Creating Constructors<br />To define a constructor use the same name as the class and give no return type<br />publicclass...
Default Constructors<br />public class MyClass {<br />int x;<br />MyClass() {<br />    x = 10;<br />  }<br />}<br />public...
Overloading Constructors<br />public class MyClassTwo {<br />int x;<br />  MyClassTwo() {<br />    x = 10;<br />  }<br /> ...
Overloading Constructors<br />public class Student {<br />private int id = 0;<br />private String name;<br />public Studen...
Module 15<br />Implementing Encapsulation and Constructors Lab<br />
Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />
Objectives<br />Practice implementing encapsulation.<br />
Lab Exercise 1<br />Declare a Customer class with variables for a salutation (such as Ms.), first name, middle name, last ...
One takes a salutation (such as Ms.), first name, middle name, and last name</li></ul>2. Test the program with a CustomerT...
Lab Exercise 2<br />Make a class called Rectangle that represents a rectangle using private width and height variables.  M...
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 character</li></ul>2. Write the main method in another class ...
Module 16Creating and Using Arrays<br />
Agenda<br />Objectives<br />Creating One-Dimensional Arrays<br />Declaring a One-Dimensional Array<br />Instantiating a On...
Agenda<br />Declaring a Two-Dimensional Array<br />Instantiating a Two-Dimensional Array<br />Initializing a Two-Dimension...
Objectives<br />Code one-dimensional arrays<br />Set array values using the length attribute and a loop<br />Pass argument...
An array is an ordered list of values.<br />Arrays are dynamically created objects in Java code.  An array can hold a numb...
Declaring a One-Dimensional Array<br />When we declare an array variable, the code creates a variable that can hold the re...
Instantiating a One-Dimensional Array<br />You can use the new operator to construct an array.  The size of the array and ...
Initializing a One-Dimensional Array<br />Arrays are indexed beginning with 0 and ending with n-1. where n is the array si...
Initializing a One-Dimensional Array<br />• Examples:<br />int[] height = new int[11]; <br />height[0] = 69; <br />height[...
Declaring, Instantiating, and Initializing One-Dimensional Arrays<br />An array initializer is written as a comma separate...
To access a value in an array, we use the name of the array followed by the index in square brackets<br />An array element...
Examples:<br />height[2] = 72;<br />height[count] = feet * 12;<br />average = (height[0] + height[1] <br />           + he...
Storing Primitive Variables and Arrays in Memory<br />
Storing Reference Variables and Arrays in Memory<br />
Setting Array Values Using the length Attribute and a loop<br />public class Primes {<br />public static void main (String...
Using the args Array in the main Method<br />Command Line Arguments can be used to supply inputs to a program during its e...
Using the args Array in the main Method<br />public class ArgsTest {<br />public static void main (String args[]) {<br /> ...
Converting String Arguments to Other Types<br />Example:<br />int ID = Integer.parseInt(args[0]);<br />The Integer class i...
A one dimensional array stores a list of elements<br />A two-dimensional array can be thought of as a table of elements, w...
A two-dimensional array element is declared by specifying the size of each dimension separately<br />Syntax:<br />type [][...
Instantiating a Two-Dimensional Array<br />• Syntax:<br />array_identifier = new type [number_of_arrays] [length];<br />• ...
Instantiating a Two-Dimensional Array<br />Example:<br />yearlySales[0][0] = 1000;<br />yearlySales[0][1] = 1500;<br />yea...
Instantiating a Two-Dimensional Array<br />int myTable[][] = {{23, 45, 65, 34, 21, 67, 78},                  {46, 14, 18, ...
Module 17Arrays Lab<br />
Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />Lab Exercise 3<br />
Objectives<br />Create and Initialize an array <br />
Lab Exercise 1<br />Make an array of 5 integers<br />Use a for loop to set the values of the array to the index plus 10<br...
Lab Exercise 2<br />Write an Ages program that will fill an array of ten positions with the ages of ten people you know. (...
Lab Exercise 3<br />Write a program that creates and assigns values to an array of Shirt objects.  In the Shirt class, dec...
Module 18Implementing Inheritance<br />
Agenda<br />Objectives<br />Inheritance<br />What is Inherited in Java?<br />Single vs. Multiple Inheritance<br />Declarin...
Objectives<br />Define and test your use of inheritance<br />
Inheritance<br />Inheritance allows a software <br />    developer to derive a new class <br />    from an existing one<br...
As the name implies, the child inherits<br />    characteristics of the parent<br />That is, the child class inherits the ...
Java does not support multiple inheritance<br />Every Java class except Object has exactly one immediate superclass (Objec...
Declaring a subclass<br />Animal<br /><ul><li>In Java, we use thereservedwordextendstoestablishaninheritancerelationship
Syntax:</li></ul>[class_modifier] classclass_identifierextends<br />superclass_identifier<br />publicclass Animal {…}<br /...
Declaring a subclass<br />public class Animal {<br />public void speak() {<br />    System.out.println(&quot;I am a generi...
Overriding Methods<br /><ul><li>When a childclass defines a methodwiththesamename and signature as a method in theparentcl...
The new methodmusthavethesamesignature as theparent’smethod, but can have a differentbody
Thetype of theobjectexecutingthemethod determines whichversion of themethodisinvoked</li></ul>class Animal<br />  eat()<br...
Overriding Methods<br />public class MoodyObject {<br />// return the mood<br />protected String getMood() {<br />return &...
Upcoming SlideShare
Loading in...5
×

Curso de Programación Java Básico

8,515

Published on

Curso Básico de Programación Java desarrollado por ISC Raúl Oramas Bustillos. Visita www.profesorjava.com

Published in: Education
3 Comments
6 Likes
Statistics
Notes
No Downloads
Views
Total Views
8,515
On Slideshare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
447
Comments
3
Likes
6
Embeds 0
No embeds

No notes for slide

Curso de Programación Java Básico

  1. 1. PJ-050. <br />Curso de Programación Java Básico.<br />www.profesorjava.com<br />
  2. 2. Esta obra está bajo una licencia Reconocimiento 2.5 México de CreativeCommons. Para ver una copia de esta licencia, visite http://creativecommons.org/licenses/by/2.5/mx/ o envíe una carta a CreativeCommons, 171 SecondStreet, Suite 300, San Francisco, California 94105, USA. <br />
  3. 3. Acerca de:<br />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.<br />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.<br />Atte.<br />ISC Raúl Oramas Bustillos.<br />rauloramas@profesorjava.com<br />
  4. 4. CONTENIDO<br />Modulo 01: Introducción al lenguaje Java. <br />Modulo 02: Crear un programa simple en Java.<br />Modulo 03: Practica de laboratorio 01.<br />Modulo 04: Declaración e inicialización de variables.<br />Modulo 05: Práctica de laboratorio 02.<br />Modulo 06: Crear y utilizar objetos.<br />Modulo 07: Práctica de laboratorio 03.<br />Modulo 08: Operadores y estructuras selectivas.<br />
  5. 5. CONTENIDO<br />Modulo 09: Práctica de laboratorio 04.<br />Modulo 10: Estructuras repetitivas.<br />Modulo 11: Práctica de laboratorio 05.<br />Modulo 12: Métodos.<br />Modulo 13: Práctica de laboratorio 06.<br />Modulo 14: Encapsulación y constructores.<br />Modulo 15: Práctica de laboratorio 07.<br />
  6. 6. CONTENIDO<br />Modulo 16: Arreglos.<br />Modulo 17: Práctica de laboratorio 08.<br />Modulo 18: Herencia.<br />Módulo 19: Práctica de laboratorio 09.<br />
  7. 7. Module 01Introduction to the Java Programming Language<br />
  8. 8. Agenda<br />Objectives<br />What is Java?<br />Java Features<br />The Java evolution<br />Java Virtual Machine (JVM)<br />The Java execution model<br />Uses of Java<br />Programs <br />Components<br />
  9. 9. Objectives<br />Describe the history and properties of the Java programming language<br />Explain the Java execution model, including the use of bytecode and the Java virtual machine<br />Outline the types of programs and components that can be built using Java<br />
  10. 10. What is Java?<br />Java is an object-oriented programming language developed by Sun Microsystems<br />Java has a set of standardized class libraries that support predefined reusable functionality<br />Java has a runtime environment that can be embedded in Web browsers and operating systems<br />
  11. 11. Java Features<br />
  12. 12. Goals of Java<br />Object-oriented<br />Java supports software development using the notion of objects<br />Software developed using Java is composed of classes and objects<br />
  13. 13. Goals of Java<br />Network capable<br />Java supports the development of distributed applications<br />Some types of Java applications are designed to be accessed through a Web browser<br />
  14. 14. Goals of Java<br />Robust<br />Many aspects of Java promote the development of reliable software<br />Java uses a pointer model which does not allow direct access to memory; memory cannot be overwritten<br />Secure<br />Java authentication is based on public-key encryption methods<br />Java’s pointer model protects private data in objects and prevents unauthorized applications from accessing data structures<br />
  15. 15. Goals of Java<br />Multi-threaded<br />Allows your program to run more than one task at the same time<br />
  16. 16. Goals of Java<br />Compiled and interpreted<br />Source code is compiled into machine code for the Java virtual machine (JVM) by the Java compiler<br />Machine code for the JVM is also known as bytecode<br />Interpreter of the Java virtual machine interprets and executes instructions<br />Architecture neutral<br />Bytecode instructions are architecture neutral because they run on the JVM, and are not specific to an architecture<br />The same application runs on all platforms, provided the Java virtual machine is installed on that platform<br />
  17. 17. Goals of Java<br />Portable at source and binary level<br />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<br />
  18. 18. The Java evolution<br />Java is a relatively young language<br />It has been in use since 1995<br />It was originally designed for consumer electronic devices<br />Java has a huge developer base<br />There is a vast collection of libraries (from Sun and other sources)<br />
  19. 19. The Java platform<br />A platform is a development or <br /> deployment environment<br />The Java platform runs on any <br /> operating system<br />Other platforms are <br /> hardware and vendor <br /> specific<br />The Java platform provides:<br />The Java virtual <br /> machine (JVM)<br />Application Programming <br /> Interface (API)<br />
  20. 20. Java Virtual Machine (JVM)<br />A virtual machine is an executable that represents a generic<br />processor on which Java’s bytecodes run<br />
  21. 21. Uses of Java<br />Java can be used to build <br /> programs and software <br /> components<br />Programs are stand-alone <br /> entities that can run on the <br /> Java Virtual Machine<br />Applications<br />Applets<br />Components are building blocks <br /> used to create programs<br />Servlets<br />JavaServer Pages (JSPs)<br />JavaBeans<br />Enterprise JavaBeans (EJBs)<br />
  22. 22. Programs<br />Application<br />A stand-alone program that can access system resources such as files<br />Does not need to run in a Web browser<br />Is explicitly invoked through the command line or menu selection<br />The method main() is the entry point for an application<br />
  23. 23. Programs<br />Applet<br />A Java program that is embedded within a Web page; almost always graphical<br />Security limits access to system resources<br />Code executes on the client inside a Web browser<br />
  24. 24. Components<br />Servlet<br />Handles requests from the Web browser and returns responses<br />Creates dynamic content on the server<br />Runs inside an application server<br />JavaServer Page (JSP)<br />HTML page embedded with Java code<br />Creates dynamic content on the server instead of on the browser<br />Runs inside an application server<br />
  25. 25. Components<br />JavaBeans<br />Java code that has its properties, methods, and events exposed to promote reuse among developers<br />Reusable software component that can be manipulated visually in a builder tool<br />
  26. 26. Components<br />Enterprise JavaBeans (EJB)<br />Distributed objects that allow communication between Java objects in different JVMs<br />Encapsulate the business logic and model of an application<br />Run inside an application server<br />
  27. 27. Module 02Developing and Testing a Java Program<br />
  28. 28. Agenda<br />Objectives<br />Identifying the Components of a Class<br />Structuring Classes<br />Class Declaration<br />Variable Declarations and Assignments<br />Comments<br />Methods<br />Creating and Using a Test Class<br />The main method<br />Compiling and Executing (Testing) a Program<br />Executing (Testing) a Program<br />Debugging Tips<br />
  29. 29. Objectives<br />Identify the four components of a class in the Java programming language<br />Use the main method in a test class to run a Java program from the command line<br />Compile and execute a Java program<br />
  30. 30. Identifying the Components of a Class<br />Classes are the blueprints that you create to define the objects in a program.<br />
  31. 31. Comments<br />//Employee.java<br />public class Employee {<br />private String id;<br />private String lastName;<br />publicint getId() {…}<br />publicvoid setId() {…} <br />}<br />Class declaration<br />Attributes<br />Methods<br />Structuring Classes<br />The class declaration<br />Attribute variable declarations and initialization (optional)<br />Methods (optional)<br />Comments (optional)<br />
  32. 32. Structuring Classes<br />//Piano.java<br />publicclassPiano{<br />privateint keys = 88;<br />//this method displays the number of keys of piano<br />public void displayPianoInformation() {<br /> System.out.println(&quot; A piano has &quot; + keys + &quot; keys.&quot;);<br /> } //end of display method<br />}//end of class<br />The name of the class<br />It’s a class<br />The class body begin’s here<br />The class body end’s here<br />
  33. 33. Class Declaration<br />Syntax:<br />[modifier] class class_identifier<br />Example:<br />public class Piano<br />public class Cat<br />publicclass Shirt<br />//Piano.java<br />public class Shirt {<br /> //write your code here<br />} //end of class<br />
  34. 34. Class Declaration<br />public class Shirt {<br />public int shirtID = 0; // Default ID for the shirt<br />public String description = &quot;-description required-&quot;; // default<br />// The color codes are R=Red, B=Blue, G=Green, U=Unset<br />public char colorCode = ‘U’;<br />public double price = 0.0; // Default price for all shirts<br />public int quantityInStock = 0; // Default quantity for all shirts<br />// This method displays the values for an item<br />public void displayShirtInformation() {<br /> System.out.println(&quot;Shirt ID: &quot; + shirtID);<br /> System.out.println(&quot;Shirt description:&quot; + description);<br /> System.out.println(&quot;Color Code: &quot; + colorCode);<br /> System.out.println(&quot;Shirt price: &quot; + price);<br /> System.out.println(&quot;Quantity in stock: &quot; + quantityInStock);<br /> } // end of display method<br />} // end of class<br />
  35. 35. Shirt id<br />Description<br />Color Code<br />Price<br />Quantity in stock<br />Variable Declarations and Assignments<br />public int shirtID = 0; // Default ID for the shirt<br />public String description = &quot;-description required-&quot;; // default<br />// The color codes are R=Red, B=Blue, G=Green, U=Unset<br />public char colorCode = &apos;U&apos;;<br />public double price = 0.0; // Default price for all shirts<br />public int quantityInStock = 0; // Default quantity for all shirts<br />
  36. 36. Comments<br />
  37. 37. Methods<br />Syntax:<br />[modifiers] return_type method_identifier([arguments]){<br /> method_code_block<br />}<br />Example:<br />public void displayShirtInformation() {<br /> System.out.println(&quot;Shirt ID: &quot; + shirtID);<br /> System.out.println(&quot;Shirt description:&quot; + description);<br /> System.out.println(&quot;Color Code: &quot; + colorCode);<br /> System.out.println(&quot;Shirt price: &quot; + price);<br /> System.out.println(&quot;Quantity in stock: &quot; + quantityInStock);<br />} // end of display method<br />
  38. 38. Methods<br /><ul><li>Classes in Java may have methods and attributes.
  39. 39. Methods define actions that a class can perform.
  40. 40. Attributes describe the class. </li></li></ul><li>Testing and Using a Test Class<br />public classShirt {<br /> …<br /> public void displayShirtInformation()<br /> {<br /> … <br /> }<br />}<br />Example:<br />Shirt.java<br />ShirtTest.java<br />public classShirtTest {<br />public static void main (String args[]) { <br />Shirt myShirt;<br /> myShirt = newShirt();<br /> myShirt.displayShirtInformation();<br /> }<br />}<br />
  41. 41. The main method<br />Syntax:<br />public static void main (String args[])<br />The main() method is the normal entry point for Java applications<br />To create an application, you write a class definition that includes a main() method<br />
  42. 42. The main method<br />This is the definition of the class OurFirstProgram. The class definition only <br />contains the method main<br />This is the definition of the method main()<br />The keyword public indicates it is globally accesible <br />The keyword static ensures it is accesible even though no objects of the class exist<br />The keyword void indicates it does not return value<br />public class OurFirstProgram {<br />public static void main (String args[]) { <br /> System.out.println(&quot;Rome wasn’t burned in a day!&quot;);<br />}<br />}<br />
  43. 43. Compiling and Executing (Testing) a Program<br />
  44. 44. Compiling and Executing (Testing) a Program<br />1. Go the directory where the source code files are stored.<br />2. Enter the following command for each .java file you want to compile.<br />Syntax:<br />javac filename<br />Example:<br /> javac Shirt.java<br />
  45. 45. Executing (Testing) a Program<br />1. Go the directory where the class files are stored.<br />2. Enter the following for the class file that contains the main method.<br />Syntax<br />java classname<br />Example<br />java ShirtTest<br />
  46. 46. Debugging Tips<br />Check line referenced in error message<br />Check for semicolons<br />Check for even number of braces<br />
  47. 47. Module 03Writing, Compiling, and Testing a Basic Program Lab<br />
  48. 48. Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />Lab Exercise 3<br />
  49. 49. Objectives<br />Become familiar with the structure and parts of a basic Java Program. <br />
  50. 50. Lab Exercise 1<br />Create a new public class, HelloWorld, with a main method. The main method should output the string “Hello, World!”.<br />Enter the following source code:<br />publicclassHelloWorld {<br />public static void main(String[] args) {<br />System.out.println(&quot;Hello, World!&quot;);<br /> }<br />}<br />Compile and runthesourcecode.<br />
  51. 51. Lab Exercise 2 (1 of 2)<br />Create a new public class,Quotation.<br />Enter the following source code:<br />publicclassQuotation {<br /> String quote = &quot;Welcome to Sun!&quot;;<br />publicvoiddisplay() {<br />System.out.println(quote);<br /> }<br />}<br />Create a new classQuotationTest, with a main method. <br />
  52. 52. Lab Exercise 2 (2 of 2)<br />Enter the following source code:<br />publicclassQuotationTest {<br />publicclassHelloWorld {<br />public static void main(String[] args) {<br /> Quotation obj = new Quotation();<br />obj.display();<br /> }<br />}<br />5. Compile and executethesourcecode.<br />
  53. 53. Lab Exercise 3<br />1. Create a new class Car with the following methods: <br />public void start() <br />public void stop() <br />public int drive(int howlong) <br />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: <br />distance = howlong*60; <br />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(). <br />
  54. 54. Module 04Declaring, Initializing, and Using Variables<br />
  55. 55. Agenda<br />Objectives<br />Identifying Variable Use and Syntax<br />Uses for variables<br />Variable Declaration and Initialization<br />Describing Primitive Data Types<br />Integral Primitive Types<br />Floating Primitive Types<br />Textual Primitive Types<br />Logical Primitive Types<br />Naming a Variable<br />Assigning a Value to a Variable<br />Declaring and Initializing Several Variables in One Line of Code<br />Additional Ways to Declare Variables and Assign<br /> Values to Variables<br />
  56. 56. Agenda<br />Constants<br />Storing Primitive and Constants in Memory<br />Standard Mathematical Operators<br />Increment and Decrement Operators (++ and --)<br />Operator Precedence<br />Using Parenthesis<br />Casting Primitive Types<br />Implicit versus explicit casting<br />Examples (Casting)<br />
  57. 57. Objectives<br />Identify the uses for variables and define the syntax for a variable<br />List the eight Java programming language primitive data types<br />Declare, initialize, and use variables and constants according to Java programming language guidelines and coding standards<br />Modify variable values using operators<br />Use promotion and type casting<br />
  58. 58. Identifying Variable Use and Syntax<br />public class PianoKeys {<br />public static void main(String[] args) {<br /> int keys = 88;<br /> System.out.println(&quot;A piano has &quot; + keys + &quot; keys.&quot;);<br /> }<br />}<br />
  59. 59. Identifying Variable Use and Syntax<br />public class Geometry {<br />public static void main(String[] args) {<br />int sides = 7; // declaration with initialization<br /> System.out.println(&quot;A heptagon has &quot; + sides + &quot; sides.&quot;);<br /> sides = 10; // assignment statement<br /> System.out.println(&quot;A decagon has &quot; + sides + &quot; sides.&quot;);<br /> sides = 12;<br /> System.out.println(&quot;A dodecagon has &quot; + sides + &quot; sides.&quot;);<br /> }<br />}<br />
  60. 60. Identifying Variable Use and Syntax<br />public class Circle {<br />public double radio;<br />public Circle(double r) {<br />int tmp = 0;<br /> radio = r;<br /> }<br />}<br /><ul><li> Instance variables of a class are initialized with default values for the particular </li></ul> datatype<br /><ul><li> Local variables are never given a default value, they have to be explicitily initialized </li></ul> before use<br />
  61. 61. Uses for variables<br />Holding unique data for an object instance<br />Assigning the value of one variable to another<br />Representing values within a mathematical expression<br />Printing the values to the screen<br />Holding references to other objects<br />
  62. 62. Variable Declaration and Initialization<br />Syntax (attribute or instance variables):<br />[modifiers] type identifier = value;<br />Syntax (local variables):<br />type identifier;<br />Syntax (local variables)<br />type identifier = value;<br />
  63. 63. Describing Primitive Data Types<br />Integral types (byte, short, int, and long)<br />Floating point types (float and double)<br />Textual type (char)<br />Logical type (boolean)<br />
  64. 64. Integral Primitive Types<br />Signed whole numbers<br />Initialized to zero<br />
  65. 65. Integral Primitive Types<br />public class IntegralType { <br />public static void main( String args[] ) { <br />byte age = 12;<br />short idCourse = 1230;<br />int javaProgrammers = 2300000;<br />long worldPeople = 5000000000L;<br /> System.out.println(worldPeople);<br /> }<br />}<br />
  66. 66. Floating Primitive Types<br />“General” numbers (can have fractional parts)<br />Initialized to zero<br />
  67. 67. Floating Primitive Types<br />public class Tax { <br />public static void main( String args[] ) {<br />double price = 20;<br />float tax = 0.15f;<br />double total;<br /> total = price * tax;<br /> System.out.println( total );<br /> } <br />}<br />
  68. 68. Textual Primitive Types<br />Any unsigned Unicode character is a char primitive data type<br />A character is a single Unicode character between two single quotes<br />Initialized to zero (u0000)<br />
  69. 69. Textual Primitive Types<br />public class PrintChar {<br />public static void main( String args[] ) {<br />char c = &apos;x&apos;;<br />int i = c;<br /> System.out.println( &quot;Print: &quot; + c );<br /> System.out.println( &quot;Print: &quot; + i );<br /> c = 88; <br /> System.out.println( &quot;Print: &quot; + c );<br /> }<br />}<br />
  70. 70. Logical Primitive Types<br />boolean values are distinct in Java<br />An int value can NOT be used in place of a boolean<br />A boolean can store either true or false<br />Initialized to false<br />
  71. 71. Logical Primitive Types<br />public class CatDog {<br />public static void main( String args[] ) {<br />boolean personWithDog = true;<br />boolean personWithCat = false;<br /> System.out.println( &quot;personWithDog is &quot; + personWithDog );<br /> System.out.println( &quot;personWithCat is &quot; + personWithCat );<br /> } <br />}<br />
  72. 72. Rules:<br />Variable identifiers must start with either an uppercase or lowercase letter, an underscore (_), or a dollar sign ($).<br />Variable identifiers cannot contain punctuation, spaces, or dashes.<br />Java keywords cannot be used.<br />Guidelines:<br />Begin each variable with a lowercase letter; subsequent words should be capitalized, such as myVariable.<br />Chose names that are mnemonic and that indicate to the casual observer the intent of the variable.<br />Naming a Variable<br />
  73. 73. Assigning a Value to a Variable<br />Example:<br />double price = 12.99;<br />Example (boolean):<br />boolean isOpen = false;<br />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.<br />A boolean cannot be assigned any type other than boolean.<br />
  74. 74. Declaring and Initializing Several Variables in One Line of Code<br />Syntax:<br />type identifier = value [, identifier = value];<br />Example:<br />double price = 0.0, wholesalePrice = 0.0;<br />int miles = 0, //One mile is 8 furlong<br /> furlong = 0, //One furlong is 220 yards<br /> yards = 0, //One yard is 3 feet<br /> feet = 0;<br />
  75. 75. Additional Ways to Declare Variables and Assign Values to Variables<br />Assigning literal values:<br />int ID = 0;<br />float pi = 3.14F;<br />char myChar = ’G’;<br />boolean isOpen = false;<br />Assigning the value of one variable to another variable:<br />int ID = 0;<br />int saleID = ID;<br />
  76. 76. Additional Ways to Declare Variables and Assign Values to Variables<br />Assigning the result of an expression to integral, floating point, or Boolean variables<br />float numberOrdered = 908.5F;<br />float casePrice = 19.99F;<br />float price = (casePrice * numberOrdered);<br />int hour = 12;<br />boolean isOpen = (hour &gt; 8);<br />Assigning the return value of a method call to a variable<br />
  77. 77. Constants<br />Variable (can change):<br />double salesTax = 6.25;<br />Constant (cannot change):<br />final double SALES_TAX = 6.25;<br />final int FEET_PER_YARD = 3;<br />final double MM_PER_INCH = 25.4;<br />A final variable may not modified once it has been assigned a value.<br />Guideline – Constants should be capitalized with words separated by an underscore (_).<br />
  78. 78. Storing Primitive and Constants in Memory<br />
  79. 79. Standard Mathematical Operators<br />
  80. 80. Standard Mathematical Operators<br />
  81. 81. Increment and Decrement Operators (++ and --)<br />
  82. 82. Increment and Decrement Operators (++ and --)<br />
  83. 83. Increment and Decrement Operators (++ and --)<br />
  84. 84. Operator Precedence<br />Rules of precedence:<br />1. Operators within a pair of parentheses<br />2. Increment and decrement operators<br />3. Multiplication and division operators, evaluated from left to right<br />4. Addition and subtraction operators, evaluated from left to right<br />Example of need for rules of precedence (is the answer 34 or 9?):<br />c = 25 - 5 * 4 / 2 - 10 + 4;<br />
  85. 85. Operator Precedence<br />
  86. 86. Using Parenthesis<br />Examples:<br />c = (((25 - 5) * 4) / (2 - 10)) + 4;<br />c = ((20 * 4) / (2 - 10)) + 4;<br />c = (80 / (2 - 10)) + 4;<br />c = (80 / -8) + 4;<br />c = -10 + 4;<br />c = -6;<br />
  87. 87. Casting Primitive Types<br />Java is a strictly typed language<br />Assigning the wrong type of value to a variable could result in a compile error or a JVM exception<br />Casting a value allows it to be treated as another type<br />The JVM can implicitly promote from a narrower type to a wider type<br />To change to a narrower type, you must cast explicitly<br />
  88. 88. Implicit versus explicit casting<br />Casting is automatically done when no loss of information is possible<br />An explicit cast is required when there is a &quot;potential&quot; loss of accuracy<br />
  89. 89. Examples (Casting)<br />byte b = 3;<br />int x = b;<br />byte a;<br />int b = 3;<br />a = (byte)b;<br />int num1 = 53; // 32 bits of memory to hold the value<br />int num2 = 47; // 32 bits of memory to hold the value<br />byte num3; // 8 bits of memory reserved<br />num3 = (num1 + num2); // causes compiler error<br />
  90. 90. Examples (Casting)<br />int num1 = 53; // 32 bits of memory to hold the value<br />int num2 = 47; // 32 bits of memory to hold the value<br />byte num3; // 8 bits of memory reserved<br />num3 = (byte)(num1 + num2); // no data loss<br />
  91. 91. 1<br />1<br />0<br />0<br />0<br />0<br />0<br />0<br />1<br />0<br />0<br />0<br />0<br />0<br />0<br />0<br /> b = (byte)s<br />1<br />1<br />0<br />0<br />0<br />0<br />0<br />0<br />Examples (Casting)<br />short s = 259;<br />byte b = s; // Compiler error<br />System.out.println(“s = ” + s + “, b = ” + b);<br />short s = 259;<br />byte b = (byte)s; // Explicit cast<br />System.out.println(“s = ” + s + “, b = ” + b);<br />
  92. 92. Examples (Casting)<br />public class ExplicitCasting { <br />public static void main( String args[] ) {<br />byte b;<br />int i = 266; //0000000100001010<br /> b = (byte)i; // 00001010<br /> System.out.println(&quot;byte to int is &quot; + b );<br /> } <br />}<br />
  93. 93. Module 05Using Primitive Types, Operators and Type Casting, in a Program Lab<br />
  94. 94. Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />Lab Exercise 3<br />
  95. 95. Objectives<br />Write the code to declare, assign values to, and use variables in a program<br />Practice using operators and type-casting<br />
  96. 96. Lab Exercise 1<br />1. Create a class called Rectangle.java, define a variable called length of type int and define another variable called width of type int. <br />2. Assign lengthequals to 10 and width equals to 2. <br />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. <br />public class Rectangle {<br />int width = 2;<br />int length = 10;<br />public static void main(String[] args) {<br /> Rectangle rectangle = new Rectangle();<br />int area = rectangle.length * rectangle.width;<br /> System.out.println(&quot;Area : &quot; + area);<br /> }<br />}<br />4. Compile an run the program.<br />
  97. 97. Lab Exercise 2<br />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.<br />Useful Tips:<br />Create a class called Calculator.<br />Declare two integer variables, and initialize them to two integer values (e.g. 10 and 5).<br />Add these two variables, and print the result to the standard output.<br />Subtract the second variable from the first, and print the result to the standard output.<br />Multiply these two variables, and print the result to the standard output.<br />Divide the first variable by the second variable, and print the result to the standard output.<br />
  98. 98. Lab Exercise 3<br />Write a program called Temperature containing a temperature in Fahrenheit and a method called calculateCelsius. Follow these steps to create a Temperature class:<br />Write a calculateCelsius method that converts a Fahrenheit value to a Celsius value and prints the Celsius value.<br />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.) <br />Test the program using the TemperatureTest class.<br />
  99. 99. Module 06Creating and Using Objects<br />
  100. 100. Agenda<br />Objectives<br />Introduction<br />Declaring Object References, Instantiating Objects, and Initializing Object References<br />Declaring Object Reference Variables<br />Instantiating an Object<br />Initializing Object Reference Variables<br />Using an Object Reference Variable to Manipulate Data<br />Storing Object Reference Variables in Memory<br />Assigning an Object Reference From One Variable to Another<br />Strings<br />Concatenating Strings<br />Comparing Strings<br />String Messages<br />StringBuffer<br />
  101. 101. Objectives<br />Declare, instantiate, and initialize object reference variables<br />Compare how object reference variables are stored in relation to primitive variables<br />Use a class (the String class) included in the Java SDK<br />
  102. 102. Introduction<br />
  103. 103. The phrase &quot;to create an <br />instance of an object“ means <br />to create a copy of this object <br />in the computer&apos;s memory<br />according to the definition of <br />its class.<br />Introduction<br />
  104. 104. Introduction<br /> Class Object (Instance)<br />
  105. 105. Declaring Object References, Instantiating Objects, and Initializing Object References<br />A primitive variable holds the value of the data item, while a reference variable holds the<br />memory address where the data item (object) is stored.<br />
  106. 106. Declaring Object References, Instantiating Objects, and Initializing Object References<br />publicclassShirtTest {<br />publicstaticvoidmain (Stringargs[]) {<br />ShirtmyShirt = newShirt();<br />myShirt.displayShirtInformation();<br /> }<br />}<br />publicclassShirt {<br />publicintshirtID = 0; <br />publicStringdescription = &quot;-descriptionrequired-&quot;; <br />publiccharcolorCode = ‘U’;<br />publicdoubleprice = 0.0; <br />publicintquantityInStock = 0; <br />publicvoiddisplayShirtInformation() {<br />System.out.println(&quot;Shirt ID: &quot; + shirtID);<br />System.out.println(&quot;Shirtdescription:&quot; + description);<br />System.out.println(&quot;Color Code: &quot; + colorCode);<br />System.out.println(&quot;Shirtprice: &quot; + price);<br />System.out.println(&quot;Quantity in stock: &quot; + quantityInStock);<br /> }<br />}<br />
  107. 107. Declaring Object Reference Variables<br />Syntax:<br />Classname identifier;<br />• Example:<br />Shirt myShirt;<br />Circle x;<br />Cat gardfiel;<br />
  108. 108. Instantiating an Object<br />Syntax:<br />new Classname();<br />
  109. 109. Initializing Object Reference Variables<br />The assignment operator<br />• Examples:<br />myShirt = new Shirt();<br />
  110. 110. Using an Object Reference Variable to Manipulate Data<br />public class Shirt {<br />public int shirtID = 0; <br />public String description = &quot;-description required-&quot;; <br /> public char colorCode = ‘U’;<br />public double price = 0.0; <br />public int quantityInStock = 0; <br /> public void displayShirtInformation() {<br /> System.out.println(&quot;Shirt ID: &quot; + shirtID);<br /> System.out.println(&quot;Shirt description:&quot; + description);<br /> System.out.println(&quot;Color Code: &quot; + colorCode);<br /> System.out.println(&quot;Shirt price: &quot; + price);<br /> System.out.println(&quot;Quantity in stock: &quot; + quantityInStock);<br /> }<br />}<br />public class ShirtTest2 {<br />public static void main (String args[]) {<br /> Shirt myShirt;<br /> myShirt = new Shirt();<br /> myShirt.size = ‘L’;<br /> myShirt.price = 29.99F;<br /> myShirt.longSleeved = true;<br /> myShirt.displayShirtInformation();<br /> }<br />}<br />Declare a reference.<br />Create the object.<br />Assign values.<br />
  111. 111. Using an Object Reference Variable to Manipulate Data<br />public class ShirtTestTwo {<br />public static void main (String args[]) {<br />Shirt myShirt = new Shirt();<br /> Shirt yourShirt = new Shirt();<br />myShirt.displayShirtInformation();<br /> yourShirt.displayShirtInformation();<br />myShirt.colorCode=’R’;<br /> yourShirt.colorCode=’G’;<br />myShirt.displayShirtInformation();<br /> yourShirt.displayShirtInformation();<br /> }<br /> }<br />
  112. 112. Using an Object Reference Variable to Manipulate Data<br />public class Circle {<br />privateint radius; <br />}<br />public class ShapeTester {<br />public static void main(String args[]) {<br />Circle  x;         <br /> x = new Circle(); System.out.println(x); <br /> } <br />}<br />
  113. 113. Using an Object Reference Variable to Manipulate Data<br />public class Circle {<br />privateint radius; <br />}<br />public class Rectangle {<br />publicdouble width = 10.128;<br />publicdouble height = 5.734; <br />}<br />public class ShapeTester {<br />public static void main(String args[]) {<br /> Circle  x;   <br /> Rectangle y;      <br /> x = new Circle(); <br /> y = new Rectangle(); <br /> System.out.println(x + &quot;   &quot; + y); <br /> } <br />}<br />
  114. 114. Storing Object Reference Variables in Memory<br />public static void main (String args[]) {<br />intcounter;<br /> counter = 10;<br /> Shirt myShirt = new Shirt();<br /> Shirt yourShirt = new Shirt();<br />}<br />
  115. 115. Assigning an Object Reference From One Variable to Another<br />1 Shirt myShirt = new Shirt();<br />2 Shirt yourShirt = new Shirt();<br />3 myShirt = yourShirt;<br />
  116. 116. Assigning an Object Reference From One Variable to Another<br />public class Cat {<br /> …<br /> …<br />}<br />Cat A = new Cat();<br />Cat B = A;<br />
  117. 117. Assigning an Object Reference From One Variable to Another<br />
  118. 118. Any number of characters between double quotes is a String:<br />String can be initialized in other ways:<br />Strings<br />
  119. 119. Strings are objects. These objects are inmmutable. Their value, once assigned, can never be changed. For instance:<br />String msg = “Hello”;<br />mgs += “ World”;<br />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.<br />Strings<br />
  120. 120. The + operator concatenates Strings:<br />String a = “This” + “ is a ” + “String”;<br />Primitive types used in a call to println are automatically converted to Strings<br />System.out.println(&quot;answer = &quot; + 1 + 2 + 3); <br />System.out.println(&quot;answer = &quot; + (1+2+3));<br />If one of the operands is a String and the other not, the Java code <br />tries to convert the other operand to a String representation. <br />Concatenating Strings<br />
  121. 121. oneString.equals(anotherString)<br />Tests for equivalence<br />Returns true or false<br />oneString.equalsIgnoreCase(anotherString)<br />Case insensitive test for equivalence<br />Returns true or false<br />oneString == anotherString is problematic<br />String name = &quot;Joe&quot;;<br />if(&quot;Joe&quot;. equals(name))<br /> name += &quot; Smith&quot;;<br />boolean same = &quot;Joe&quot;.equalsIgnoreCase(&quot;joe&quot;);<br />Comparing Strings<br />
  122. 122. Strings are objects; objects respond to messages<br />Use the dot (.) operator to send a message<br />String is a class<br />String name = “Johny Flowers”;<br />name.toLowerCase(); //”johny flowers”<br />name.toUpperCase(); //”JOHNY FLOWERS”<br />“ Johny Flowers ”.trim(); //”Johny Flowers”<br />“Johny Flowers”.indexOf(‘h’); //2<br />“Johny Flowers”.lenght(); //13<br />“Johny Flowers”.charAt(2); //’h’<br />“Johny Flowers”.substring(5); //Flowers<br />“Johny Flowers”.substring(6,8); //”fl”<br />String Messages<br />
  123. 123. StringBuffer is a more efficient mechanism for building strings<br />String concatenation <br />Can get very expensive<br />Is converted by most compilers into a StringBuffer implementation<br />If building a simple String, just concatenate <br />If building a String through a loop, use a StringBuffer<br />StringBuffer buffer = new StringBuffer(15);<br />buffer.append(“This is”);<br />buffer.append(“String”);<br />buffer.insert(7,“a”);<br />buffer.append(“.”);<br />System.out.println(buffer.length()); //17<br />String output = buffer.toString();<br />System.out.println(output); //”This is a String”<br />StringBuffer<br />
  124. 124. Module 07Objects and Strings Lab<br />
  125. 125. Agenda<br />Objectives<br />Lab Exercise 1<br />
  126. 126. Objectives<br />Create instances of a class and manipulate these instances in several ways.<br />Make use of the String class and its methods<br />
  127. 127. Lab Exercise 1 (1 of 5)<br />Create a class called BankAccount.<br />Enter the following code:<br />public class BankAccount {<br />// these are the instance variables<br />private int balance;<br />private int accountNumber;<br />private String accountName;<br />// this is the constructor<br />public BankAccount(int num, String name) {<br /> balance = 0;<br /> accountNumber = num;<br /> accountName = name;<br /> }<br />
  128. 128. Lab Exercise 1 (2 of 5)<br /> // the code for the methods starts here<br />public int getBalance() { return balance;}<br />public void credit(int amount){balance=balance+amount; }<br />public void debit(int amount) {balance = balance - amount;}<br />public String toString() {<br /> return (&quot;####################### &quot; + &quot;Account number: “<br /> + accountNumber + &quot; Account name: &quot; <br /> + accountName<br /> + &quot; Balance: $&quot; + balance <br /> + &quot; #######################&quot;);<br /> }<br />}<br />
  129. 129. Lab Exercise 1 (3 of 5)<br />3. Create a BankAccount in another Test program (BankTest). The instance is named savings. For example:<br />BankAccount savings = newBankAccount(121,&quot;John Doe&quot;);<br />4. Create another BankAccount instance named cheque. For example:<br />BankAccountcheque = newBankAccount(122,&quot;John Perez&quot;);<br />
  130. 130. Lab Exercise 1 (4 of 5)<br />5. Call methods of the objects and see what effect they have. <br />savings.credit(1000); <br />System.out.println(savings);<br />cheque.credit(500); <br />System.out.println(cheque);<br />cheque.credit(1500); <br />System.out.println(cheque);<br />cheque.debit(200); <br />System.out.println(cheque);<br />
  131. 131. Lab Exercise 1 (5 of 5)<br />6. Assign one object reference to another object reference by assigning savings to a new instance named myAccount<br />BankAccount myAccount;<br />myAccount = cheque;<br />System.out.println(myAccount);<br />7. Make sure that you understand what is happening here!<br />
  132. 132. Module 08Using Operators and Decision Constructs<br />
  133. 133. Agenda<br />Objectives<br />Using Relational and Conditional Operators<br />Creating if and if/else Constructs<br />Using the switch Construct<br />
  134. 134. Objectives<br />Identify relational and conditional operators<br />Examine if and if/else constructs<br />Use the switch constructs<br />
  135. 135. Using Relational and Conditional Operators<br />The Java language provides several means of altering the sequential flow of a program<br />
  136. 136. Relational operators<br /><ul><li>Relational operators are used for comparing two values stored in a variable.</li></li></ul><li>Conditional operators<br /><ul><li>Usually conditional operators are used in combination with relational operators to determine if a condition is true of false
  137. 137. These operators require two operators. Hence they are called binary operators</li></li></ul><li>The if Construct<br />An if construct lets you perform certain statements if a condition is true<br />Syntax:<br />if (boolean_expression) {<br /> code_block;<br />} // end of if construct<br />// program continues here<br />We cannot use numerica values to represent true and false as we do in C/C++<br />
  138. 138. The if Construct<br />public class Coffee {<br />private static inthour=9;<br />public static void main(String args[]) {<br />if(hour&gt;=8 && hour&lt;12) { <br /> System.out.println(“Drink coffee”);<br /> } <br /> }<br />}<br />
  139. 139. The if/else Construct<br />Syntax:<br />if (boolean_expression) {<br /> code_block;<br />} // end of if construct<br />else {<br /> code_block;<br />} // end of else construct<br />// program continues here<br />The curly braces are optional if the body is limited to a single statement.<br />We cannot use numeric values to represent true and false<br />if(x==5) {} // compiles, executes body id x is equals to 5<br />if(x=0) {} // does not compiles<br />if(x=true) {} // compile<br />The else part in the if/else statement is optional. The curly braces are optional if the body is limited to a single statement<br />
  140. 140. The if/else Construct<br />public class CoffeeIfElse {<br />private static inthour=9;<br />public static void main(String args[]) {<br />if(hour&gt;=8 && hour&lt;12) { <br /> System.out.println(“Drink coffee”);<br /> }<br />else {<br /> System.out.println(“Drink tea”);<br /> }<br /> //continue here<br /> }<br />}<br />
  141. 141. The if/else Construct<br />public class IfElseDemo {<br />public static void main(String[] args) {<br />int testscore = 76;<br />char grade;<br />if (testscore &gt;= 90) {<br /> grade = &apos;A&apos;;<br /> } else if (testscore &gt;= 80) {<br /> grade = &apos;B&apos;;<br /> } else if (testscore &gt;= 70) {<br /> grade = &apos;C&apos;;<br /> } else if (testscore &gt;= 60) {<br /> grade = &apos;D&apos;;<br /> } else {<br /> grade = &apos;F&apos;;<br /> }<br /> System.out.println(&quot;Grade = &quot; + grade);<br /> }<br />}<br />
  142. 142. Tests a single variable for several alternative values and executes the corresponding case<br />Any case without break will “fall through”<br />Next case will also be executed<br />default clause handles values not explicitly handled by a case<br />Using the switch Construct<br />switch (day) { <br />case 0: <br />case 1: <br /> rule = “weekend”;<br />break;<br />case 2:<br /> …<br />case 6:<br /> rule = “weekday”;<br />break;<br />default:<br /> rule = “error”;<br />} <br />if (day == 0 || day == 1) {<br /> rule = “weekend”;<br />} else if (day &gt; 1 && day &lt;7) {<br /> rule = “weekday”;<br />} else {<br /> rule = error;<br />}<br />
  143. 143. The argument passed to the switch and case statements should be int, short, char, or byte.<br />Syntax:<br />switch (variable) {<br />case literal_value:<br /> code_block;<br /> [break;]<br />case another_literal_value:<br />code_block;<br />[break;]<br />[default:]<br /> code_block;<br />}<br />Note that the control comes to the default statement only if none of the cases match.<br />Using the switch Construct<br />
  144. 144. Using the switch Construct<br />public class SwitchDemo {<br />public static void main(String[] args) {<br />int month = 8;<br />switch (month) {<br />case 1:System.out.println(&quot;January&quot;);break;<br />case 2:System.out.println(&quot;February&quot;);break;<br />case 3:System.out.println(&quot;March&quot;);break;<br />case 4:System.out.println(&quot;April&quot;);break;<br />case 5:System.out.println(&quot;May&quot;);break;<br />case 6:System.out.println(&quot;June&quot;);break;<br />case 7:System.out.println(&quot;July&quot;);break;<br />case 8:System.out.println(&quot;August&quot;);break;<br />case 9:System.out.println(&quot;September&quot;);break;<br />case 10:System.out.println(&quot;October&quot;);break;<br />case 11:System.out.println(&quot;November&quot;);break;<br />case 12:System.out.println(&quot;December&quot;);break;<br />default:System.out.println(&quot;Invalid month.&quot;);break;<br /> }<br /> }<br />}<br />
  145. 145. Module 09if/switch Lab<br />
  146. 146. Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />Lab Exercise 3<br />
  147. 147. Objectives<br />Create classes that use if and if/else constructs.<br />Using the switch construct in decision-making programs<br />
  148. 148. Lab Exercise 1<br />Write a program called Division that does the following:<br />Takes three command-line arguments<br />Divides the third number by the first and prints the result<br />Divides the third number by the second and prints the result<br />Checks to be sure the first and the second numbers are not equal to zero.<br />
  149. 149. Lab Exercise 2 <br />Create a class called DayOfWeek with one variable that can only contain a value from 1 to 7. Where:<br />The number 1 represents Monday (beginning of the week).<br />The number 7 represents Sunday (end of the week).<br />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.<br />
  150. 150. Lab Exercise 3<br />Create a class called DayOfWeek02 with one variable containing a value from 1 to 7, where:<br />The number 1 represents Monday (beginning of the week).<br />The number 7 represents Sunday (end of the week).<br />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.<br />
  151. 151. Module 10Using Loop Constructs<br />
  152. 152. Agenda<br />Objectives<br />Creating while loops<br />Nested while loops<br />Developing a for loop<br />Nested for loops<br />Coding a do/while loop<br />Nested do/while loops<br />Comparing loop constructs<br />
  153. 153. Objectives<br />Create while loops<br />Develop for loops<br />Create do/while loops<br />
  154. 154. 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<br />Syntax:<br />while(boolean_expression) {<br /> code_block;<br />} // end of while construct<br />// program continues here<br />Creating while loops<br />The body of the while loop is executed only if the expression is true<br />
  155. 155. Creating while loops<br />public class WhileCountDown {<br />public static void main(String args[]) {<br />int count = 10;<br />while(count&gt;=0) {<br /> System.out.println(count);<br /> count--;<br /> }<br /> System.out.println(“Blast Off.”);<br /> }<br />}<br />
  156. 156. Nested while loops<br />public class WhileRectangle {<br />public int height = 3;<br />public int width = 10;<br />public void displayRectangle() {<br />int colCount = 0;<br />int rowCount = 0;<br />while (rowCount &lt; height) {<br /> colCount=0;<br />while (colCount &lt; width) {<br /> System.out.print(“@”);<br />colCount++;<br /> }<br /> System.out.println();<br /> rowCount++;<br /> }<br /> }<br />}<br />
  157. 157. Developing a for loop<br />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<br />Syntax:<br />for(initialize[,initialize]; boolean_expression; update[,update]) {<br /> code_block;<br />}<br />There can be more than one initialization expression and more than one iteration expression, but only one test expression<br />
  158. 158. Developing a for loop<br />public class ForLoop {<br />public static void main(String[] args) {<br />int limit = 20; // Sum from 1 to this value<br />int sum = 0; // Accumulate sum in this variable<br />// Loop from 1 to the value of limit, adding 1 each cycle<br />for(int i = 1; i &lt;= limit; i++) {<br /> sum += i; // Add the current value of i to sum<br /> }<br /> System.out.println(“sum = “ + sum);<br /> }<br />}<br />
  159. 159. Nested for loops<br />public class ForRectangle {<br />public int height = 3;<br />public int width = 10;<br />public void displayRectangle() {<br />for (int rowCount = 0; rowCount &lt; height; rowCount++) {<br />for (int colCount = 0; colCount &lt; width; colCount++){<br /> System.out.print(“@”);<br /> }<br /> System.out.println();<br />}<br /> }<br />}<br />
  160. 160. 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<br />Syntax:<br />do {<br /> code_block;<br />}<br />while(boolean_expression);// Semicolon is<br />// mandatory.<br />Coding a do/while loop<br />The body of the do/while is executed at least once because the test expression is evaluated only after executing the loop body.<br />
  161. 161. Nested do/while loops<br />public class DoWhileRectangle {<br />public int height = 3;<br />public int width = 10;<br />public void displayRectangle() {<br />int rowCount = 0;<br />int colCount = 0;<br />do {<br /> colCount = 0;<br />do {<br /> System.out.print(“@”);<br /> colCount++; <br /> }while (colCount &lt; width);<br /> System.out.println();<br /> rowCount++;<br /> }while (rowCount &lt; height);<br /> }<br />} <br />
  162. 162. Use the while loop to iterate indefinitely through statements and to perform the statements zero or more times.<br />• Use the do/while loop to iterate indefinitely through statements and to perform the statements one or more times.<br />• Use the for loop to step through statements a predefined number of times.<br />Comparing loop constructs<br />
  163. 163. Module 11Loops Constructs Lab<br />
  164. 164. Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />Lab Exercise 3<br />
  165. 165. Objectives<br />Write classes that use while loops. <br />Write classes that use for loops.<br />Write classes that use do/while loops.<br />
  166. 166. Lab Exercise 1<br />1. Write a class called Counter that contains a method called displayCount that:<br />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<br />Displays the count<br />2. Compile yourprogram.<br />3. Use the CounterTest.class file to test your program.<br />
  167. 167. Lab Exercise 2<br />1. Write a class called CounterTwo that contains a method called displayCount that:<br />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.<br />Displays the count<br />2. Compile your program.<br />3. Use the CounterTwoTest.class file to test your program. <br />
  168. 168. Lab Exercise 3<br />1. Write a class called CounterThree containing a method called displayCount that:<br />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<br />Displays the count<br />2. Compile your program.<br />3. Use the CounterThreeTest.class file to test your program.<br />
  169. 169. Module 12Developing and Using Methods<br />
  170. 170. Agenda<br />Objectives<br />Introduction<br />Creating and Invoking Methods<br />Invoking a Method From a Different Class<br />Calling and Worker Methods<br />Invoking a Method in the Same Class<br />Guidelines for Invoking Methods<br />Passing Arguments and Returning Values<br />Declaring Methods With Arguments<br />Invoking a Method With Arguments<br />Declaring Methods With Return Values<br />Returning a Value<br />Receiving Return Values<br />Advantages of Method Use<br />
  171. 171. Agenda<br />Creating Static Methods and Variables<br />Statics Methods and Variables in the Java API<br />When to declare a static method or variable<br />Uses for Method Overloading<br />Using Method Overloading<br />Method Overloading and the Java API<br />
  172. 172. Objectives<br />Describe the advantages of methods and define worker and calling methods<br />Declare and invoke a method<br />Compare object and static methods<br />Use overloaded methods<br />
  173. 173. Objects are self-contained entities that are made up of both data and functions that operate on the data<br />An object often models the real world<br />Data is encapsulated by objects<br />Encapsulation means enclosing, hiding, or containing<br />Implementation details of functions are also encapsulated<br />Introduction<br />
  174. 174. Objects communicate by sending messages<br />getMoneyTotal and getName are examples of messages that can be sent to the person object, Jim<br />Sending messages is the only way that objects can communicate<br />Introduction<br />
  175. 175. Introduction<br />colour = anUmbrella.getColour();       <br />anUmbrella.setColour(&quot;blue&quot;);<br />homer.eat(donuts);<br />
  176. 176. Sending a message is a different concept than calling a function<br />Calling a function indicates that you have identified the actual implementation code that you want to run at the time of the function call<br />Sending a message is just a request for a service from an object; the object determines what to do<br />Different objects may interpret the same message differently<br />Introduction<br />
  177. 177. Message<br />A message is a request for a service.<br />Method<br />A method is the implementation of the service requested by the message<br />In procedural languages, these are known as procedures or functions<br />A message is typically sent from one object to another; it does not imply what actual code will be executed<br />A method is the code that will be executed in response to a message that is sent to an object<br />Introduction<br />
  178. 178. Introduction<br />public double getMoneyTotal() {<br /> double totalMoney = 0.0;<br /> totalMoney = totalMoney + (.25*quarters);<br /> totalMoney = totalMoney + (.10*dimes);<br /> totalMoney = totalMoney + (.05*nickels);<br /> totalMoney = totalMoney + (.01*pennies);<br />return totalMoney;<br />}<br />
  179. 179. Methods define how an object responds to messages<br />Methods define the behavior of the class<br />Syntax:<br />[modifiers] return_type method_identifier ([arguments])<br />{<br /> method_code_block<br />}<br />Creating and Invoking Methods<br />
  180. 180. Creating and Invoking Methods<br />modifier keyword<br />return type<br />method name<br />method arguments<br />public void displayShirtInformation( ) {<br /> System.out.println(&quot;Shirt ID: &quot; + shirtID);<br /> System.out.println(&quot;Shirt description:&quot; + description);<br /> System.out.println(&quot;Color Code: &quot; + colorCode);<br /> System.out.println(&quot;Shirt price: &quot; + price);<br /> System.out.println(&quot;Quantity in stock: &quot; <br /> + quantityInStock);<br />} // end of display method<br />
  181. 181. Invoking a Method From a Different Class<br />public class ShirtTest {<br />public static void main (String args[]) {<br /> Shirt myShirt;<br /> myShirt = new Shirt();<br />myShirt.displayShirtInformation();<br /> }<br />}<br />public void displayShirtInformation() {<br /> System.out.println(&quot;Shirt ID: &quot; + shirtID);<br /> System.out.println(&quot;Shirt description:&quot; + description);<br /> System.out.println(&quot;Color Code: &quot; + colorCode);<br /> System.out.println(&quot;Shirt price: &quot; + price);<br /> System.out.println(&quot;Quantity in stock: &quot; + quantityInStock);<br />} // end of display method<br />
  182. 182. Calling and Worker Methods<br />
  183. 183. Calling and Worker Methods<br />public class One {<br />public static void main(String args[]) {<br /> Two twoRef = new Two();<br />twoRef.workerMethod();<br /> }<br />}<br />Calling <br />method<br />public class Two {<br />public void workerMethod() {<br />int i = 42;<br />int j = 24;<br /> }<br />}<br />Worker <br />method<br />
  184. 184. Calling and Worker Methods<br />public class CallingClass {<br />public static void main(String args[]) {<br /> WorkerClass workerObject = new WorkerClass();<br /> workerObject.worker1();<br /> workerObject.worker2();<br /> }<br />}<br />public class WorkerClass {<br />public void worker1() {<br />int id = 44559;<br /> System.out.println(“The id is ” + id);<br /> }<br />public void worker2() {<br />float price = 29.99f;<br /> System.out.println(“The price is ” + price);<br /> }<br />}<br />
  185. 185. 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.<br />Invoking a Method in the Same Class<br />public class DisclaimerOneFile {<br />public void callMethod() {<br />//calls the printDisclaimer method<br /> printDisclaimer();<br /> }<br /> public void printDisclaimer() {<br /> System.out.println(“Hello Culiacan”);<br /> }<br />}<br />
  186. 186. Invoking a Method in the Same Class<br />public class Elevator {<br /> //instance variables<br />public void openDoor() {…}<br /> public void closeDoor() {…}<br />public void goUp() {…}<br />public void goDown() {…}<br /> public void setFloor(int desiredFloor) {<br />while (currentFloor != desiredFloor)<br />if (currentFloor &lt; desiredFloor) {<br /> goUp();<br /> } <br /> else {<br /> goDown();<br /> } <br /> }<br /> public int getFloor() {…}<br />public boolean checkDoorStatus() {…}<br />}<br />
  187. 187. Guidelines for Invoking Methods<br />There is no limit to the number of method calls that a calling method can make.<br />The calling method and the worker method can be in the same class or in different classes.<br />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.<br />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).<br />
  188. 188. Passing Arguments and Returning Values<br />
  189. 189. Passing Arguments and Returning Values<br />
  190. 190. Declaring Methods With Arguments<br />Example:<br />public void setFloor(int desiredFloor) {<br />while (currentFloor != desiredFloor) {<br />if (currentFloor &lt; desiredFloor) {<br /> goUp();<br /> }<br />else {<br /> goDown();<br /> }<br /> }<br />}<br />• Example:<br />public void multiply(int NumberOne, int NumberTwo)<br />
  191. 191. Invoking a Method With Arguments<br />public class GetInfo2 {<br />public static void main(String args[]) {<br />//makes a Shirt object<br /> Shirt2 theShirt = new Shirt2();<br />//calls the printInfo method<br />theShirt.printInfo(44339,’L’);<br />}<br />public class Shirt2 {<br />int id;<br />char size;<br />public void printInfo(int shirtId, char shirtSize) {<br /> id = shirtId; //assign arguments to variables<br /> size = shirtSize;<br /> System.out.println(id);<br /> System.out.println(size);<br /> }<br />}<br />
  192. 192. Invoking Methods With Arguments<br />public class Arguments {<br />public void passArguments() {<br /> subtract( 3.14159f, 9f );<br /> }<br />public void subtract( float first , float second ) {<br />if((first-second)&gt;=0) {<br /> System.out.println(“Positive”);<br /> }<br />else {<br /> System.out.println(“Negative”);<br /> }<br /> }<br />}<br />
  193. 193. Declaring Methods With Return Values<br />Declaration:<br />public int sum(int numberOne, int numberTwo)<br />
  194. 194. Example:<br />public int sum(int numberOne, int numberTwo) {<br />int sum = numberOne + numberTwo;<br />return sum;<br />}<br />Example:<br />public int getFloor() {<br />return currentFloor;<br />}<br />Returning a Value<br />
  195. 195. Receiving Return Values<br />
  196. 196. Receiving a Return Values<br />public class ReceiveValues {<br />public static void main(String args[]) {<br /> AddsValues adder = new AddsValues();<br />int sum = adder.returnSum();<br /> }<br />}<br />public class AddsValues {<br />public int returnSum() {<br />int x = 4;<br />int y = 17;<br />return(x + y); <br /> }<br />}<br />
  197. 197. Advantages of Method Use<br />Methods make programs more readable and easier to maintain.<br />Methods make development and maintenance quicker.<br />Methods are central to reusable software.<br />Methods allow separate objects to communicate and to distribute the work performed by the program.<br />Remember:<br />
  198. 198. Variables having the same value for all instances of a class are called class variables<br />Class variables are also sometimes referred to as static variables<br />Creating Static Methods and Variables<br />public class Student {<br />//class variables<br />static int maxIdAssigned;<br />//instance variable<br />private int id;<br />//constructor<br />public Student() {<br />this.id = maxIdAssigned;<br /> maxIdAssigned++;<br /> }<br />}<br />
  199. 199. Certain methods defined in a class can operate only on class variables<br />We can invoke these methods directly using the class name without creating an instance<br />Such methods are known as class methods, or static methods<br />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.<br />Creating Static Methods and Variables<br />In general, static refers to memory allocated at load time(when the program is loaded into RAM just before it starts running)<br />
  200. 200. Example:<br />Creating Static Methods and Variables<br />public class CountInstances {<br />public static void main (String[] args) {<br /> Slogan obj;<br /> obj = new Slogan (&quot;Remember the Alamo.&quot;);<br /> System.out.println (obj);<br /> obj = new Slogan (&quot;Don&apos;t Worry. Be Happy.&quot;);<br /> System.out.println (obj);<br /> obj = new Slogan (&quot;Live Free or Die.&quot;);<br /> System.out.println (obj);<br /> obj = new Slogan (&quot;Talk is Cheap.&quot;);<br /> System.out.println (obj);<br /> obj = new Slogan (&quot;Write Once, Run Anywhere.&quot;);<br /> System.out.println (obj);<br /> System.out.println();<br /> System.out.println (&quot;Slogans created: &quot; + Slogan.getCount());<br /> }<br />}<br />
  201. 201. Example:<br />Creating Static Methods and Variables<br />public class Slogan {<br />private String phrase;<br />private static int count = 0;<br />public Slogan (String str) {<br /> phrase = str;<br /> count++;<br /> }<br />public String toString() {<br />return phrase;<br /> }<br />public static int getCount () {<br />return count;<br /> }<br />}<br />
  202. 202. Creating Static Methods and Variables<br />
  203. 203. • Examples:<br />The Math class<br />The Math class provides the important mathematical constants E and PI which are of type double.<br />The Math class also provides many useful math functions as methods.<br />The System class<br />The System class provides access to the native operating system&apos;s environment through the use of static methods.<br />Statics Methods and Variables in the Java API<br />
  204. 204. • Examples:<br /> •<br />Statics Methods and Variables in the Java API<br />public class Get {<br />public static void main (String[] args) {<br /> StaticExample ex = new StaticExample();<br /> ex.getNumber();<br />}<br />public class StaticExample {<br />public void getNumber() {<br /> System.out.println(“A random number: ” <br /> + Math.random());<br /> }<br />}<br />
  205. 205. • Examples:<br /> •<br />Statics Methods and Variables in the Java API<br />// Determines the roots of a quadratic equation.<br />public class Quadratic {<br />public static void main (String[] args) {<br />int a, b, c; // ax^2 + bx + c<br /> a = 5; // the coefficient of x squared<br /> b = 7; // the coefficient of x<br /> c = 2; // the constant<br />// Use the quadratic formula to compute the roots.<br /> // Assumes a positive discriminant.<br />double discriminant = Math.pow(b, 2) - (4 * a * c);<br />double root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);<br />double root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);<br /> System.out.println (&quot;Root #1: &quot; + root1);<br /> System.out.println (&quot;Root #2: &quot; + root2);<br /> }<br />}<br />
  206. 206. Performing the operation on an individual object or associating the variable with a specific object type is not important.<br />Accessing the variable or method before instantiating an object is important.<br />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.<br />When to declare a static method or variable<br /><ul><li>A static method can only change static variables
  207. 207. Instance variables can only be changed by non-static methods</li></li></ul><li>Uses for Method Overloading<br />Java allows us to have two or more methods with the same name inside the same class<br />As with constructors, the overloaded methods should also have different number of parameters, or have different data types for the parameters<br />This feature of Java is called method overloading<br />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<br />
  208. 208. Example overloaded methods:<br />Using Method Overloading<br />public class OverloadTest {<br />public static void main(String args[]) {<br /> MethodOverloadingDemo md = new MethodOverloadingDemo();<br />md.printToScreen(53,8965);<br /> md.printToScreen(68, &apos;g&apos;);<br /> md.printToScreen(&apos;f&apos;, 74);<br /> md.printToScreen(64, 36, &apos;h&apos;);<br /> md.printToScreen(85, &apos;d&apos;, (float)745.3, &quot;true&quot;);<br /> }<br />}<br />
  209. 209. Example overloaded methods:<br />Using Method Overloading<br />public class MethodOverloadingDemo {<br />public void printToScreen(int a, int b) {<br /> System.out.println(a);<br /> System.out.println(b);<br /> }<br />public void printToScreen(int a, char c) {<br /> System.out.println(a);<br /> System.out.println(c);<br /> }<br />public void printToScreen(char c, int a) {<br /> System.out.println(c);<br /> System.out.println(a);<br /> }<br />
  210. 210. Example overloaded methods:<br />Using Method Overloading<br />public void printToScreen(int a, int b, int c) {<br /> System.out.println(a);<br /> System.out.println(b);<br /> System.out.println(c);<br /> } <br />public void printToScreen(int a, char c, float f, String s) {<br /> System.out.println(a);<br /> System.out.println(c);<br /> System.out.println(f);<br /> System.out.println(s);<br /> }<br />}<br />
  211. 211. Method Overloading and the Java API<br />
  212. 212. Examples:<br />public int sum(int numberOne, int numberTwo)<br />public int sum(int numberOne, int numberTwo, int numberThree)<br />public int sum(int numberOne, int numberTwo,int numberThree, int<br /> numberFour)<br />Uses for Method Overloading<br />
  213. 213. Uses for Method Overloading<br />public class ShirtTwo {<br />public int shirtID = 0; // Default ID for the shirt<br />public String description = “-description required-”; // default<br />// The color codes are R=Red, B=Blue, G=Green, U=Unset<br />public char colorCode = ‘U’;<br />public double price = 0.0; // Default price for all items<br />public int quantityInStock = 0; // Default quantity for all items<br />public void setShirtInfo(int ID, String desc, double cost, char color){<br /> shirtID = ID;<br /> description = desc;<br /> price = cost;<br /> colorCode = color;<br /> }<br />
  214. 214. Uses for Method Overloading<br />public void setShirtInfo(int ID, String desc, double cost, char color,<br />int quantity){<br />shirtID = ID;<br />description = desc;<br />price = cost;<br />colorCode = color;<br />quantityInStock = quantity;<br /> }<br /> // This method displays the values for an item <br />public void display() {<br /> System.out.println(“Item ID: “ + shirtID); <br /> System.out.println(“Item description:” + description);<br /> System.out.println(“Color Code: “ + colorCode);<br /> System.out.println(“Item price: “ + price);<br /> System.out.println(“Quantity in stock: “ + quantityInStock);<br /> } // end of display method<br />} // end of class<br />
  215. 215. Uses for Method Overloading<br />public class ShirtTwoTest {<br />public static void main (String args[]) {<br /> ShirtTwo shirtOne = new ShirtTwo();<br /> ShirtTwo shirtTwo = new ShirtTwo();<br /> ShirtTwo shirtThree = new ShirtTwo();<br /> shirtOne.setShirtInfo(100, “Button Down”, 12.99); <br /> shirtTwo.setShirtInfo(101, “Long Sleeve Oxford”, 27.99, ‘G’);<br /> shirtThree.setShirtInfo(102, “Shirt Sleeve T-Shirt”, 9.99, ‘B’, 50);<br /> shirtOne.display();<br /> shirtTwo.display();<br /> shirtThree.display();<br /> }<br />}<br />
  216. 216. Module 13Methods Lab<br />
  217. 217. Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />Lab Exercise 3<br />
  218. 218. Objectives<br />Create classes and objects<br />Invoke methods of a class<br />Overload methods in a class<br />
  219. 219. Lab Exercise 1<br />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). <br />Write another class that calls and prints those values.<br />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.<br />
  220. 220. Lab Exercise 2 (1 of 2)<br />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 &quot;Hello.&quot;<br />public class Methodcall {<br />public static void main(String[] args) {<br />new Methodcall().start(); // students: ignore this<br />}<br />public void start() { // a test harness for two methods<br /> // <br /> }<br />// Define method sayHello with no arguments and no return value<br /> // Make it print &quot;Hello&quot;.<br />// Define method addTwo with an int parameter and int return type<br /> // Make it add 2 to the parameter and return it.<br />}<br />
  221. 221. Lab Exercise 2 (2 of 2)<br />Make the start method of Methodcall call sayHello().<br />Define a method called addTwo that takes an integer argument, adds 2 to it, and returns that result.<br />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. <br />
  222. 222. Lab Exercise 3 (1 of 2)<br />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.<br />Write a class called Area.<br />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.<br />
  223. 223. Lab Exercise 3 (2 of 2)<br />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.<br />Area of circle = 3.14 * radius * radius<br />Area of triangle = 0.5 * base * height<br />Area of rectangle = length * breadth<br />Area of cylinder = 3.14 * radius * radius * height<br />
  224. 224. Module 14Implementing Encapsulation and Constructors<br />
  225. 225. Agenda<br />Objectives<br />Using Encapsulation<br />The public Modifier<br />The private Modifier<br />Describing Variable Scope<br />How Instance Variables and Local Variables Appear in Memory<br />Constructors of a Class<br />Creating Constructors<br />Default Constructors<br />Overloading Constructors<br />
  226. 226. Objectives<br />Use encapsulation to protect data<br />Create constructors to initialize objects<br />
  227. 227. Encapsulation separates the external aspects of an object from the internal implementation details<br />Internal changes need not affect external interface<br />Using Encapsulation<br />Hideimplementation from clients.<br />Clients depend on interface<br />
  228. 228. Using Encapsulation<br />
  229. 229. Using Encapsulation<br />
  230. 230. 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.<br />The public Modifier<br />public class PublicExample {<br />public static void main(String args[]) {<br /> PublicClass pc = new PublicClass();<br />pc.publicInt = 27;<br /> pc.publicMethod();<br /> }<br />}<br />public class PublicClass {<br />public int publicInt;<br />public void publicMethod() {<br /> System.out.println(publicInt);<br /> }<br />}<br />
  231. 231. The public Modifier<br />public int currentFloor=1;<br />public void setFloor(int desiredFloor) {<br />...<br />}<br />
  232. 232. 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.<br />The private Modifier<br />public class PrivateExample {<br />public static void main(String args[]) {<br /> PrivateClass pc = new PublicClass();<br />pc.privateInt = 27;<br /> pc.privateMethod();<br /> }<br />}<br />X<br />public class PrivateClass {<br />private int privateInt;<br />private void privateMethod() {<br /> System.out.println(privateInt);<br /> }<br />}<br />X<br />
  233. 233. private int currentFloor=1;<br />private void calculateCapacity() {<br />...<br />}<br />The private Modifier<br />
  234. 234. Describing Variable Scope<br />All variables are not available throughout a program<br />Variable scope means where a variabe can be used<br />public class Person2 {<br />// begin scope of int age<br />private int age = 34;<br />public void displayName() {<br />// begin scope of String name<br /> String name = “Peter Simmons”;<br /> System.out.println(“My name is “+ name + “ and I am “ + age );<br /> } // end scope of String name<br />public String getName () {<br />return name; // this causes an error<br /> }<br />} // end scope of int age<br />
  235. 235. Describing Variable Scope<br />Local variables are:<br />Variables that are defined inside a method and are called local, automatic, temporary, or stack variables<br />Variables that are created when the method is executed are destroyed when the method is exited<br />Local variables require explicit initialization<br />Member and class variables are automatically initialized<br />
  236. 236. How Instance Variables and Local Variables Appear in Memory<br />
  237. 237. Constructors of a Class<br />The constructor is essentially used to initialize a newly created object of that particular type<br />All classes written in Java have at least one constructor<br />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<br />The default constructor accepts no arguments<br />It has an empty implementation, and does nothing<br />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<br />
  238. 238. Creating Constructors<br />To define a constructor use the same name as the class and give no return type<br />publicclassHat {<br />privateStringtype;<br />publicHat(StringhatType) {<br />type = hatType;<br /> }<br />publicclassOrder {<br />Hat hat1 = newHat(“Fedora”);<br />}<br />
  239. 239. Default Constructors<br />public class MyClass {<br />int x;<br />MyClass() {<br /> x = 10;<br /> }<br />}<br />public class ConstructorDemo {<br />public static void main(String[] args ) {<br /> MyClass t1 = new MyClass();<br /> MyClass t2 = new MyClass();<br /> System.out.println(t1.x + &quot; &quot; + t2.x);<br /> }<br />}<br />
  240. 240. Overloading Constructors<br />public class MyClassTwo {<br />int x;<br /> MyClassTwo() {<br /> x = 10;<br /> }<br /> MyClassTwo(int i) {<br /> x = i;<br /> }<br />}<br />public class ParametrizedConstructorDemo {<br />public static void main(String[] args) {<br /> MyClassTwo t1 = new MyClassTwo(10);<br /> MyClassTwo t2 = new MyClassTwo(88);<br /> System.out.println(t1.x + &quot; &quot; + t2.x);<br /> }<br />}<br />
  241. 241. Overloading Constructors<br />public class Student {<br />private int id = 0;<br />private String name;<br />public Student() {<br /> }<br />public Student(int a) {<br /> id = a;<br /> }<br />public Student(int a, String aName) {<br /> id = a;<br /> name = aName;<br /> }<br />public void setValues(int sid, String sName) {<br /> id = sid;<br /> name = sName;<br /> }<br />public static void main(String[] args) {<br /> Student s = new Student(1,&quot;John&quot;);<br /> }<br />}<br />
  242. 242. Module 15<br />Implementing Encapsulation and Constructors Lab<br />
  243. 243. Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />
  244. 244. Objectives<br />Practice implementing encapsulation.<br />
  245. 245. Lab Exercise 1<br />Declare a Customer class with variables for a salutation (such as Ms.), first name, middle name, last name, and address, with three constructors:<br /><ul><li>One creates a new customer with no values
  246. 246. One takes a salutation (such as Ms.), first name, middle name, and last name</li></ul>2. Test the program with a CustomerTest.java program<br />
  247. 247. Lab Exercise 2<br />Make a class called Rectangle that represents a rectangle using private width and height variables. Make the following public methods:<br /><ul><li>getHeight returns the height of the rectangle
  248. 248. getWidth returns the witdh of the rectangle
  249. 249. setHeight verifies the data and assigns the new value to the height
  250. 250. setWidth verifies the data and assigns the new value to the width
  251. 251. getArea returns the area of the rectangle
  252. 252. getPerimeter returns the perimeter of rectangle
  253. 253. draw draws the rectangle using asterisks(*’s) as the drawing character</li></ul>2. Write the main method in another class TestRectangle to test the <br />Rectangle class (call the methods, and so on).<br />
  254. 254. Module 16Creating and Using Arrays<br />
  255. 255. Agenda<br />Objectives<br />Creating One-Dimensional Arrays<br />Declaring a One-Dimensional Array<br />Instantiating a One-Dimensional Array<br />Declaring, Instantiating, and Initializing One-Dimensional Arrays<br />Accessing a Value Within an Array<br />Storing Primitive Variables and Arrays of Primitives in Memory<br />Storing Reference Variables and Arrays of References in Memory<br />Setting Array Values Using the length Attribute and a Loop<br />Using the args Array in the main method<br />Converting String arguments to Other Types<br />Describing Two-Dimensional Arrays<br />
  256. 256. Agenda<br />Declaring a Two-Dimensional Array<br />Instantiating a Two-Dimensional Array<br />Initializing a Two-Dimensional Array<br />
  257. 257. Objectives<br />Code one-dimensional arrays<br />Set array values using the length attribute and a loop<br />Pass arguments to the main method for use in a program<br />Create two-dimensional arrays<br />
  258. 258. An array is an ordered list of values.<br />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.<br />Creating One-Dimensional Arrays<br />
  259. 259. Declaring a One-Dimensional Array<br />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.<br />Syntax:<br />type [] array_identifier;<br />• Examples:<br />char [] status;<br />int [] ages;<br />Shirt [] shirts;<br />String [] names;<br />
  260. 260. Instantiating a One-Dimensional Array<br />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.<br />Syntax:<br />array_identifier = new type [length];<br />• Examples:<br />status = newchar[20];<br />ages = new int[5];<br />names = new String[7];<br />shirts = new Shirt[3];<br />
  261. 261. Initializing a One-Dimensional Array<br />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<br />Once an array is created, it has a fixed size<br />Syntax:<br />array_identifier[index] = value;<br />A particular value in an array is referenced using the array name followed by index in brackets.<br />
  262. 262. Initializing a One-Dimensional Array<br />• Examples:<br />int[] height = new int[11]; <br />height[0] = 69; <br />height[1] = 61;<br />height[2] = 70;<br />height[3] = 74;<br />height[4] = 62;<br />height[5] = 69;<br />height[6] = 66;<br />height[7] = 73;<br />height[8] = 79;<br />height[9] = 62;<br />height[10] = 70;<br />
  263. 263. Declaring, Instantiating, and Initializing One-Dimensional Arrays<br />An array initializer is written as a comma separated list of expressions, enclosed within curly braces.<br />Syntax:<br />type [] array_identifier = <br /> {comma-separated list of values or expressions};<br />• Examples:<br />int [] ages = {19, 42, 92, 33, 46};<br />Shirt [] shirts = { new Shirt(), <br /> new Shirt(121,”Work Shirt”, ‘B’, 12.95), <br /> new Shirt(122,”Flannel Shirt”, ‘G’, 22.95)};<br />double[] heights = {4.5, 23.6, 84.124, 78.2, 61.5};<br />boolean[] tired = {true, false, false, true}; <br />char vowels[] = {&apos;a&apos;, &apos;e&apos;, &apos;i&apos;, &apos;o&apos;, &apos;u&apos;}<br />
  264. 264. To access a value in an array, we use the name of the array followed by the index in square brackets<br />An array element can be assigned a value, printed, or used in calculation<br />Examples:<br />status[0] = ’3’;<br />names[1] = &quot;Fred Smith&quot;;<br />ages[1] = 19;<br />prices[2] = 9.99F;<br />char s = status[0];<br />String name = names [1];<br />int age = ages[1];<br />double price = prices[2];<br />Accessing a Value Within an Array<br />
  265. 265. Examples:<br />height[2] = 72;<br />height[count] = feet * 12;<br />average = (height[0] + height[1] <br /> + height[2]) / 3;<br />System.out.println (“The middle value is “ <br /> + height[MAX/2]);<br />pick = height[rand.nextInt(11)];<br />Accessing a Value Within an Array<br />
  266. 266. Storing Primitive Variables and Arrays in Memory<br />
  267. 267. Storing Reference Variables and Arrays in Memory<br />
  268. 268. Setting Array Values Using the length Attribute and a loop<br />public class Primes {<br />public static void main (String[] args) {<br />int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19};<br /> System.out.println (&quot;Array length: &quot; + primeNums.length);<br /> System.out.println (&quot;The first few prime numbers are:&quot;);<br />for (int scan = 0; scan &lt; primeNums.length; scan++)<br /> System.out.print (primeNums[scan] + &quot; &quot;);<br /> System.out.println ();<br /> }<br />}<br />
  269. 269. Using the args Array in the main Method<br />Command Line Arguments can be used to supply inputs to a program during its execution.<br />The general construct used for the command line arguments is as follows:<br />java classFileName argument1 argument2 etc…<br />We can give any number of command line arguments. These <br />command line arguments are stored in the string array passed to <br />the main() method.<br />
  270. 270. Using the args Array in the main Method<br />public class ArgsTest {<br />public static void main (String args[]) {<br /> System.out.println(“args[0] is “ + args[0]);<br /> System.out.println(“args[1] is “ + args[1]);<br /> }<br />}<br />java ArgTest Hello Java<br />The output is:<br />args[0] is Hello<br />args[1] is Java<br />All command line arguments are interpreted as strings in Java.<br />
  271. 271. Converting String Arguments to Other Types<br />Example:<br />int ID = Integer.parseInt(args[0]);<br />The Integer class is one of Java&apos;s<br /> &quot;wrapper&quot; classes that provides <br /> methods useful for manipulating <br /> primitive types. Its parseInt() method <br /> will convert a String into an int, <br /> if possible. <br />
  272. 272. A one dimensional array stores a list of elements<br />A two-dimensional array can be thought of as a table of elements, with rows and columns<br />We must use two indexes to refer to a value in a two-dimensional array, one specifying the row and another the column.<br />Describing Two-Dimensional Arrays<br />
  273. 273. A two-dimensional array element is declared by specifying the size of each dimension separately<br />Syntax:<br />type [][] array_identifier;<br />• Example:<br />int [][] yearlySales;<br />Declaring a Two-Dimensional Array<br />
  274. 274. Instantiating a Two-Dimensional Array<br />• Syntax:<br />array_identifier = new type [number_of_arrays] [length];<br />• Example:<br />// Instantiates a two-dimensional array: 5 arrays of 4 elements each<br />yearlySales = new int[5][4];<br />
  275. 275. Instantiating a Two-Dimensional Array<br />Example:<br />yearlySales[0][0] = 1000;<br />yearlySales[0][1] = 1500;<br />yearlySales[0][2] = 1800;<br />yearlySales[1][0] = 1000;<br />yearlySales[2][0] = 1400;<br />yearlySales[3][3] = 2000;<br />
  276. 276. Instantiating a Two-Dimensional Array<br />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}}; <br />for (int row=0;row&lt;4; row++) {     for (int col=0;col&lt;7; col++)         System.out.print(myTable[row][col] + &quot;  &quot;);     System.out.println(); } <br />
  277. 277. Module 17Arrays Lab<br />
  278. 278. Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />Lab Exercise 3<br />
  279. 279. Objectives<br />Create and Initialize an array <br />
  280. 280. Lab Exercise 1<br />Make an array of 5 integers<br />Use a for loop to set the values of the array to the index plus 10<br />Use a for loop to print out the values in the array<br />Make an arrays of strings initialized to Frank, Bob, and Jim using the variable initializer syntax<br />Use a for loop to print out the string in the array<br />Set the last element of the array to Mike<br />Print out the last element in the array<br />
  281. 281. Lab Exercise 2<br />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.<br />
  282. 282. Lab Exercise 3<br />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. <br />Create another class that create the arrays of shirts.<br />
  283. 283. Module 18Implementing Inheritance<br />
  284. 284. Agenda<br />Objectives<br />Inheritance<br />What is Inherited in Java?<br />Single vs. Multiple Inheritance<br />Declaring a subclass<br />Overriding Methods<br />Overloading vs. Overriding<br />
  285. 285. Objectives<br />Define and test your use of inheritance<br />
  286. 286. Inheritance<br />Inheritance allows a software <br /> developer to derive a new class <br /> from an existing one<br />The existing class is called the parent class or superclass, or base class<br />The derived class is called the <br /> child class or subclass.<br />Inheritance is the backbone of object-oriented programming. It enables programmers to create a hierarchy among a group of classes that have similar characteristics<br />
  287. 287. As the name implies, the child inherits<br /> characteristics of the parent<br />That is, the child class inherits the methods<br /> and data defined for the parent class<br />To tailor a derived class, the programmer can<br /> add new variables or methods, or can modify<br /> the inherited ones<br />What is Inherited in Java?<br />Animal<br />Mammal<br />Cat<br />class Animal<br /> eat()<br /> sleep()<br /> reproduce()<br />Cat Gardfield<br /> eat()<br /> reproduce()<br /> sleep()<br /> huntMice()<br /> purr()<br />class Mammal<br /> reproduce()<br />classCat<br />sleep()<br />huntMice()<br />purr()<br />
  288. 288. Java does not support multiple inheritance<br />Every Java class except Object has exactly one immediate superclass (Object does not have a superclass)<br />You can force classes that are not related by inheritance to implement a common set of methods using interfaces<br />Single vs. Multiple Inheritance<br />
  289. 289. Declaring a subclass<br />Animal<br /><ul><li>In Java, we use thereservedwordextendstoestablishaninheritancerelationship
  290. 290. Syntax:</li></ul>[class_modifier] classclass_identifierextends<br />superclass_identifier<br />publicclass Animal {…}<br />publicclassMammalextends Animal {<br /> //codespecificto a Mammal<br />}<br />publicclassCatextendsMammal {<br /> //codespecificto a Cat<br />}<br />Mammal<br />Cat<br />HereMammalextends Animal meansthatMammalinheritsfrom Animal, orMammalis<br />a type of Animal<br />
  291. 291. Declaring a subclass<br />public class Animal {<br />public void speak() {<br /> System.out.println(&quot;I am a generic animal&quot;);<br /> } <br />}<br />public class Dog extends Animal {<br />public void speak() {<br /> System.out.println(&quot;Woof!!&quot;);<br /> } <br />}<br />public class Cat extends Animal {<br />public void speak() {<br /> System.out.println(“Meow!!&quot;);<br /> } <br />}<br />
  292. 292. Overriding Methods<br /><ul><li>When a childclass defines a methodwiththesamename and signature as a method in theparentclass, wesaythatthechild’sversionoverridestheparent’sversion in favor of itsown
  293. 293. The new methodmusthavethesamesignature as theparent’smethod, but can have a differentbody
  294. 294. Thetype of theobjectexecutingthemethod determines whichversion of themethodisinvoked</li></ul>class Animal<br /> eat()<br /> sleep()<br /> reproduce()<br />overriding<br />Cat Gardfield<br /> eat()<br /> reproduce()<br /> sleep()<br /> huntMice()<br /> purr()<br />class Mammal<br /> reproduce()<br />classCat<br />sleep()<br />huntMice()<br />purr()<br />
  295. 295. Overriding Methods<br />public class MoodyObject {<br />// return the mood<br />protected String getMood() {<br />return &quot;moody&quot;;<br /> }<br />// ask the object how it feels<br />public void queryMood() {<br /> System.out.println(&quot;I feel &quot; + getMood() + &quot; today!&quot;);<br /> }<br />}<br />
  296. 296. Overriding Methods<br />public class HappyObject extends MoodyObject {<br />// redefine class’s mood<br />protected String getMood() {<br />return &quot;happy&quot;;<br /> }<br />// specialization<br />public void laugh() {<br /> System.out.println(&quot;hehehe... hahaha... HAHAHAHAHAHA!!!!!&quot;);<br /> }<br />}<br />
  297. 297. Overriding Methods<br />publicclass MoodyDriver {<br />publicfinalstaticvoid main(String[] args) {<br /> MoodyObject moodyObject = new MoodyObject();<br /> HappyObject happyObject = new HappyObject();<br /> System.out.println(&quot;How does the moody object feel today?&quot;);<br />moodyObject.queryMood();<br /> System.out.println(&quot;&quot;);<br /> System.out.println(&quot;How does the happy object feel today?&quot;);<br />happyObject.queryMood();//overriding changes the mood<br />happyObject.laugh();<br /> System.out.println(&quot;&quot;);<br /> }<br />}<br />
  298. 298. Overloading vs. Overriding<br />
  299. 299. Overloading vs. Overriding<br />Inheritance<br />Method(x)<br />superclass<br />Method(x)<br />Method(x,y)<br />Method(x)<br />…<br />subclass<br />…<br />…<br />Sub-subclass<br />Polymophism: Override, Overload <br />
  300. 300. Module 19Inheritance Lab<br />
  301. 301. Agenda<br />Objectives<br />Lab Exercise 1<br />Lab Exercise 2<br />
  302. 302. Objectives<br />Work with inheritance<br />Invoke methods in a super class<br />
  303. 303. Lab Exercise 1<br />Design and implement a set of classes that define the following <br />class hierarchy. Include methods in each class that are named <br />according to the services provided by that class and that print an <br />appropriate message. Create a main driver class to instantiate and <br />exercise several of the classes.<br />
  304. 304. Lab Exercise 2 (1 of 2)<br />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:<br />final void setColor(String color);<br />String getColor(); // returned string gives the color<br />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:<br />void activatePrism(Color c);<br />
  305. 305. Lab Exercise 2 (2 of 2)<br />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:<br />void activateAntiPrism(Red r, Blue b, Green g);<br />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.<br />5. A class Scientist uses the Prism and AntiPrism classes.<br />
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×