Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
SOFTWARE FOR NETWORK SYSTEMS Ghadah Aldabbagh 19th of September, 2011 OBJECTIVES Know the basics of the Object Oriented Programming Language Inheritance, Polymorphism … BUILDING JAVA APPLICATIONS GOALS OF THIS LECTURE Be able to write a simple Java application Use input and output statements Know Java primitive types Understand basic memory concepts Use arithmetic operators Use the if else constructor WHY JAVA? The answer is that Java enables users to develop and deploy applications on the Internet for servers, desktop computers, and small hand-held devices. The future of computing is being profoundly influenced by the Internet, and Java promises to remain a big part of that future. Java is the Internet programming language. FJava is a general purpose programming language. FJava is the Internet programming language. 5 JAVA, WEB, AND BEYOND Java can be used to develop Web applications. Java Applets Java Web Applications Java can also be used to develop applications for hand-held devices such as Palm and cell phones 6 EXAMPLES OF JAVA’S VERSATILITY (APPLETS) 7 PDA AND CELL PHONE 8 JAVA’S HISTORY James Gosling and Sun Microsystems Oak Java, May 20, 1995, Sun World HotJava The first Java-enabled Web browser Early History Website: http://java.sun.com/features/1998/05/birthday.h tml 9 Companion Website CHARACTERISTICS OF JAVA Java Is Simple Java Is Object-Oriented Java Is Distributed Java Is Interpreted Java Is Robust Java Is Secure Java Is Architecture-Neutral Java Is Portable Java's Performance Java Is Multithreaded Java Is Dynamic www.cs.armstrong.edu/liang/intro8e/JavaCharacteristics 10 .pdf Companion WebsiteHARACTERISTICS C OF JAVA Java is partially modeled on C++, but greatly Java Is Simple simplified and improved. Some people refer to Java Is Object-Oriented Java as "C++--" because it is like C++ but with more functionality and fewer negative Java Is Distributed aspects. Java Is Interpreted Java Is Robust Java Is Secure Java Is ArchitectureNeutral Java Is Portable Java's Performance Java Is Multithreaded Java Is Dynamic 11 Companion WebsiteHARACTERISTICS C OF Java Is Simple Java Is Object-Oriented Java Is Distributed Java Is Interpreted Java Is Robust Java Is Secure Java Is ArchitectureNeutral Java Is Portable Java's Performance Java Is Multithreaded Java Is Dynamic JAVA Java is inherently object-oriented. Although many object-oriented languages began strictly as procedural languages, Java was designed from the start to be object-oriented. Object-oriented programming (OOP) is a popular programming approach that is replacing traditional procedural programming techniques. One of the central issues in software development is how to reuse code. Objectoriented programming provides great flexibility, modularity, clarity, and reusability through encapsulation, inheritance, and polymorphism. 12 Companion WebsiteHARACTERISTICS C OF Java Is Simple Java Is Object-Oriented Java Is Distributed Java Is Interpreted Java Is Robust Java Is Secure Java Is ArchitectureNeutral Java Is Portable Java's Performance Java Is Multithreaded Java Is Dynamic JAVA Distributed computing involves several computers working together on a network. Java is designed to make distributed computing easy. Since networking capability is inherently integrated into Java, writing network programs is like sending and receiving data to and from a file. 13 Companion WebsiteHARACTERISTICS C OF Java Is Simple Java Is Object-Oriented Java Is Distributed Java Is Interpreted Java Is Robust Java Is Secure Java Is ArchitectureNeutral Java Is Portable Java's Performance Java Is Multithreaded Java Is Dynamic JAVA You need an interpreter to run Java programs. The programs are compiled into the Java Virtual Machine code called bytecode. The bytecode is machineindependent and can run on any machine that has a Java interpreter, which is part of the Java Virtual Machine (JVM). 14 Companion WebsiteHARACTERISTICS C OF Java Is Simple Java Is Object-Oriented Java Is Distributed Java Is Interpreted Java Is Robust Java Is Secure Java Is ArchitectureNeutral Java Is Portable Java's Performance Java Is Multithreaded Java Is Dynamic JAVA Java compilers can detect many problems that would first show up at execution time in other languages. Java has eliminated certain types of errorprone programming constructs found in other languages. Java has a runtime exception-handling feature to provide programming support for robustness. 15 Companion WebsiteHARACTERISTICS C OF JAVA Java Is Simple Java Is Object-Oriented Java Is Distributed Java Is Interpreted Java implements several security Java Is Robust mechanisms to protect your system against harm caused by stray programs. Java Is Secure Java Is ArchitectureNeutral Java Is Portable Java's Performance Java Is Multithreaded Java Is Dynamic 16 Companion WebsiteHARACTERISTICS C OF Java Is Simple Java Is Object-Oriented Java Is Distributed Java Is Interpreted Java Is Robust Java Is Secure Java Is ArchitectureNeutral Java Is Portable Java's Performance Java Is Multithreaded Java Is Dynamic JAVA Write once, run anywhere With a Java Virtual Machine (JVM), you can write one program that will run on any platform. 17 Companion WebsiteHARACTERISTICS C OF JAVA Java Is Simple Java Is Object-Oriented Java Is Distributed Java Is Interpreted Java Is Robust Java Is Secure Java Is ArchitectureNeutral Because Java is architecture neutral, Java programs are portable. They can Java Is Portable be run on any platform without being Java's Performance recompiled. Java Is Multithreaded Java Is Dynamic 18 Companion WebsiteHARACTERISTICS C OF JAVA Java Is Simple Java Is Object-Oriented Java Is Distributed Java Is Interpreted Java Is Robust Java Is Secure Java Is ArchitectureNeutral Java’s performance Because Java is architecture neutral, Java programs are Java Is Portable portable. They can be run on any Java's Performance platform without being recompiled. Java Is Multithreaded Java Is Dynamic 19 Companion WebsiteHARACTERISTICS C OF JAVA Java Is Simple Java Is Object-Oriented Java Is Distributed Java Is Interpreted Java Is Robust Java Is Secure Java Is ArchitectureNeutral Java Is Portable Multithread programming is smoothly Java's Performance integrated in Java, whereas in other Java Is Multithreadedlanguages you have to call procedures specific to the operating system to enable Java Is Dynamic multithreading. 20 Companion WebsiteHARACTERISTICS C OF JAVA Java Is Simple Java Is Object-Oriented Java Is Distributed Java Is Interpreted Java Is Robust Java Is Secure Java Is ArchitectureNeutral Java was designed to adapt to an evolving Java Is Portable environment. New code can be loaded on the Java's Performance fly without recompilation. There is no need for Java Is Multithreaded developers to create, and for users to install, major new software versions. New features can Java Is Dynamic be incorporated transparently as needed. 21 PLATFORM INDEPENDENCE Achieved by targeting the Java Virtual Machine A relatively simple machine architecture Win32 Emulated in software Machine Java Application or Applet Java Virtual Machine Unix Machine Smart Card EXAMPLES OF VIRTUAL MACHINE IMPLEMENTATIONS On Win32 Platforms Microsoft’s jview.exe The Sun JDK’s java.exe Embedded Netscape in Browsers 2.0+ comes packaged with a VM internally to run Java applets JAVA ARCHITECTURE AND VIRTUAL MACHINE The Java Language The Java Virtual Machine The Core API Core API Classes Java Language Source Code Networking Java Compiler Java Classes Windowing Java Virtual Machine EDITORS AND INTEGRATED DEVELOPMENT ENVIRONMENTS www.eclipse.org, The Eclipse development environment can be used to develop code in any programming language www.netbeans.org, The NetBean IDE is one of the most widely used, freely distributed Java development tools. www.blueJ.org, BlueJ is a free tool designed to help teach object-oriented Java to new programmers www.jgrasp.org, jGRASP is a “lighter weight” integrated development environment that displays visual representations of Java programs to aid comprehension. www.jcreator.com, JCreator is a popular Java IDE. Jcreator Lite Edition is available as a free download. www.textpad.com www.editplus.com www.jedit.org JDK EDITIONS Java J2SE can be used to develop client-side standalone applications or applets. Java Enterprise Edition (J2EE) J2EE can be used to develop server-side applications such as Java servlets and Java ServerPages. Java Standard Edition (J2SE) Micro Edition (J2ME). J2ME can be used to develop applications for mobile devices such as cell phones. This book uses J2SE to introduce Java programming. 26 POPULAR JAVA IDES NetBeans Eclipse Open Source by Sun Open Source by IBM 27 CREATING, COMPILING, AND RUNNING PROGRAMS Create/Modify Source Code Source code (developed by the programmer) public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } Byte code (generated by the compiler for JVM to read and interpret, not for you to understand) … Method Welcome() 0 aload_0 … Method void main(java.lang.String[]) 0 getstatic #2 … 3 ldc #3 <String "Welcome to Java!"> 5 invokevirtual #4 … 8 return Saved on the disk Source Code Compile Source Code i.e., javac Welcome.java If compilation errors stored on the disk Bytecode Run Byteode i.e., java Welcome Result If runtime errors or incorrect 28 result ANATOMY OF A JAVA PROGRAM Comments Reserved words Modifiers Statements Blocks Classes Methods The main method 29 COMMENTS Three types of comments in Java. Line comment: A line comment is preceded by two slashes (//) in a line. Paragraph comment: A paragraph comment is enclosed between /* and */ in one or multiple lines. javadoc comment: javadoc comments begin with /** and end with */. They are used for documenting classes, data, and methods. They can be extracted into an HTML file using JDK's javadoc command. 30 RESERVED WORDS Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. For example, when the compiler sees the word class, it understands that the word after class is the name for the class. Other reserved words in Listing 1.1 are public, static, and void. Their use will be introduced later in the book. 31 MODIFIERS Java uses certain reserved words called modifiers that specify the properties of the data, methods, and classes and how they can be used. Examples of modifiers are public and static. Other modifiers are private, final, abstract, and protected. A public datum, method, or class can be accessed by other programs. A private datum or method cannot be accessed by other programs. Modifiers are discussed in Chapter 6, “Objects and Classes.” 32 STATEMENTS A statement represents an action or a sequence of actions. The statement System.out.println("Welcome to Java!") in the program in Listing 1.1 is a statement to display the greeting "Welcome to Java!" Every statement in Java ends with a semicolon (;). 33 BLOCKS A pair of braces in a program forms a block that groups components of a program. public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } Class block Method block 34 CLASSES The class is the essential Java construct. A class is a template or blueprint for objects. To program in Java, you must understand classes and be able to write and use them. The mystery of the class will continue to be unveiled throughout this book. For now, though, understand that a program is defined by using one or more classes. 35 METHODS What is System.out.println? It is a method: a collection of statements that performs a sequence of operations to display a message on the console. It can be used even without fully understanding the details of how it works. It is used by invoking a statement with a string argument. The string argument is enclosed within parentheses. In this case, the argument is "Welcome to Java!" You can call the same println method with a different argument to print a different message. 36 MAIN METHOD The main method provides the control of program flow. The Java interpreter executes the application by invoking the main method. The main method looks like this: public static void main(String[] args) { // Statements; } 37 HOW DO WE COMPILE AND RUN OUR PROGRAMS. THREE STEPS: First we save the class in a file with .java extension. The name of the class and the file need to be the same First one compiles the program into a class file Then we run the program AN APPLICATION An application in Java consists of one or more classes. One and only one of these classes has to have a method called main Class 2 Class 1 Class 3 main() Class n A JAVA PROGRAM // Text-printing program. public class Welcome1 { // main method begins execution of Java application public static void main( String args[] ) { System.out.println( "Welcome to Java Programming!" ); } // end method main } // end class A Comments. These are ignored by the JAVA PROGRAM Compiler. They can also be of the form /* Comment line 1 Comment line 2 */ // Text-printing program. Always opening and closing brackets public class Welcome1 Always a main method { // main method begins execution of Java application public static void main( String args[] ) { System.out.println( "Welcome to Java Programming!" ); } // end method main } // end class Statements always finish with a ; Spaces and Indentation are optional But crucial for human readability PROGRAM 2 // Addition program that displays the sum of two numbers. import java.util.Scanner; // program uses class Scanner public class Addition { // main method begins execution of Java application public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int number1; // first number to add int number2; // second number to add int sum; // sum of number1 and number2 Variables is where a Program stores data. They have a type and the name is chosen by the programmer Mathematical operator System.out.print( "Enter first integer: " ); // prompt number1 = input.nextInt(); // read first number from user System.out.print( "Enter second integer: " ); // prompt number2 = input.nextInt(); // read second number from user sum = number1 + number2; // add numbers System.out.printf( "Sum is %d\n", sum ); // display sum } // end method main Printing variables to the screen PROGRAM 2 // Addition program that displays the sum of two numbers. import java.util.Scanner; // program uses class Scanner public class Addition { // main method begins execution of Java application public static void main( String args[] ) To input from the user we use the Class Scanner { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int number1; // first number to add int number2; // second number to add int sum; // sum of number1 and number2 System.out.print( "Enter first integer: " ); // prompt number1 = input.nextInt(); // read first number from user System.out.print( "Enter second integer: " ); // prompt number2 = input.nextInt(); // read second number from user sum = number1 + number2; // add numbers System.out.printf( "Sum is %d\n", sum ); // display sum } // end method main } Here we input integers. Later we’ll input other types EXPRESSIONS AND OPERATORS expressions are statements that can convey a value. The most common ones are Mathematical + Addition 3+4 * / % Subtraction Multiplication Division Modulus 5-7 5*7 14 / 7 20 % 7 import java.util.Scanner; // program uses class Scanner public class Comparison { // main method begins execution of Java application public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int number1; // first number to compare int number2; // second number to compare System.out.print( "Enter first integer: " ); // prompt number1 = input.nextInt(); // read first number from user System.out.print( "Enter second integer: " ); // prompt number2 = input.nextInt(); // read second number from user if ( number1 == number2 ) System.out.printf( "%d == %d\n", number1, number2 ); if ( number1 != number2 ) System.out.printf( "%d != %d\n", number1, number2 ); if ( number1 < number2 ) System.out.printf( "%d < %d\n", number1, number2 ); if ( number1 > number2 ) System.out.printf( "%d > %d\n", number1, number2 ); if ( number1 <= number2 ) System.out.printf( "%d <= %d\n", number1, number2 ); if ( number1 >= number2 ) System.out.printf( "%d >= %d\n", number1, number2 ); } // method main } // end class Comparison PROGRAM 3 import java.util.Scanner; // program uses class Scanner public class Comparison { // main method begins execution of Java application public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int number1; // first number to compare int number2; // second number to compare System.out.print( "Enter first integer: " ); // prompt number1 = input.nextInt(); // read first number from user System.out.print( "Enter second integer: " ); // prompt number2 = input.nextInt(); // read second number from user PROGRAM 3: CONDITIONS Condition If the condition is true This is run if ( number1 == number2 ) System.out.printf( "%d == %d\n", number1, number2 ); if ( number1 != number2 ) System.out.printf( "%d != %d\n", number1, number2 ); if ( number1 < number2 ) System.out.printf( "%d < %d\n", number1, number2 ); if ( number1 > number2 ) System.out.printf( "%d > %d\n", number1, number2 ); if ( number1 <= number2 ) System.out.printf( "%d <= %d\n", number1, number2 ); if ( number1 >= number2 ) System.out.printf( "%d >= %d\n", number1, number2 ); } // method main } // end class Comparison 3 NOTES ON CONDITIONS Be careful that == is different from = One is a condition the other an assignment. You can do more than one thing in case the condition is true by using the {s If (a == b) { System.out.printf(“A is equal to B”); System.out.printf(“B is equal to A”); } You can use the else keyword to do something if the condition is not met If (a == b) { System.out.printf(“A is equal to B”); } else System.out.printf(“A is different than B”); COMPARISON OPERATORS In an if (expression) { } else {} constructor we can use several comparison operators for expression. They all return true or false == Equal x == 3 != < > <= Not Equal Less than Greater than Less than or equal to x != 3 x<3 x>3 x <= 3 >= Greater than or equal to x >=3 Attention x==3 is very different from x=3. Common mistake!!! SUMMARY Applications and Classes Compile and Running Programs Arithmetic operations Decisions with if and else CLASSES AND OBJECTS GOALS OF THIS LECTURE Classes and Objects Instance Variables and Methods Primitive Types and Reference Types Constructer Methods The double type CLASSES AND OBJECTS Man Car Classes Objects GM EV1 Miguel Reva John OBJECT ORIENTED APPLICATION Class 1 Attributes Methods Class 2 Attributes Class 3 Attributes Methods Methods Objects // Class declaration with one method. public class GradeBook { // display a welcome message to the GradeBook user public void displayMessage() { System.out.println( "Welcome to the Grade Book!" ); } // end method displayMessage } // end class Instantiation // Create a GradeBook object and call its displayMessage method. public class GradeBookTest { // main method begins program execution public static void main( String args[] ) { // create a GradeBook object and assign it to myGradeBook GradeBook myGradeBook = new GradeBook(); // call myGradeBook's displayMessage method myGradeBook.displayMessage(); } // end main } // end class Method Invocation METHODS WITH PARAMETERS // Class declaration with a method that has a parameter. public class GradeBook { // display a welcome message to the GradeBook user public void displayMessage( String courseName ) { System.out.printf( "Welcome to the grade book for\n%s!\n", courseName ); } // end method displayMessage } // end clas METHOD INVOCATION WITH PARAMETERS // Create GradeBook object and pass a String to // its displayMessage method. import java.util.Scanner; // program uses Scanner public class GradeBookTest { // main method begins program execution public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); // create a GradeBook object and assign it to myGradeBook GradeBook myGradeBook = new GradeBook(); // prompt for and input course name System.out.println( "Please enter the course name:" ); String courseName = input.nextLine(); // read a line of text System.out.println(); // outputs a blank line // call myGradeBook's displayMessage method // and pass courseName as an argument myGradeBook.displayMessage( } // end main } // courseName ); METHODS // GradeBook class that contains a courseName instance variable // and methods to set and get its value. public class GradeBook { private String courseName; // course name for this GradeBook Instance Variable (not in a method) Method Return Value // method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // end method setCourseName // method to retrieve the course name public String getCourseName() { return courseName; } // end method getCourseName // display a welcome message to the GradeBook user public void displayMessage() { // this statement calls getCourseName to get the // name of the course this GradeBook represents System.out.printf( "Welcome to the grade book for\n%s!\n", getCourseName() ); } // end method displayMessage } // end class GradeBook // Create and manipulate a GradeBook object. import java.util.Scanner; // program uses Scanner public class GradeBookTest { // main method begins program execution public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); USING IT… // create a GradeBook object and assign it to myGradeBook GradeBook myGradeBook = new GradeBook(); // display initial value of courseName System.out.printf( "Initial course name is: %s\n\n", myGradeBook.getCourseName() ); // prompt for and read course name System.out.println( "Please enter the course name:" ); String theName = input.nextLine(); // read a line of text myGradeBook.setCourseName( theName System.out.println(); // outputs a blank line ); // set the course name // display welcome message after specifying course name myGradeBook.displayMessage(); } // end main PRIMITIVE TYPES AND REFERENCE TYPES All variables have to have a type ! There a 8 primitive types in Java: Boolean, byte, char, short, int, long, float and double All other types are called Reference types. Classes are Reference types OBJECTS WITH CONSTRUCTORS // GradeBook class with a constructor to initialize the course name. public class GradeBook { private String courseName; // course name for this GradeBook // constructor initializes courseName with String supplied as argument public GradeBook( String name ) { courseName = name; // initializes courseName } // end constructor // method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // end method setCourseName // method to retrieve the course name public String getCourseName() { return courseName; } // end method getCourseName // display a welcome message to the GradeBook user public void displayMessage() { // this statement calls getCourseName to get the // name of the course this GradeBook represents System.out.printf( "Welcome to the grade book for\n%s!\n", getCourseName() ); } // end method displayMesssage Constructor methods have the same name as the class USING IT… // GradeBook constructor used to specify the course name at the // time each GradeBook object is created. public class GradeBookTest { // main method begins program execution public static void main( String args[] ) { // create GradeBook object GradeBook gradeBook1 = new GradeBook( ”CPCS 203 JAVA Object Oriented Programming" ); GradeBook gradeBook2 = new GradeBook( ”ELEC2004 OOP2" ); // display initial value of courseName for each GradeBook System.out.printf( "gradeBook1 course name is: %s\n", gradeBook1.getCourseName() ); System.out.printf( "gradeBook2 course name is: %s\n", gradeBook2.getCourseName() ); } // end main } // end class CLASS WITH INSTANCE VARIABLE OF TYPE DOUBLE // Account class with a constructor to // initialize instance variable balance. public class Account { private double balance; // instance variable that stores the balance // constructor public Account( double initialBalance ) { // validate that initialBalance is greater than 0.0; // if it is not, balance is initialized to the default value 0.0 if ( initialBalance > 0.0 ) balance = initialBalance; } // end Account constructor // credit (add) an amount to the account public void credit( double amount ) { balance = balance + amount; // add amount to balance } // end method credit // return the account balance public double getBalance() { return balance; // gives the value of balance to the calling method } // end method getBalance } // end of class // Inputting and outputting floating-point numbers with Account objects. import java.util.Scanner; public class AccountTest { // main method begins execution of Java application public static void main( String args[] ) { Account account1 = new Account( 50.00 ); // create Account object Account account2 = new Account( -7.53 ); // create Account object // display initial balance of each object System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() ); System.out.printf( "account2 balance: $%.2f\n\n", account2.getBalance() ); // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); double depositAmount; // deposit amount read from user System.out.print( "Enter deposit amount for account1: " ); // prompt depositAmount = input.nextDouble(); // obtain user input System.out.printf( "\nadding %.2f to account1 balance\n\n", depositAmount ); account1.credit( depositAmount ); // add to account1 balance USING IT… CONTINUED… // display balances System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() ); System.out.printf( "account2 balance: $%.2f\n\n", account2.getBalance() ); System.out.print( "Enter deposit amount for account2: " ); // prompt depositAmount = input.nextDouble(); // obtain user input System.out.printf( "\nadding %.2f to account2 balance\n\n", depositAmount ); account2.credit( depositAmount ); // add to account2 balance // display balances System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() ); System.out.printf( "account2 balance: $%.2f\n", account2.getBalance() ); } // end main } //end class SUMMARY Classes and Objects Instance Variables and Methods Primitive Types and Reference Types Constructer Methods The double type HOMEWORK 1 In this exercise you are supposed to create a class, instantiate object of that class and call methods on these objects. Program a Java application that performs calculations (addition and multiplication). The application will consist of two classes: A class Calculator that has two instance variables and three methods: setNumbers - which is used to set the numbers addNumbers - which is used to return the sum of the numbers multiplyNumbers - which is used to multiply the numbers A class CalculatorApp that contains the main method and asks the user what he/she wants to do through a menu. Depending what the user wants to do, it needs to call the appropriate methods in the class Calculator and potentially print the results returned. CONTROL STATEMENTS (PART 1) GOALS OF THIS LECTURE Revisit Classes and Objects The if else selection statement The while repetition statement Compound operators Increment Operators LAB CLASS 2 int number1; int number2; main() { public void setNumbers public int addNumbers public int multiplyNumbers } Calculator.java CalculatorApp.java // GradeBook class that contains a courseName instance variable STEP 1: DEFINING A CLASS WITH VARIABLES // and methods to set and get its value. VARIABLES AND METHODS public class GradeBook { private String courseName; // course name for this GradeBook // method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // end method setCourseName Methods // method to retrieve the course name public String getCourseName() { return courseName; } // end method getCourseName // display a welcome message to the GradeBook user public void displayMessage() { // this statement calls getCourseName to get the // name of the course this GradeBook represents System.out.printf( "Welcome to the grade book for\n%s!\n", getCourseName() ); } // end method displayMessage } // end class GradeBook STEP 2: CREATING AN OBJECT OF A CLASS GradeBook variableName = new GradeBook() You choose the name of the variable STEP 3: CALLING METHODS . variableName setCourseName(input); The dot operator . output = variableName getCourseName() IF…ELSE SELECTION STATEMENT Decisions in a typical programming language follow the structure if condition do_something else do_something_else EXAMPLE IN JAVA if (grade >=50) System.out.printf(“Passed”); else System.out.printf(“Failed”); NESTED IF STATEMENTS if (grade >=70) { System.out.printf(“First”); System.out.printf(“Well done”); } else if (grade >=60) System.out.printf(“2.1”); else if (grade >= 50) System.out.printf(“2.2”); If you want to do More than one Thing, you use brackets THE WHILE REPETITION STATEMENT int product =3; while (product <= 100) product = 3 * product; WHILE WITH COUNTER-CONTROLLED REPETITION public void determineClassAverage() { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int total; // sum of grades entered by user int gradeCounter; // number of the grade to be entered next int grade; // grade value entered by user int average; // average of grades // initialization phase total = 0; // initialize total gradeCounter = 1; // initialize loop counter // processing phase while ( gradeCounter <= 10 ) // loop 10 times { System.out.print( "Enter grade: " ); // prompt grade = input.nextInt(); // read grade from user total = total + grade; // add grade to total gradeCounter = gradeCounter + 1;//increment counter by 1 } // end while // termination phase average = total / 10; // integer division yields integer result // display total and average of grades System.out.printf( "\nTotal of all 10 grades is %d\n", total ); System.out.printf( "Class average is %d\n", average ); } // end method determineClassAverage WHILE WITH SENTINEL-CONTROLLED REPETITION public void determineClassAverage() { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int total; // sum of grades int gradeCounter; // number of grades entered int grade; // grade value double average; // number with decimal point for average // initialization phase total = 0; // initialize total gradeCounter = 0; // initialize loop counter // processing phase // prompt for input and read grade from user System.out.print( "Enter grade or -1 to quit: " ); grade = input.nextInt(); // loop until sentinel value read from user while ( grade != -1 ) { total = total + grade; // add grade to total gradeCounter = gradeCounter + 1; // increment counter // prompt for input and read next grade from user System.out.print( "Enter grade or -1 to quit: " ); grade = input.nextInt(); } // end while public void processExamResults() { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); // initializing variables in declarations int passes = 0; // number of passes int failures = 0; // number of failures int studentCounter = 1; // student counter int result; // one exam result (obtains value from user) // process 10 students using counter-controlled loop while ( studentCounter <= 10 ) { // prompt user for input and obtain value from user System.out.print( "Enter result (1 = pass, 2 = fail): " ); result = input.nextInt(); // if...else nested in while if ( result == 1 ) // if result 1, passes = passes + 1; // increment passes; else // else result is not 1, so failures = failures + 1; // increment failures // increment studentCounter so loop eventually terminates studentCounter = studentCounter + 1; } // end while // termination phase; prepare and display results System.out.printf( "Passed: %d\nFailed: %d\n", passes, failures ); // determine whether more than 8 students passed if ( passes > 8 ) System.out.println( "Raise Tuition" ); } // end method processExamResults PUTTING IT ALL TOGETHER COMPOUND ASSIGNMENT OPERATORS Instead of writing c = c + 3 You can write c+=3 Valid for -,*,/,% INCREMENT AND DECREMENT OPERATORS Instead of writing c = c + 1 You can write c++ Instead of writing c = c-1 You can write c-- int a,b; a=3; b=4; a++; b+=a; SUMMARY 3 steps for Object use The if else selection statement The while repetition statement Compound operators Increment Operators CONTROL STATEMENTS (PART 2) UNTIL NOW…. We defined our first basic applications We learned how to Define classes Instantiate Objects Call methods The while loop Compound, Increment and Decrement Operators THE DIFFERENCE BETWEEN A++ AND ++A With a++, we use the variable and then increment it With ++a, we increment the variable and then use it Examples: int a, b; a=3; b=a++; // print a,b int a, b; a=3; b=++a; // print a,b int a, b, c; a=3; b=a++; c=++a; // print a,b,c THE FOR REPETITION STATEMENT A very practical Java constructor is the for repetition statement public class ForCounter { public static void main( String args[] ) { // for statement header includes initialization, // loop-continuation condition and increment for ( int counter = 1; counter <= 10; counter++ ) System.out.printf( "%d ", counter ); System.out.println(); // output a newline } // end main } // end class FOR SYNTAX Control variable Required semicolon separators for ( int counter = 1; counter <= 10 ; counter++) Initial value of Control variable Loop continuation condition Increment of Control variable FOR EXAMPLE WITH DIFFERENT INCREMENT // Counter-controlled repetition with the for repetition statement. public class ForCounter { public static void main( String args[] ) { // for statement header includes initialization, // loop-continuation condition and increment for ( int counter = 1; counter <= 10; ++counter ) System.out.printf( "%d ", counter ); System.out.println(); // output a newline } // end main } // end classs { PUBLIC STATIC VOID MAIN( STRING ARGS[] { ) INT TOTAL = 0; // INITIALIZE TOTAL for example with compound operator // TOTAL EVEN INTEGERS FROM 2 THROUGH 20 FOR ( INT NUMBER = 2; NUMBER <= 20; NUMBER += 2 ) TOTAL += NUMBER; SYSTEM.OUT.PRINTF( "SUM IS %D\N", TOTAL ); // DISPLAY RESULTS } // END MAIN } // END CLASS THE DO…WHILE REPETITION STATEMENT // do...while repetition statement. public class DoWhileTest { public static void main( String args[] ) { int counter = 1; // initialize counter do { System.out.printf( "%d ", counter ); ++counter; } while ( counter <= 10 ); // end do...while System.out.println(); // outputs a newline } // end main } // end class One iteration before condition testing THE SWITCH MULTIPLE-SELECTION STATEMENT public void incrementLetterGradeCounter( int grade ) { // determine which grade was entered switch ( grade / 10 ) { case 9: // grade was between 90 case 10: // and 100 ++aCount; // increment aCount break; // necessary to exit switch case 8: // grade was between 80 and 89 ++bCount; // increment bCount break; // exit switch case 7: // grade was between 70 and 79 ++cCount; // increment cCount break; // exit switch case 6: // grade was between 60 and 69 ++dCount; // increment dCount break; // exit switch default: // grade was less than 60 ++fCount; // increment fCount break; // optional; will exit switch anyway } // end switch } // end method incrementLetterGradeCounter Several options Tested at the same time break after each Option is finished default is used when None of the previous Options was a match } COUNT = 30; BREAK; CASE 2: IF (YEAR % 4 == COUNT = 29; ELSE COUNT = 28; IF ((YEAR % 100 COUNT = 28; 0) == 0) & (YEAR % 400 != 0)) RETURN COUNT; If a break command is not present the program will go to the other “case”s LOGICAL OPERATORS And && Or || Not ! LOGICAL OPERATOR EXAMPLES if ( (a < 3) && ( b!=a ) ) System.out printf(“both are true”); if ( (a >4 ) || ( b==3)) System.out.printf(“one is true”); if (! (a!=3)) System.out.printf(“a is equal to 3); TRANSFORMING WHILE INTO A FOR int a; int a,b; a=3; a=4; b=5; while (a < 4000) { System.out.printf(“%d\n”); a=a+1; } while ((a < a*b) && (a <19)) { System.out.printf(“%d\n”); a+=b; } SUMMARY The for constructor The do…while constructor The switch constructor Logical Operators CONTROL STATEMENTS (PART 2) THE DIFFERENCE BETWEEN A++ AND ++A With a++, we use the variable and then increment it With ++a, we increment the variable and then use it Examples: int a, b; a=3; b=a++; // print a,b int a, b; a=3; b=++a; // print a,b int a, b, c; a=3; b=a++; c=++a; // print a,b,c THE FOR REPETITION STATEMENT A very practical Java constructor is the for repetition statement public class ForCounter { public static void main( String args[] ) { // for statement header includes initialization, // loop-continuation condition and increment for ( int counter = 1; counter <= 10; counter++ ) System.out.printf( "%d ", counter ); System.out.println(); // output a newline } // end main } // end class FOR SYNTAX Control variable Required semicolon separators for ( int counter = 1; counter <= 10 ; counter++) Initial value of Control variable Loop continuation condition Increment of Control variable FOR EXAMPLE WITH DIFFERENT INCREMENT // Counter-controlled repetition with the for repetition statement. public class ForCounter { public static void main( String args[] ) { // for statement header includes initialization, // loop-continuation condition and increment for ( int counter = 1; counter <= 10; ++counter ) System.out.printf( "%d ", counter ); System.out.println(); // output a newline } // end main } // end classs { PUBLIC STATIC VOID MAIN( STRING ARGS[] { ) INT TOTAL = 0; // INITIALIZE TOTAL for example with compound operator // TOTAL EVEN INTEGERS FROM 2 THROUGH 20 FOR ( INT NUMBER = 2; NUMBER <= 20; NUMBER += 2 ) TOTAL += NUMBER; SYSTEM.OUT.PRINTF( "SUM IS %D\N", TOTAL ); // DISPLAY RESULTS } // END MAIN } // END CLASS THE DO…WHILE REPETITION STATEMENT // do...while repetition statement. public class DoWhileTest { public static void main( String args[] ) { int counter = 1; // initialize counter do { System.out.printf( "%d ", counter ); ++counter; } while ( counter <= 10 ); // end do...while System.out.println(); // outputs a newline } // end main } // end class One iteration before condition testing THE SWITCH MULTIPLE-SELECTION STATEMENT public void incrementLetterGradeCounter( int grade ) { // determine which grade was entered switch ( grade / 10 ) { case 9: // grade was between 90 case 10: // and 100 ++aCount; // increment aCount break; // necessary to exit switch case 8: // grade was between 80 and 89 ++bCount; // increment bCount break; // exit switch case 7: // grade was between 70 and 79 ++cCount; // increment cCount break; // exit switch case 6: // grade was between 60 and 69 ++dCount; // increment dCount break; // exit switch default: // grade was less than 60 ++fCount; // increment fCount break; // optional; will exit switch anyway } // end switch } // end method incrementLetterGradeCounter Several options Tested at the same time break after each Option is finished default is used when None of the previous Options was a match } COUNT = 30; BREAK; CASE 2: IF (YEAR % 4 == COUNT = 29; ELSE COUNT = 28; IF ((YEAR % 100 COUNT = 28; 0) == 0) & (YEAR % 400 != 0)) RETURN COUNT; If a break command is not present the program will go to the other “case”s LOGICAL OPERATORS And && Or || Not ! LOGICAL OPERATOR EXAMPLES if ( (a < 3) && ( b!=a ) ) System.out printf(“both are true”); if ( (a >4 ) || ( b==3)) System.out.printf(“one is true”); if (! (a!=3)) System.out.printf(“a is equal to 3); TRANSFORMING WHILE INTO A FOR int a; int a,b; a=3; a=4; b=5; while (a < 4000) { System.out.printf(“%d\n”); a=a+1; } while ((a < a*b) && (a <19)) { System.out.printf(“%d\n”); a+=b; } SUMMARY The for constructor The do…while constructor The switch constructor Logical Operators ARRAYS ARRAYS An array is a group of variables (called elements or components) containing values that all have the same type Name of array Index (or subcript) of the element in array c c[0] -45 c[1] 6 c[2] 0 c[3] 72 c[4] 1000 c[5] 3 Values in the array DECLARING ARRAYS To declare an array we do int c[] = new int[12]; // 12 “slots” in the array Alternatively: int c[]; c = new int[12]; Arrays are considered Objects. Object rules apply ACCESSING ARRAYS sum = c[1] + c[2] +c[3]; // Creating an array. AN EXAMPLE public class InitArray { public static void main( String args[] ) { int array[]; // declare array named array array = new int[ 10 ]; // create the space for array // column headings System.out.printf( "%s%8s\n", "Index", "Value" ); // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%d %d\n", counter, array[ counter ] ); } } // end main } // end USING AN ARRAY INITIALIZER A program can create an array and initialize its elements with an array initializer int n[] = {10,20,30,40,50}; The length of the array is determined by the number of elements in the initializer list ANOTHER EXAMPLE // Initializing the elements of an array with an array initializer. public class InitArray { public static void main( String args[] ) { // initializer list specifies the value for each element int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; // column headings System.out.printf( "%s%8s\n", "Index", "Value" ); // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%d %d\n", counter, array[ counter ] ); } // end main } // end ARRAYS OF OBJECTS class Simple { int a; void init() { a=3; } void changeToTen() { a=10; } void printValue() { System.out.printf("%d\n",a); } } class SimpleArray { public static void main(String[] args) { Simple[] S = new Simple[10]; int i; for (i=0;i<10; i++) { S[i] = new Simple(); S[i].init(); } S[2].changeToTen(); S[1].printValue(); S[2].printValue(); } } Every Member Needs initializing INCREMENT AND DECREMENT // Roll a six-sided die 6000 times. import java.util.Random; public class RollDie { public static void main( String args[] ) { Random randomNumbers = new Random(); // random number generator int frequency[] = new int[ 7 ]; // array of frequency counters // roll die 6000 times; use die value as frequency index for ( int roll = 1; roll <= 6000; roll++ ) ++frequency[ 1 + randomNumbers.nextInt( 6 ) ]; System.out.printf( "%s %s\n", "Face", "Frequency" ); // output each array element's value for ( int face = 1; face < frequency.length; face++ ) System.out.printf( "%d %d\n", face, frequency[ face ] ); } // end main } // end Class ENHANCED FOR STATEMENT In Java we have another type of for statement for( parameter: arrayName) statement AN EXAMPLE… // Using enhanced for statement to total integers in an array. public class EnhancedForTest { public static void main( String args[] ) { int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; int total = 0; // add each element's value to total for ( int number : array ) total += number; System.out.printf( "Total of array elements: %d\n", total ); } // end main } // end class PASSING ARRAYS TO METHODS // Passing arrays and individual array elements to methods. public class PassArray { public static void main( String args[] ) { int array[] = { 1, 2, 3, 4, 5 }; modifyArray( array ); // pass array } public static void modifyArray( int array2[] ) { for ( int counter = 0; counter < array2.length; counter++ ) array2[ counter ] *= 2; } // end method modifyArray } MULTI-DIMENSIONAL ARRAYS Arrays can have more than one dimension These are very useful to store matrices for example: int b[][] = new int[3][4]; We can have as many dimensions as we want; M class MatrixExample ATRIX { public static void main (String[] args) { int m[][] = new int[3][4]; int i,j, total=0; EXAMPLE m[0][0]=3; m[0][1]=4; m[0][2]=23; m[0][3]=45; m[1][0]=1; m[1][1]=0; m[1][2]=45; m[1][3]=9; m[2][0]=3; m[2][1]=1; m[2][2]=45; m[2][3]=99; for(i=0; i < 3; i++) for(j=0; j <4 ; j++) total+=m[i][j]; System.out.printf("Matrix total is %d\n", total); } } VARIABLE LENGTH ARGUMENT LISTS Sometimes you may want a method to have a variable number of parameters For this we use the … constructor public class VarargsTest { // calculate average public static double average( double... numbers ) { double total = 0.0; // initialize total // calculate total using the enhanced for statement for ( double d : numbers ) total += d; return total / numbers.length; } // end method average public static void main( String args[] ) { double d1 = 10.0; double d2 = 20.0; double d3 = 30.0; double d4 = 40.0; System.out.printf( "d1 = %.1f\nd2 = %.1f\nd3 = %.1f\nd4 = %.1f\n\n", d1, d2, d3, d4 ); System.out.printf( "Average of d1 and d2 is %.1f\n", average( d1, d2 ) ); System.out.printf( "Average of d1, d2 and d3 is %.1f\n", average( d1, d2, d3 ) ); System.out.printf( "Average of d1, d2, d3 and d4 is %.1f\n", average( d1, d2, d3, d4 ) ); } // end method} USING COMMAND LINE ARGUMENTS You may have noticed that the main method has parameters. These are parameters that can be passed in the command line when you call the program java Program arg1 arg2 arg3 class CommandLine { public static void main(String args[]) { int i; System.out.printf("You passed %d arguments\n", args.length); for(i=0; i< args.length ; i++) System.out.printf("Argument number %d was %s\n", i+1, args[i]); } } SUMMARY Declaring and using Arrays Arrays of Objects Array initializer Enhanced for statement Passing Arrays to methods Multi-dimensional arrays Variable Length argument lists Using Command Line Arguments ADVANCED CLASSES AND OBJECTS GOALS OF THIS LECTURE Revising some constructors and addressing some common “mistakes” Some advanced topics about classes and objects LOOPS If one wants to run the cycle at least once, the do while cycle is usually the most appropriate If we may not run it even once, the while cycle is usually the most appropriate If you know in advance how many cycles you are going to run (e.g. 100), the for cycle is usually the most appropriate COMMENTS It is very important that you comment your code. For your team, for who marks your exam and for yourself in the future It is good practice to put the comments first and then the code itself public class Time1 { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 THE TIME CLASS CASE STUDY // set a new time value using universal time; ensure that // the data remains consistent by setting invalid values to zero public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); // validate hour minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); // validate minute second = ( ( s >= 0 && s < 60 ) ? s : 0 ); // validate second } // end method setTime // convert to String in universal-time format (HH:MM:SS) public String toUniversalString() { return String.format( "%02d:%02d:%02d", hour, minute, second ); } // end method toUniversalString // convert to String in standard-time format (H:MM:SS AM or PM) public String toString() { return String.format( "%d:%02d:%02d %s", ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ), minute, second, ( hour < 12 ? "AM" : "PM" ) ); } // end method toS public class Time1Test { public static void main( String args[] ) { // create and initialize a Time1 object Time1 time = new Time1(); // invokes Time1 constructor // output string representations of the time System.out.print( "The initial universal time is: " ); System.out.println( time.toUniversalString() ); System.out.print( "The initial standard time is: " ); System.out.println( time.toString() ); System.out.println(); // output a blank line // change time and output updated time time.setTime( 13, 27, 6 ); System.out.print( "Universal time after setTime is: " ); System.out.println( time.toUniversalString() ); System.out.print( "Standard time after setTime is: " ); System.out.println( time.toString() ); System.out.println(); // output a blank line // set time with invalid values; output updated time time.setTime( 99, 99, 99 ); System.out.println( "After attempting invalid settings:" ); System.out.print( "Universal time: " ); System.out.println( time.toUniversalString() ); System.out.print( "Standard time: " ); System.out.println( time.toString() ); } CONTROLLING ACCESS TO MEMBERS Remember the private limits the access to variables and methods Only methods inside the class can access them public class Time2 { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 OVERLOADED CONSTRUCTORS WITH “THIS” // Time2 no-argument constructor: initializes each instance variable // to zero; ensures that Time2 objects start in a consistent state public Time2() { this( 0, 0, 0 ); // invoke Time2 constructor with three arguments } // end Time2 no-argument constructor // Time2 constructor: hour supplied, minute and second defaulted to 0 public Time2( int h ) { this( h, 0, 0 ); // invoke Time2 constructor with three arguments } // end Time2 one-argument constructor // Time2 constructor: hour and minute supplied, second defaulted to 0 public Time2( int h, int m ) { this( h, m, 0 ); // invoke Time2 constructor with three arguments } // end Time2 two-argument constructor // Time2 constructor: hour, minute and second supplied public Time2( int h, int m, int s ) { setTime( h, m, s ); // invoke setTime to validate time } // end Time2 three-argument constructor public void setTime( int h, int m, int s ) { setHour( h ); // set the hour setMinute( m ); // set the minute setSecond( s ); // set the second } // end method setTime // validate and set hour public void setHour( int h ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); } // end method setHour // validate and set minute public void setMinute( int m ) { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); } // end method setMinute // validate and set second public void setSecond( int s ) { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } GET AND SET METHODS GARBAGE COLLECTION AND METHOD FINALIZE When you use the new constructor the java program (which implements what is called the Java Virtual Machine - JVM) allocates memory in your computer for that object Routinely the JVM does Automatic Garbage Collection. It frees the memory of objects that are not needed any more You can run some code in your objects with the finalize method Careful: It is not guaranteed to run public class Employee { private String firstName; private String lastName; private static int count = 0; // number of objects in memory // initialize employee, add 1 to static count and // output String indicating that constructor was called public Employee( String first, String last ) { firstName = first; lastName = last; count++; // increment static count of employees System.out.printf( "Employee constructor: %s %s; count = %d\n", firstName, lastName, count ); } // end Employee constructor // subtract 1 from static count when garbage // collector calls finalize to clean up object; // confirm that finalize was called protected void finalize() { count--; // decrement static count of employees System.out.printf( "Employee finalizer: %s %s; count = %d\n", firstName, lastName, count ); } STATIC CLASS MEMBERS Note the static keyword in the count variable This means that all objects of this class share the same variable FINAL INSTANCE VARIABLES public class Increment { private int total = 0; // total of all increments private final int INCREMENT; // constant variable (uninitialized) // constructor initializes final instance variable INCREMENT public Increment( int incrementValue ) { INCREMENT = incrementValue; // initialize constant variable (once) } // end Increment constructor // add INCREMENT to total public void addIncrementToTotal() { total += INCREMENT; } // end method addIncrementToTotal Can only be Changed in the constructor. Forever // return String representation of an Increment object's data public String toString() { return String.format( "total = %d", total ); } // end method toIncrementString } CREATING PACKAGES Sometimes it is usefull to group classes in packages that other classes can import For this we use the package keyword // Time1 class declaration maintains the time in 24-hour format. package com.deitel.jhtp7.ch08; public class Time1 { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 // set a new time value using universal time; ensure that // the data remains consistent by setting invalid values to zero public void setTime( int h, int) … SUMMARY Choosing the appropriate Loop Comments !!! Private variables Overloading constructors with this Garbage Collection Static Class members Final instance variables Packages QUIZ Write a program that takes as input from the user his/her details (i.e. name, age and gender) and displays the average age of all the people entered. Hint: Person class with the following components: Instance variables name, age, gender. Instance methods setName, getName, and getAge. Class method getAverageAge.