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.
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
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
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!"); } }
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
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().
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)
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); } }
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 (_).
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 ); } }
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.
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
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.
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;
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
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!
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; } } }
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.
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
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
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.
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
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
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
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).
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; } }
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); } }
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(); } }
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
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
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
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"); } }
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).
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.
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
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];
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
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!!"); } }
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.