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

Mais conteúdo relacionado

Mais procurados

Chapter 1. java programming language overview
Chapter 1. java programming language overviewChapter 1. java programming language overview
Chapter 1. java programming language overview
Jong Soon Bok
 
Chapter 1 introduction to java technology
Chapter 1 introduction to java technologyChapter 1 introduction to java technology
Chapter 1 introduction to java technology
sshhzap
 
Profiler Instrumentation Using Metaprogramming Techniques
Profiler Instrumentation Using Metaprogramming TechniquesProfiler Instrumentation Using Metaprogramming Techniques
Profiler Instrumentation Using Metaprogramming Techniques
Ritu Arora
 

Mais procurados (20)

Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Structure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryStructure programming – Java Programming – Theory
Structure programming – Java Programming – Theory
 
Chapter 1. java programming language overview
Chapter 1. java programming language overviewChapter 1. java programming language overview
Chapter 1. java programming language overview
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
 
core java
core javacore java
core java
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
Chapter 1 introduction to java technology
Chapter 1 introduction to java technologyChapter 1 introduction to java technology
Chapter 1 introduction to java technology
 
Java seminar
Java seminarJava seminar
Java seminar
 
Profiler Instrumentation Using Metaprogramming Techniques
Profiler Instrumentation Using Metaprogramming TechniquesProfiler Instrumentation Using Metaprogramming Techniques
Profiler Instrumentation Using Metaprogramming Techniques
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 
Programming in Java
Programming in JavaProgramming in Java
Programming in Java
 
Eclipse vs Netbean vs Railo
Eclipse vs Netbean vs RailoEclipse vs Netbean vs Railo
Eclipse vs Netbean vs Railo
 
Introduction to java technology
Introduction to java technologyIntroduction to java technology
Introduction to java technology
 
A seminar report on core java
A  seminar report on core javaA  seminar report on core java
A seminar report on core java
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat Shahriyar
 
Java notes
Java notesJava notes
Java notes
 
Introduction To Java.
Introduction To Java.Introduction To Java.
Introduction To Java.
 

Semelhante a Curso de Programación Java Básico

Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
sotlsoc
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
Nexus
 
JavaClassPresentation
JavaClassPresentationJavaClassPresentation
JavaClassPresentation
juliasceasor
 
Core java over view basics introduction by quontra solutions
Core java over view basics introduction by quontra solutionsCore java over view basics introduction by quontra solutions
Core java over view basics introduction by quontra solutions
QUONTRASOLUTIONS
 

Semelhante a Curso de Programación Java Básico (20)

Javalecture 1
Javalecture 1Javalecture 1
Javalecture 1
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
 
Introduction to Java Programming.pdf
Introduction to Java Programming.pdfIntroduction to Java Programming.pdf
Introduction to Java Programming.pdf
 
OOPS JAVA.pdf
OOPS JAVA.pdfOOPS JAVA.pdf
OOPS JAVA.pdf
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Java programming basics notes for beginners(java programming tutorials)
Java programming basics notes for beginners(java programming tutorials)Java programming basics notes for beginners(java programming tutorials)
Java programming basics notes for beginners(java programming tutorials)
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Java
JavaJava
Java
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Introducción a la progrogramación orientada a objetos con Java
Introducción a la progrogramación orientada a objetos con JavaIntroducción a la progrogramación orientada a objetos con Java
Introducción a la progrogramación orientada a objetos con Java
 
JavaClassPresentation
JavaClassPresentationJavaClassPresentation
JavaClassPresentation
 
Introduction to java programming tutorial
Introduction to java programming   tutorialIntroduction to java programming   tutorial
Introduction to java programming tutorial
 
Core java over view basics introduction by quontra solutions
Core java over view basics introduction by quontra solutionsCore java over view basics introduction by quontra solutions
Core java over view basics introduction by quontra solutions
 
Java platform
Java platformJava platform
Java platform
 
Java Basic PART I
Java Basic PART IJava Basic PART I
Java Basic PART I
 

Mais de Universidad de Occidente (7)

Programación para niños app inventor
Programación para niños app inventorProgramación para niños app inventor
Programación para niños app inventor
 
Programación para niños app inventor
Programación para niños app inventorProgramación para niños app inventor
Programación para niños app inventor
 
Taller app inventor
Taller app inventorTaller app inventor
Taller app inventor
 
Pj100 modulo 01
Pj100 modulo 01Pj100 modulo 01
Pj100 modulo 01
 
P J020
P J020P J020
P J020
 
Introducción al Análisis y Diseño Orientado a Objetos
Introducción al Análisis y Diseño Orientado a ObjetosIntroducción al Análisis y Diseño Orientado a Objetos
Introducción al Análisis y Diseño Orientado a Objetos
 
Curso Básico de JDBC
Curso Básico de JDBCCurso Básico de JDBC
Curso Básico de JDBC
 

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Último (20)

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 

Curso de Programación Java Básico

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