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
Dr.Ammar Almomani Dept. of Information Technology, Al-Huson University College, Al- Balqa Applied University Dr. Ammar Almomani-2017-BAU Page 1 Java Programming Syllabus First semester/ 2017 Course Title: Java Programming Faculty Name: Al-huson University College Dep. Name: Information technology Course No: 30801205 Time: Prerequisite: [Object Oriented programming lab] Location : Credit Hours: 3 Semester: first semester 2016/2017 Instructor: Dr. Ammar ALmomaniEmail: [email protected] Office: # 17 in the 3 ed floor of the Main Building References (How to Program) Paul Deitel, Java How to Program, Early Objects-Pearson Education (2015), 10TH EDITION Course website: https://www.facebook.com/groups/834813086662939/ Course Facebook group: JAVA-2017-Dr-ammar Course Objectives : The following syllabus is designed for a typical undergraduate course where the goal is to introduce students to the concepts of JAVA Programming. We expect the typical undergraduate introductory JAVA Programming course to partially cover the 14 chapters. Evaluation Plan: First Exam Second Exam Home work and quiz Final exam 20% 20% 10% 50% Makeup exams: Only under extreme circumstances will be possible to take make-up exams a student must request a make-up before the scheduled time of the exam if possible. Grading: The mapping from your final score to your letter grade for the course will be determined at the end of the semester by an appropriate curve based on the overall performance of the class Additional Notes The students are expected to obey all university rules during the classes. Notify the instructor by the beginning of the class, if you need to leave the class early that day. The students may be given some additional tasks during the lectures for bonus credit. Attendance: Attendance is required. The university absence policy will be enforced and I reserve the right to award extra credit for perfect attendance Dr. Ammar Almomani-2017-BAU Page 2 Course Outline and Schedule: Ch-No 1 2 3 4 5 Chapters and details 1- Introduction Java 1.1 Introduction 2-Introduction to Java Applications 2.1 Introduction 2.2 Your First Program in Java: Printing a Line of Text 2.3 Modifying Your First Java Program 2.4 Displaying Text with printf 2.5 Another Application: Adding Integers 2.6 Memory Concepts viii Contents 2.7 Arithmetic 2.8 Decision Making: Equality and Relational Operators 3- Introduction to Classes, Objects, Methods and Strings 3.1 Introduction 3.2 Declaring a Class with a Method and Instantiating an Object of a Class 3.3 Declaring a Method with a Parameter 3.4 Instance Variables, set Methods and get Methods 3.5 Primitive Types vs. Reference Types 3.6 Initializing Objects with Constructors 3.7 Floating-Point Numbers and Type double 4 Control Statements: Part 1 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection Statement 4.6 if…else Double-Selection Statement 4.7 while Repetition Statement 4.8 Formulating Algorithms: Counter-Controlled Repetition 4.9 Formulating Algorithms: Sentinel-Controlled Repetition 4.10 Formulating Algorithms: Nested Control Statements 4.11 Compound Assignment Operators 4.12 Increment and Decrement Operators 4.13 Primitive Types 5-Control Statements: Part 2 5.1 Introduction 5.2 Essentials of Counter-Controlled Repetition 5.3 for Repetition Statement 5.4 Examples Using the for Statement 5.5 do…while Repetition Statement 5.6 switch Multiple-Selection Statement 5.7 break and continue Statements 5.8 Logical Operators Dr. Ammar Almomani-2017-BAU Hours 1 2 1.30 1.30 1.30 Page 3 6 7 8 9 10 11 6-Methods: A Deeper Look 6.1 Introduction 6.2 Program Modules in Java 6.3 static Methods, static Fields and Class Math 6.4 Declaring Methods with Multiple Parameters 6.5 Notes on Declaring and Using Methods 6.6 Method-Call Stack and Activation Records 6.7 Argument Promotion and Casting 6.8 Java API Packages 7 Arrays and ArrayLists 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using Arrays 7.5 Case Study: Card Shuffling and Dealing Simulation 7.6 Enhanced for Statement 7.7 Passing Arrays to Methods 7.9 Multidimensional Arrays First exam 20% 8- Classes and Objects: A Deeper Look 8.1 Introduction 8.2 Time Class Case Study 8.3 Controlling Access to Members 8.4 Referring to the Current Object’s Members with the this Reference 8.6 Default and No-Argument Constructors 8.7 Notes on Set and Get Methods 8.8 Composition 8.9 Enumerations 9- Object-Oriented Programming: Inheritance 9.1 Introduction 9.2 Superclasses and Subclasses 9.3 protected Members 9.4 Relationship between Superclasses and Subclasses 9.4.1 Creating and Using a CommissionEmployee Class 9.4.2 Creating and Using aBasePlusCommissionEmployee Class 9.4.3 Creating a CommissionEmployee–BasePlus CommissionEmployee Inheritance Hierarchy 9.5 Constructors in Subclasses 10- Object-Oriented Programming: Polymorphism 10.1 Introduction 10.2 Polymorphism Examples 10.3 Demonstrating Polymorphic Behavior 11- Exception Handling: A Deeper Look 11.1 Introduction 11.2 Example: Divide by Zero without Exception Handling 11.3 Example: Handling ArithmeticExceptions and InputMismatchExceptions 11.4 When to Use Exception Handling 11.5 Java Exception Hierarchy Dr. Ammar Almomani-2017-BAU 3 3 4.30 4.30 1.30 4.30 Page 4 11.6 finally Block 11.7 Stack Unwinding and Obtaining Information from an Exception Object 11.8 Chained Exceptions 11.9 Declaring New Exception Types 11.10 Preconditions and Postconditions 11.11 Assertions 11.12 (New in Java SE 7) Multi-catch: Handling Multiple Exceptions in One catch 12 17 12 GUI Components: Part 1 12.1 Introduction 12.2 Java’s Nimbus Look-and-Feel 12.3 Simple GUI-Based Input/Output with JOptionPane 12.4 Overview of Swing Components 12.5 Displaying Text and Images in a Window 12.6 Text Fields and an Introduction to Event Handling with Nested Classes 12.7 Common GUI Event Types and Listener Interfaces 12.8 How Event Handling Works 12.9 JButton 12.10 Buttons That Maintain State 12.10.1 JCheckBox 12.10.2 JRadioButton 12.11 JComboBox; Using an Anonymous Inner Class for Event Handling 12.12 JList 12.13 Multiple-Selection Lists 12.14 Mouse Event Handling Second exam 20% 17 Files, Streams and Object Serialization 17.1 Introduction 17.2 Files and Streams 17.3 Class File 17.4 Sequential-Access Text Files 17.4.1 Creating a Sequential-Access Text File 726xiv Contents 17.4.2 Reading Data from a Sequential-Access Text File 27 Networking 27.1 Introduction 27.2 Manipulating URLs 27.3 Reading a File on a Web Server 27 27.4 Establishing a Simple Server Using Stream Sockets 27.5 Establishing a Simple Client Using Stream Sockets 27.6 Client/Server Interaction with Stream Socket Connections 27.7 Datagrams: Connectionless Client/Server Interaction Final exam 50% Dr. Ammar almomani Good luck Dr. Ammar Almomani-2017-BAU 3 3 4.30 Page 5 Ch1 - Introduction to Java 1.1 Introduction: James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991 Java as free and open-source software, (FOSS)all of Java's core code available under free software/open-source distribution terms Java is the world’s most widely used computer programming language. The number of mobile Internet users will reach approximately 134 million by 2013. Smartphone sales are projected to surpass personal computer sales in 2011 and tablet sales to account for over 20% of all personal computer sales by 2015. By 2014, the smartphone applications market is expected to exceed $40 billion, which is creating significant opportunities for programming mobile applications. Recognizing this, Sun Microsystems funded an internal corporate research project led by James Gosling, which resulted in a C++-based object-oriented programming language Sun called Java. Key goal of Java is to be able to write programs that will run on a great variety of computer systems and computer-control devices. This is sometimes called “write once, run anywhere.” Sun saw the potential of using Java to add dynamic content to web pages. Sun Microsystems was acquired by Oracle in 2009. As of 2010 97% of enterprise desktops, three billion handsets, and 80 million television devices run Java. Java is the most widely used software development language in the world. 1.2 Java Platform 1- Standard Edition or Java SE: is a widely used platform for development and deployment of portable applications for desktop and server environments.[1] Java SE uses the object-oriented Java programming language. Java SE defines a wide range of general purpose APIs – such as Java APIs for the Java Class Library. One of the most well-known implementations of Java SE is Oracle Corporation's Java Development Kit (JDK). Dr. Ammar Almomani-2017-BAU Page 6 2- Java Micro Edition (Java ME) Geared toward developing applications for small, memory-constrained devices, such as BlackBerry smartphones. 3- JAVA enterprise applications (Java EE):typically run in server environments. 1.3 Java and a Typical Java Development Environment Java programs normally go through five phases ◦ edit ◦ compile ◦ load ◦ verify ◦ execute. Download the JDK and its documentation from ◦ www.oracle.com/technetwork/java/javase/downloads/index.html. 1.3 Java programs normally go through five phases Phase 1:consists of editing a file ◦ ◦ ◦ Type a Java program (source code) using the editor. like (eclipse, net beans, notepad. Jcreator) Integrated development environments (IDEs) :Provide tools that support the software development process Including editors for writing and editing programs and debuggers for locating logic errors—errors that cause programs to execute incorrectly. Phase 2: Compiling a Java Program into Byte codes Use the command javac (the Java compiler) to compile a program. For example, to compile a program called Welcome.java Java compiler translates Java source code into bytecodes that represent the tasks to execute. Bytecodes are executed by the Java Virtual Machine (JVM)—a part of the JDK and the foundation of the Java platform. Virtual machine (VM)—a software application that simulates a computer ◦ Hides the underlying operating system and hardware from the programs that interact with it. If the same VM is implemented on many computer platforms, applications that it executes can be used on all those platforms. Phase 3: Loading a Program into Memory ◦ The JVM places the program in memory to execute it—this is known as loading. Phase 4: Byte code Verification Dr. Ammar Almomani-2017-BAU Page 7 ◦ ◦ As the classes are loaded, the byte code verifier examines their byte codes Ensures that they’re valid and do not violate Java’s security restrictions. Phase 5: Execution ◦ The JVM executes the program’s byte codes. ◦ JVMs typically execute byte codes using a combination of interpretation and so-called just-in-time (JIT) compilation. Analyzes the byte codes as they’re interpreted ◦ A just-in-time (JIT) compiler—known as the Java Hot Spot compiler—translates the byte codes into the underlying computer’s machine language. Dr. Ammar Almomani-2017-BAU Page 8 Fig1:Java programs normally go through five phases Dr. Ammar Almomani-2017-BAU Page 9 2-Introduction to Java Applications 2.1 Introduction 2.2 Your First Program in Java: Printing a Line of Text CH2: ex1_welcome package ch2; public class ex1_welcome { //main method public static void main(String[] args) { System.out.print("hello world!_"); // System.out meaning object, println is command System.out.println("welcome to java"); System.out.println("welcome \n to \n java"); System.out.printf("%s\n%s\n", "welcome to" , "java program"); /*System.out.printf method f means “formatted” displays formatted data , fixed text using print or println and format specifiers using percent sign (%). */ } //end method main } // end class ex1_welcome run: hello world!_welcome to java welcome to java welcome to java program Why Is Method main Declared static ? public static void main( String[] args ) Answer: When you execute the Java Virtual Machine (JVM) with the java command, the JVM Attempts to invoke the main method of the class you specify—when no objects of the class have been created. Declaring main as static allows the JVM to invoke main without creating an instance of the class. Dr. Ammar Almomani-2017-BAU Page 10 CH2: ex2_sum_two_numbers(SUM two numbers and IF statement) package ch2; import java.util.Scanner; // program uses class Scanner public class ex2_sum_two_numbers { // Addition program that displays the sum of two numbers. // main method begins execution of Java application public static void main( String[] args ) { // create a Scanner to obtain input from the 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, then store total in sum System.out.printf( "Sum is %d\n", sum ); // display sum as decimal number 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 ); } // end method main } // end class Addition run: Enter first integer: 2 Enter second integer: 3 Sum is 5 2 != 3 2<3 2 <= 3 Dr. Ammar Almomani-2017-BAU Page 11 CH3:- Introduction to Classes, Objects, Methods and Strings Classes are an expanded concept of data structures: like data structures, they can instance variables, but they can also contain methods as members. An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable. Object-Oriented Programming(OOP) may be seen as a collection of cooperating objects A Java method is a collection of statements that are grouped together to perform an operation. For using a method, it should be called. There are two ways in which a method is called i.e. method returns a value or returning nothing (no return value). Declaring the main Method public static void main( String[] args ) { } Dr. Ammar Almomani-2017-BAU Page 12 UML class diagram Three compartments. Top: contains the class name centered horizontally in boldface type. Middle: contains the class’s attributes, which correspond to instance variables Bottom: contains the class’s operations, which correspond to methods. The plus sign (+) corresponds to the keyword public The minus sign (-) corresponds to the keyword private Dr. Ammar Almomani-2017-BAU Page 13 CH3:ex1_GradeBookTest package ch3; Parentheses in combination with a class name represent a call to a constructor, which is public class GradeBookTest { public static void main (String Args[]) { GradeBook myGradeBook=new GradeBook(); myGradeBook.displayMessage(); } // end main } // end class GradeBookTest similar to a method but is used only at the time an object is created to initialize the object’s data. package ch3; A static method (such as main) is special public class GradeBook { It can be called without first creating an object of the class in which the method is declared. // display a welcome message to the GradeBook user public void displayMessage() { System.out.println(“Welcome to the Grade Book!”); } // end method displayMessage } // end class GradeBook GradeBook myGradeBook=new GradeBook(); Meaning create Gradebook Object and assign it to variable my GradeBook myGradeBook.displayMessage(); meaning invoked method displayMessage(). Typically, you cannot call a method that belongs to another class until you create an object of that class. run: Welcome to the Grade Book! Dr. Ammar Almomani-2017-BAU Page 14 CH3_ex2: (using parameters with class and methods) package ch3_2; 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 ); Parameter: Additional information a method needs to perform its task. A method call supplies values— called arguments—for each of the method’s parameters. } // end method displayMessage } // end class GradeBook More on Arguments and Parameters package ch3_2; The number of arguments in a method call must match the number of parameters in the parameter list of the method’s declaration. 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 GradeBookmyGradeBook = 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 (string text) System.out.println(); // outputs a blank line // call myGradeBook'sdisplayMessage method // and pass courseName as an argument myGradeBook.displayMessage(courseName ); } // end main } // end class GradeBookTest Dr. Ammar Almomani-2017-BAU The argument types in the method call must be “consistent with” the types of the corresponding parameters in the method’s declaration. Notes on import Declarations Classes that are compiled in the same directory on disk are in the same package—known as the default package. Classes System and String are in package java.lang Package name followed by a dot (.) and the class name. run: Please enter the course name: Java Haw To Program Welcome to the grade book for Java Haw To Program! Page 15 CH3_ex3: Instance Variables, set Methods and get Methods package ch3_3; // 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 // 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() { // 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 A class normally consists of one or more methods that manipulate the attributes that belong to a particular object of the class. Attributes are represented as variables in a class declaration. Called fields. Instance variable: Declared inside a class declaration but outside the bodies of the class’s method declarations. When each object of a class maintains its own copy of an attribute, the field is an instance variable Each object (instance) of the class has a separate instance of the variable in memory. Every instance (i.e., object) of a class contains one copy of each instance variable. Instance variables typically declared private. private is an access modifier. private variables and methods are accessible only to methods of the class in which they are declared. Declaring instance private is known as data hiding or information hiding. Set and get methods used to access instance variables Dr. Ammar Almomani-2017-BAU Page 16 package ch3_3; 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 ); One method of a class can call another method of the same class by using just the method name. EX: getCourseName() every field has a default initial value—a value provided by Java The default value for a field of type String is null EX: WDQD // 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 );// set the course name System.out.println(); // outputs a blank line // display welcome message after specifying course name myGradeBook.displayMessage(); } // end main } // end class GradeBookTest Classes often provide public methods to allow clients to set (i.e., assign values to) or get (i.e., obtain the values of) private instance variables. The names of these methods need not begin with set or get, but this naming convention is recommended. A minus sign (–) access modifier corresponds to access modifier private. run: Initial course name is: null Please enter the course name: JAVA PROGRAMMING Welcome to the grade book for JAVA PROGRAMMING! Dr. Ammar Almomani-2017-BAU Page 17 3.5 Primitive Types vs. Reference Types Types are divided into primitive types and reference types. The primitive types are boolean, byte, char, short, int, long, float and double. All nonprimitive types are reference types. A primitive-type variable can store exactly one value of its declared type at a time. Primitive-type instance variables are initialized by default—variables of types byte, char, short, int, long, float and double are initialized to 0, and variables of type boolean are initialized to false. You can specify your own initial value for a primitive-type variable by assigning the variable a value in its declaration 3.6 Initializing Objects with Constructors When an object of a class is created, its instance variables are initialized by default. Each class can provide a constructor that initializes an object of a class when the object is created. Java requires a constructor call for every object that is created. Keyword new requests memory from the system to store an object, then calls the corresponding class’s constructor to initialize the object. A constructor must have the same name as the class. Initializing Objects with Constructors (Cont.) By default, the compiler provides a default constructor with no parameters in any class that does not explicitly include a constructor. Instance variables are initialized to their default values. Can provide your own constructor to specify custom initialization for objects of your class. A constructor’s parameter list specifies the data it requires to perform its task. Constructors cannot return values, so they cannot specify a return type. Normally, constructors are declared public. If you declare any constructors for a class, the Java compiler will not create a default constructor for that class. Q1: Write a program in java language to design the following UML class with its object and variables? The output should be as follow run: gradeBook1 course name is: CS101 Introduction to Java Programming gradeBook2 course name is: CS102 Data Structures in Java Dr. Ammar Almomani-2017-BAU Page 18 Answer:Q1 CH3_ex4 package ch3_4; public class GradeBook { private String courseName; // course name for this GradeBook // constructor initializes courseName with String argument Public GradeBook( String name ) // constructor name is class name { courseName = name; // initializes courseName } // end constructor // method to retrieve the course name public String getCourseName() { return courseName; } // end method getCourseName } // end class GradeBook package ch3_4; public class GradeBookTest { // main method begins program execution public static void main( String[] args ) { // create GradeBook object GradeBook gradeBook1 = new GradeBook ("CS101 Introduction to Java Programming"); //gradebook1 and gradebook2 are reference variable GradeBook gradeBook2 = new GradeBook("CS102 Data Structures in Java"); // 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 GradeBookTest Dr. Ammar Almomani-2017-BAU Page 19 Q2: Write a program in java programming language to design the following UML class with its object and variables Program uses Scanner The output should be as follow run: gradeBook1 course name is: CS101 Introduction to Java Programming gradeBook2 course name is: CS102 Data Structures in Java Initial course name is: java how to program Please enter the course name: Java programming Welcome to the grade book for Java programming! Dr. Ammar Almomani-2017-BAU Page 20 Answer:Q3 package ch3_ex5; 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("java how to program"); // create GradeBook object GradeBook gradeBook1 = new GradeBook( "CS101 Introduction to Java Programming" ); GradeBook gradeBook2 = new GradeBook( "CS102 Data Structures in Java" ); // 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() ); // 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 ); // set the course name System.out.println(); // outputs a blank line // display welcome message after specifying course name myGradeBook.displayMessage(); } // end main } // end class GradeBookTest Dr. Ammar Almomani-2017-BAU Page 21 package ch3_ex5; public class GradeBook { private String courseName; // course name for this GradeBook public GradeBook( String name ) // constructor name is class 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() { // 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 Dr. Ammar Almomani-2017-BAU Page 22 3.7 Floating-Point Numbers and Type double Q3: Write a program in java language to design the following UML class with its object and variables AccountTest Main() Depositamount:double The output as follow using float and double variables Dr. Ammar Almomani-2017-BAU Page 23 Answer:Q4 CH3_ex6:Bank account system using double values package ch3_6; 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 %f is used to output values of type float or double. .2 represents the number of decimal places (2) to output to the right of the decimal point Ex:%.2f // 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 class Account Dr. Ammar Almomani-2017-BAU Page 24 package ch3_6; importjava.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.println( "Enter deposit amount for account1: " ); // prompt depositAmount = input.nextDouble(); // obtain user input System.out.printf( "\n adding %.2f to account1 balance\n\n", depositAmount ); account1.credit(depositAmount ); // add to account1 balance // 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 AccountTest Dr. Ammar Almomani-2017-BAU Page 25 Ch4.control statement 1 Three types of selection statements. if statement: if ( studentGrade>= 60 ) System.out.println( "Passed" ); Format: if ( condition ) Statement; Format: if…else statement: if ( grade >= 60 ) System.out.println( "Passed" ); else System.out.println( "Failed" ); Ch4_ex1: if else if : Multiple-Selection Statement (1) if ( Condition ) StatementOne; else StatementTwo; Java’s logical operators enable you to form more complex conditions by combining simple conditions. The logical operators are package ch4_ex1; public class if_else { public static void main(String args[]){ int x = 30; if( x == 10 ){ System.out.print("Value of X is 10"); } else if( x == 20 ){ System.out.print("Value of X is 20"); } else if( x == 30 ){ System.out.println("Value of X is 30"); System.out.println("Value of X is 30"); } else{ System.out.print("This is else statement"); } } } run: Value of X is 30 Value of X is 30 Dr. Ammar Almomani-2017-BAU && (conditional AND) || (conditional OR) & (boolean logical AND) | (boolean logical inclusive OR) ^ (boolean logical exclusive OR) ! (logical NOT). & <-- verifies both operands && <-- stops evaluating if the first operand evaluates to false since the result will be false (x != 0) & (1/x > 1) <-- this means evaluate (x != 0) then evaluate (1/x > 1) then do the &. the problem is that for x=0 this will throw an exception. (x != 0) && (1/x > 1) <-- this means evaluate (x != 0) and only if this is true then evaluate (1/x > 1) so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1). Page 26 switch statement: Multiple-Selection Statement (2) Format switch ( Controlling expression ) { case const_var_1: … block of statements….. break; case const_var_2: … block of statements….. break; //case statements may be repeated as many times as necessary default: //cases other than above listed } Dr. Ammar Almomani-2017-BAU note: in switch statement you can use only the current data type 1- int 2- double not float 3- char 4- string 5- short 6-bool or boolean (0,1) ex: using string switch( city ) { case "Maynard": zipCode = "01754"; break; case "Marlborough": zipCode = "01752"; break; case "Framingham": zipCode = "01701"; break; } // end switch Page 27 Ch4_ex2:switch Selection Statement package ch4_2; import java.util.Scanner; public class Switch { public static void main(String args[]){ { Scanner input= new Scanner(System.in); int grade; System.out.print("enter your grade (1,2,3,4,5):\n"); grade= input.nextInt(); switch (grade) { case 1 : System.out.print("Excellent!" ); case 2 : case 3 : System.out.print( "Well done" ); break; case 5 : System.out.print("You passed" ); case 6 : System.out.print("Better try again" ); break; default : System.out.print("Invalid grade"); } System.out.printf("Your grade is %d\n", grade); }}} Dr. Ammar Almomani-2017-BAU run: enter your grade (1,2,3,4,5): 3 Well done Your grade is 3 -----------------------------run: enter your grade (1,2,3,4,5): 5 You passed Better try again Your grade is 5 -----------------------------run: enter your grade (1,2,3,4,5): 7 Invalid grade Your grade is 7 Page 28 5.Three repetition statements (also called looping statements) while and for statements int product =3; while ( product <= 100 ) product = 3 * product; The do…while statement performs the action(s) in its body one or more times. if, else, switch, while, do and for are keywords The general form of the while statement is initialization; while ( loop Continuation Condition ) { statement increment; 2.Control statement part2: (while Repetition Statement) } Ch4.ex3: package ch4_3; public class While { public static void main( String[] args ) { int sum; int x; x = 1; sum = 0; while ( x <= 10 ) { sum += x; ++x; } System.out.printf( "The sum is: %d\n", sum ); }} Dr. Ammar Almomani-2017-BAU x 1 2 3 4 5 6 7 8 9 10 sum 0-->1 3 6 10 15 21 28 36 45 55 output The sum is:55 run: The sum is: 55 Page 29 Ch4.ex4:write aprograme to calculate the current series (12+22+32+......+102) ? public class while2 { public static void main( String[] args ) { int y; int x = 1; int total = 0; while ( x <= 10 ) { y = x * x; System.out.println( y ); total += y; ++x; } // end while x 1 2 3 4 5 . . . . . y 1 4 9 16 25 . . . . . total 0 4 13 29 54 . . . . . output 1 4 9 16 25 . . . . . Total is 385 run: 1 4 9 16 25 36 49 64 81 100 Total is 385 System.out.printf( "Total is %d\n", total ); } // end main } // end class Mystery Ch4.ex5: write a program to draw the current shap? package ch4_5; public class while5 { public static void main( String[] args ) { int count = 1; while ( count <= 10 ) { System.out.println( count % 2 == 1 ? "****" : "++++++++" ); ++count; } // end while } // end main } Dr. Ammar Almomani-2017-BAU run: **** ++++++++ **** ++++++++ **** ++++++++ **** ++++++++ **** ++++++++ Note: 1%2=1 2%2=0 3%1=1 Page 30 Ch4.ex6: write a program to draw the current shap? package ch4.pkg6; public class while6 { public static void main( String[] args ) { int row = 10; int column; while ( row >= 1 ) { column = 1; while ( column <= 10 ) { System.out.print( row % 2 == 1 ? "<" : ">" ); ++column; } // end while --row; System.out.println(); } // end while } // end main } Dr. Ammar Almomani-2017-BAU row column 10 1 2 3 . . . 10 9 1 2 . . . 10 8 ... 7 ... . ... . . 1 ... output >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< . . . <<<<<<<<<< run: >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< Page 31 ch4.ex7: write a program to calculate the total and average of student score until user entering (-1) using while statement? package ch4_7; import java.util.Scanner; public class while7 { public static void main(String[] args) { System.out.print("enter grade or -1 to quit:"); Scanner input = new Scanner(System.in); int grade; grade= input.nextInt(); double total =0.0; int gradecounter = 0; while(grade!=-1) { total= total + grade; gradecounter++; System.out.print("enter grade or -1 to quit:"); grade= input.nextInt(); } if (gradecounter!=0) { double average =(double)total/gradecounter; System.out.printf("total=%.2f\n",total); System.out.printf("average=%.2f\n",average); } else System.out.print("no grade was entered"); }} Dr. Ammar Almomani-2017-BAU run: enter grade or -1 to quit:30 enter grade or -1 to quit:70 enter grade or -1 to quit:80 enter grade or -1 to quit:-1 total=180.00 average=60.00 Page 32 Ch4.ex8: package ch4_8; public class increment { public static void main( String[] args ) { int c; // demonstrate postfix increment operator c = 5; // assign 5 to c System.out.println( c ); System.out.println( c++ ); System.out.println( c ); System.out.println(); // skip a line // demonstrate prefix increment operator c = 5; // assign 5 to c System.out.println( c ); System.out.println( ++c ); System.out.println( c ); System.out.println(); // skip a line run: 5 5 6 5 6 6 5 5 4 5 4 4 c = 5; // assign 5 to c System.out.println( c ); System.out.println( c-- ); System.out.println( c ); System.out.println(); // skip a line // demonstrate prefix increment operator c = 5; // assign 5 to c System.out.println( c ); System.out.println( --c ); System.out.println( c ); }} Dr. Ammar Almomani-2017-BAU Page 33 //CH4_ex9 package Increment; import java.util.Scanner; public class Increment { public static void main( String[] args ) { System.out.println("please enetr your choice from 0-6"); Scanner input = new Scanner( System.in ); int i = input.nextInt(); // read first double From left to right in java to calculate increment or decrement in equation int x = 5, y = 8; switch (i) { case 0: x+=(++x)+(x++); System.out.printf("x =%d\n", x); break; 1) x= x+=(++x)+(x++); 2) x=5+6+6 =17 case 1: 1) x= x + ++y; 2) x= 5+9 =14 x+=++y; System.out.printf ("x =%d\n", x); break; case 2: x+=2*x++; System.out.printf ("x =%d\n", x); break; x= x+ 2*x++; 5+2*5 =15 Note : next x value = 6 because x++ appear At the end of equation Dr. Ammar Almomani-2017-BAU Page 34 case 3: x=--y+x--+x; System.out.printf ("x =%d\n", x); break; x= --y+x--+x; x= 7+5+4 =16 Note: we calculate x-- because it appear before the end of equation case 4: x-=(-y)%3; System.out.printf ("x =%d\n", x); break; case 5: y+=--y+x-y%x--; System.out.printf ("y =%d\n", y); break; case 6: x= ++y - --x + y++; System.out.printf ("x =%d\n", x); break; 1)x= x- (-y)%3; 5-(-8)%3 5--2=7 1) y= y+--y+x-y%x--; 8+7+5-7%5 8+7+5-2= 18 x= ++y - --x + y++; 9-4+9 5+9=14 Note: y++ value in next will be 10 } } Dr. Ammar Almomani-2017-BAU Page 35 Ch5-Control statement 2 For Statement Format: for (Initialization; Test; Update counter) { //the block of code which is executed multiple times } Initialization : Variable declaration and Initialization. Test : A boolean expression. Update: Update the Variable. Ch5.ex1: package ch5_1; public class For { public static void main( String[] args ) { int total = 0; // 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 ); } } Dr. Ammar Almomani-2017-BAU run: Sum is 110 Page 36 Note:The increment expression in a for acts as if it were a standalone statement at the end of the for’s body, so counter = counter + 1 counter += 1 ++counter counter++ are equivalent increment expressions in a for statement. Example: For example, assume that x = 2 and y = 10. If x and y are not modified in the body of the loop, the statement for (int j = x; j <= 4 * x * y; j += y / x) is equivalent to the statement for (int j = 2; j <= 80; j += 5) Ch5.ex2: package ch5_2; // total even integers from 2 through 20 public class for2 { public static void main( String[] args ) { int total = 0; for ( int number = 2; number <= 20;total += number, System.out.printf( "number is %d Sum is %d\n", number, total ), number += 2); }} run: number is 2 Sum is 2 number is 4 Sum is 6 number is 6 Sum is 12 number is 8 Sum is 20 number is 10 Sum is 30 number is 12 Sum is 42 number is 14 Sum is 56 number is 16 Sum is 72 number is 18 Sum is 90 number is 20 Sum is 110 Ch5.ex3 :nested for statement package ch5_3; public class nested_for { public static void main(String[] args) { int num1, num2; for(num1=0;num1<=3;num1++) { for(num2=0;num2<=2;num2++) { System.out.printf("num1=%d num2=%d",num1,num2); System.out.println(); } } }} Dr. Ammar Almomani-2017-BAU run: num1=0 num2=0 num1=0 num2=1 num1=0 num2=2 num1=1 num2=0 num1=1 num2=1 num1=1 num2=2 num1=2 num2=0 num1=2 num2=1 num1=2 num2=2 num1=3 num2=0 num1=3 num2=1 num1=3 num2=2 Page 37 Ch5.ex4: do-while statement Format //condition variable is initiated do { Statement //condition variable is updated } while ( Condition ); package ch5_4; public class do_while { 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 } } run: 1 2 3 4 5 6 7 8 9 10 Ch5: break and continue Statements Ch5.ex5: break statement package ch5_5; run: public class Break { 1234 public static void main( String[] args ) { int count; for ( count = 1; count <= 10; count++ ) { if ( count == 5 ) // if count is 5, break; System.out.printf( "%d ", count ); } System.out.printf( "\n Broke out of loop at count = %d\n", count ); } } Dr. Ammar Almomani-2017-BAU Broke out of loop at count = 5 The break statement causes program control to proceed with the first statement after the switch. Or terminates the loop Page 38 CH5_ex6: continue statement The continue statement causes program control to terminates the loop immediately and program control continues package ch5_6; public class Continue { public static void main( String[] args ) { int count; for ( count = 1; count <= 10; count++ ) { if ( count == 5 ) // if count is 5, continue; // terminate loop System.out.printf( "%d ", count ); } System.out.printf( "\n Broke out of loop at count = %d\n", count ); }} run: 1 2 3 4 6 7 8 9 10 Broke out of loop at count = 11 CH5_ex7 The Logical Operators are && (conditional AND) || (conditional OR) ! (logical NOT). Example1: if ( gender == 1 && age >= 65 ) seniorFemales++; Example2: if ( 3<x && x<7 ) { System.out.print(“you are welcome”) } public static void main(String[] args) { int x = 25; Note: &:evaluates both sides of the operation. if(x < 50 && x > 0) { System.out.println("OK"); } if(x < 50 & x > 0) { System.out.println("Yup" ); } }} Output: &&:evaluates the left side of the operation, if it's true, it continues and evaluates the right side. The same condition for other OK Yup Dr. Ammar Almomani-2017-BAU Page 39 Local and non local variable Local Variable: Variables declared in the loop structure only exist within the block Variables declared outside the loop structure are non-local variables. The values of these variables are kept after finishing each iteration of the loop structure. Ch5_ex8: Local and non local variable package ch5_8; run: public class localvariable { couter=1 x= 1 couter=2 x= 1 couter=3 x= 1 couter=4 x= 1 public static void main(String[] args) { int x=1; //non local variable for (int counter = 1; counter<=4; counter++) // counter is local variable { System.out.printf("couter=%d x= %d\n",counter,x); } } } Ch5.9:error in counter definition package ch5_9; Run public class Error { public static void main(String[] args) { Error , because counter in final statement is undefined , outside for statement int x=1; //non local variable for (int counter = 1; counter<=4; counter++) // counter local variable { System.out.printf("couter=%d x= %d\n",counter,x); } System.out.printf("couter=%d } } Dr. Ammar Almomani-2017-BAU x= %d\n", counter, x); Page 40 Ch5.ex10: nested for with break statement package ch5.ex10; run: public class Nestedfor { 2 is prime public static void main(String[] args) { inti, j; for(i=2; i<=7; i++) { for(j=2; j <= (i/j); j++) if(!(i%j==1)) break; if(j > (i/j)) System.out.printf("%d is prime\n",i); } } } For-Cond(T/F) I J COUT F 2 2 2 is prime F 3 2 3 is prime T (break) !(0==1) 4 2 No print T F (break) F 5 2 No print 5 3 5 is prime 3 is prime 5 is prime 7 is prime !(1==1) F F F 6 2 No print T F !(1==1) 7 2 No print 7 3 7 is prime T (break) !(1==1) T Dr. Ammar Almomani-2017-BAU Page 41 Ch6: Methods: A Deeper Look Dr. Ammar Almomani-2017-BAU Page 42 6.3 static Methods, static Fields and Class Math (Cont.) Ch6_ex1: static Methods or class method Perform common tasks package ch6_1; public class Static_Methods { run: Math.abs( -23.7 ) = 23.700000 Math.floor( 9.2 ) = 9.000000 public static void main( String[] args ) { System.out.printf( "Math.abs( -23.7 ) = %f\n", Math.abs( -23.7 ) ); System.out.printf( "Math.floor( 9.2 ) = %f\n", Math.floor( 9.2 ) ); System.out.printf( "Math.floor( -9.8 ) = %f\n",Math.floor( -9.8 ) ); System.out.printf( "Math.max( 2.3, 12.7 ) = %f\n",Math.max( 2.3, 12.7 )); System.out.printf( "Math.min( 2.3, 12.7 ) = %f\n", Math.min( 2.3, 12.7 ) ); System.out.printf( "Math.pow( 2.0, 7.0 ) = %f\n", Math.pow( 2.0, 7.0 ) ); System.out.printf( "Math.sqrt( 900.0 ) = %f\n", Math.sqrt( 900.0 ) ); System.out.printf( "Math.PI = %f\n", Math.PI ); System.out.printf( "Math.E = %f\n", Math.E ); } // end main } // end class Math.floor( -9.8 ) = -10.000000 Math.max( 2.3, 12.7 ) = 12.700000 Math.min( 2.3, 12.7 ) = 2.300000 Math.pow( 2.0, 7.0 ) = 128.000000 Math.sqrt( 900.0 ) = 30.000000 Math.PI = 3.141593 Math.E = 2.718282 Math fields for common mathematical constants Math class constants PI and E ◦ Math.PI = (3.141593) ◦ Math.E = (2.718282) PI and E are declared final because their values never change. System.out.println(Math.sqrt( 4 ) ); correctly evaluates Math.sqrt(4) and prints the value 2.0. The method declaration’s parameter list causes Java to convert the int value 4 to the double value 4.0 before passing the value to method sqrt. Such conversions may lead to compilation errors if Java’s promotion rules are not satisfied Dr. Ammar Almomani-2017-BAU Page 43 Ch6_ex2: // obtain three floating-point values and determine maximum value package ch6_ex2; importjava.util.Scanner; public class MaximumFinder { public static void main( String[] args ) { // create Scanner for input from command window Scanner input = new Scanner( System.in ); System.out.print( "Enter three floating-point values separated by spaces: " ); double number1 = input.nextDouble(); // read first double double number2 = input.nextDouble(); // read second double double number3 = input.nextDouble(); // read third double double result = maximum( number1, number2, number3 ); System.out.println( "Maximum is: " + result ); } public static double maximum( double x, double y, double z ) { double maximumValue = x; if ( y >maximumValue ) maximumValue = y; if ( z >maximumValue ) maximumValue = z; return maximumValue; } // end method maximum } // end class MaximumFinder run: Enter three floating-point values separated by spaces: 3.2 5.7 1.1 Maximum is: 5.7 Note: To Implement Method maximum by Reusing Method Math.max return Math.max( x, Math.max( y, z ) ); Dr. Ammar Almomani-2017-BAU Page 44 6.5 Notes on Declaring and Using Methods Three ways to call a method: 1- Using a method name by itself to call another method of the same class : like ch6_ex2 page 44 maximum( number1, number2, number3 ) 2- Using a variable that contains a reference to an object, followed by a dot (.) and the method name to call a method of the referenced object such as maximumFinder.determineMaximum() 3- Using the class name and a dot (.) to call a static method of a class such as Math.sqrt(900.0) Note: A static method can call only other static methods of the same class directly (i.e., using the method name by itself) and can manipulate only static variables in the same class directly. Such as return Math.max( x, Math.max( y, z ) ); There are three ways to return control to the statement that calls a method. 1- If the method does not return a result, use return; 2- is executed. If the method returns a result, use the statement return expression; 3- evaluates the expression, then returns the result to the caller. Such as return 20; or return x; 4- if we have void method don't use return 6.8 Java API Packages Package java.applet java.awt java.io java.lang java.net java.util Description The Java Applet Package contains a class and several interfaces required to create Java applets—programs that execute in web browsers. The Java Abstract Window Toolkit Package contains the classes and interfaces required to create and manipulate GUIs The Java Input/Output Package contains classes and interfaces that enable programs to input and output data. The Java Language Package contains classes and interfaces, This package is imported by the compiler into all programs The Java Networking Package contains classes and interfaces that enable programs to communicate via computer networks like the Internet. The Java Utilities Package contains utility classes and interfaces that enable such actions as date and time manipulations, random-number Dr. Ammar Almomani-2017-BAU Page 45 6.9 Case Study: Random-Number Generation Simulation and game playing element of chance Class Random (package java.util) static method random of class Math. Objects of class Random can produce random boolean, byte, float, double, int, long and Gaussian values Math method random can produce only double values in the range 0.0 <= x < 1.0. Ch6.ex3 : Shifted and scaled random integers. import java.util.Random; // program uses class Random public class random { // Fig. 6.6: RandomIntegers.java // Shifted and scaled random integers. public static void main( String[] args ) { Random randomNumbers = new Random(); // random number generator int face; // stores each random integer generated // loop 20 times for ( int counter = 1; counter <= 20; counter++ ) { // pick random integer from 1 to 6 face = 1 + randomNumbers.nextInt( 6 ); System.out.printf( "%d ", face ); // display generated value // if counter is divisible by 5, start a new line of output if ( counter % 5 == 0 ) System.out.println(); } // end for } // end main } // end class RandomIntegers run: 4 3 2 6 1 2 6 3 4 2 5 6 2 5 2 1 1 1 5 5 number = shiftingValue + randomNumbers.nextInt( scalingFactor ); ex: face = 1 + randomNumbers.nextInt( 6 ); range from 1-6 note: 1+randomeNumber.nextInt(6) =1+ rand()%6 (C++ language) 0%6=0,1%6=1,2%6-2 .....5%6=5,6%6=0 : the range (1-6) because ( 1+0=1)...(5+1=6) Dr. Ammar Almomani-2017-BAU Page 46 6.11 Scope of Declarations Basic scope rules: The scope of a parameter declaration is the body of the method in which the declaration appears. The scope of alocal-variable declaration is from the point at which the declaration appears to the end of that block. The scope of a local-variable declaration that appears in the initialization section of a for statement’s header is the body of the for statement and the other expressions in the header. A method or field’s scope is the entire body of the class. Any block may contain variable declarations. If a local variable or parameter in a method has the same name as a field of the class, the field is “hidden” until the block terminates execution—this is called shadowing. Ch6_ex4:Scope package ch6_4; public class scope { // Scope class demonstrates field and local variable scopes. // field that is accessible to all methods of this class private static int x = 1; // method main creates and initializes local variable x // and calls methods useLocalVariable and useField public static void main( String[] args ) { int x = 5; // method's local variable x shadows field x System.out.printf( "local x in main is %d\n", x ); { x=7; System.out.printf( " shadowing x in main is %d\n", x ); } // shadowing. useLocalVariable(); // useLocalVariable has local x useField(); // useField uses class Scope's field x useLocalVariable(); // useLocalVariable reinitializes local x useField(); // class Scope's field x retains its value System.out.printf( "\nlocal x in main is %d\n", x ); } // end main // create and initialize local variable x during each call public static void useLocalVariable() { int x = 25; // initialized each time useLocalVariable is called System.out.printf( "\nlocal x on entering method useLocalVariable is %d\n", x ); ++x; // modifies this method's local variable x System.out.printf( "local x before exiting method useLocalVariable is %d\n", x ); } // end method useLocalVariable Dr. Ammar Almomani-2017-BAU Page 47 // modify class Scope's field x during each call public static void useField() { System.out.printf( "\nfield x on entering method useField is %d\n", x ); x *= 10; // modifies class Scope's field x System.out.printf( "field x before exiting method useField is %d\n", x ); } // end method useField } // end class Scope run: local x in main is 5 shadowing x in main is 7 local x on entering method useLocalVariable is 25 local x before exiting method useLocalVariable is 26 field x on entering method useField is 1 field x before exiting method useField is 10 local x on entering method useLocalVariable is 25 local x before exiting method useLocalVariable is 26 field x on entering method useField is 10 field x before exiting method useField is 100 local x in main is 5 Dr. Ammar Almomani-2017-BAU Page 48 Ch6_ex5: Method Overload public class MethodOverload { // test overloaded square methods public static void main( String[] args ) { System.out.printf( "Square of integer 7 is %d\n", square( 7 ) ); System.out.printf( "Square of double 7.5 is %f\n", square( 7.5 ) ); } // square method with int argument public static int square( int intValue ) { System.out.printf( "\n Called square with int argument: %d\n", intValue ); return intValue * intValue; } // end method square with int argument // square method with double argument public static double square( double doubleValue ) { System.out.printf( "\n Called square with double argument: %f\n", doubleValue ); return doubleValue * doubleValue; } // end method square with double argument } // end class MethodOverload run: Called square with int argument: 7 Square of integer 7 is 49 Called square with double argument: 7.5 Square of double 7.5 is 56.25 Dr. Ammar Almomani-2017-BAU Page 49 Ch7-Arrays and Array lists Arrays Data structures consisting of related data items of the same type. Make it convenient to process related groups of values. Remain the same length once they are created. Common array manipulations with static methods of class Arrays from the java.util package. Array is Group of variables (called elements) containing values of the same type. Arrays are objects so they are reference types. Elements can be either primitive or reference types. ArrayList collection Similar to arrays Dynamic resizing They automatically increase their size at execution time to accommodate additional elements Note: An index must be a nonnegative integer. Every array object knows its own length and stores it in a length instance variable. length cannot be changed because it’s a final variable. 7.3 Declaring and Creating Arrays Declaration and array-creation expression for an array of 12 int elements int[] c = new int[ 12 ]; Can be performed in two steps as follows: int[] c; // declare the array variable c = new int[ 12 ]; // creates the array Dr. Ammar Almomani-2017-BAU Page 50 When an array is created, each element of the array receives a default value Zero for the numeric primitive-type elements, false for boolean elements and null for references. Array initializer A comma-separated list of expressions (called an initializer list) enclosed in braces. int[] n = { 10, 20, 30, 40, 50 }; Creates a five-element array with index values 0–4. Ch7_ex1: Index Fig. 7.2 uses keyword new to create an array of 10 int elements which are initially zero (the default for int variables).,included initialize 10 element of array . package ch7_1; public class Index{ public static void main( String[] args ) { int[] array; // declare array named array array = new int[ 10 ]; // create the array object // initializer list specifies the value for each element int[] array2 = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings Ch7_ex2: Array initializer // output each array element's value for ( int counter = 0; counter <array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] ); for ( int counter = 0; counter < array2.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array2[ counter ] ); } // end main } // end class InitArray Dr. Ammar Almomani-2017-BAU Index 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 Value 0 0 0 0 0 0 0 0 0 0 32 27 64 18 95 14 90 70 60 37 Page 51 Ch7_ex2: creates a 10-element array and assigns to each element one of the even integers from 2 to 20 (2, 4, 6, …, 20).? package ch7_2; public class even { public static void main( String[] args ) { int ARRAY_LENGTH = 10; // constant int[] array = new int[ ARRAY_LENGTH ]; // create array Index Value 0 2 1 4 2 6 3 8 4 10 // calculate value for each array element for ( int counter = 0; counter <array.length; counter++ ) array[ counter ] = 2 + 2 * counter; 5 12 6 14 System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings 7 16 // output each array element's value for ( int counter = 0; counter <array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] ); }} 8 18 9 20 ch7_ex3: Computing the sum of the elements of an array. package ch7_3; public class SumArray { 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 counter = 0; counter <array.length; counter++ ) total += array[ counter ]; System.out.printf( "Total of array elements: %d\n", total ); } } Dr. Ammar Almomani-2017-BAU Total of array elements: 849 // Using enhanced for statement Iterates through the elements of an array without using a counter // The enhanced for statement can be used only to obtain array elements It cannot be used to modify elements. for ( int number : array ) total += number; Syntax: for ( parameter : arrayName ) statement; Page 52 Note in array: Format specifier%02d indicates that an int value should be formatted as a field of two digits. The 0 flag displays a leading 0 for values with fewer digits than the field width (2). ch7_ex4: // Bar chart printing program. package ch7_4;: // Bar chart printing program. public class BarChart { public static void main( String[] args ) { int[] array = { 0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1 }; System.out.println( "Grade distribution:" ); // for each array element, output a bar of the chart for ( int counter = 0; counter <array.length; counter++ ) { // output bar label ( "00-09: ", ..., "90-99: ", "100: " ) if ( counter == 10 ) System.out.printf( "%5d: ", 100 ); else System.out.printf( "%02d-%02d: ", counter * 10, counter * 10 + 9 ); // print bar of asterisks for ( int stars = 0; stars < array[ counter ]; stars++ ) System.out.print( "*" ); System.out.println(); // start a new line of output } } } Dr. Ammar Almomani-2017-BAU Page 53 7.7 Passing Arrays to Methods To pass an array argument to a method, specify the name of the array without any brackets. To receive an array, the method’s parameter list must specify an array parameter. When an argument to a method is an entire array or an individual array element of a reference type, the called method receives a copy of the reference. (Pass-by-reference (also called call-by-reference) send full array When an argument to a method is an individual array element of a primitive type, the called method receives a copy of the element’s value. Pass-by-value (also called call-by-value) send some elements of array ch7_ex5: Passing Arrays to Methods package ch7_5; public class PassArray { // main creates array and calls modifyArray and modifyElement public static void main( String[] args ) { int[] array = { 1, 2, 3, 4, 5 }; System.out.println( "Effects of passing reference to entire array:\n" + "The values of the original array are:" ); // output original array elements for ( int value : array ) System.out.printf( " %d", value ); modifyArray( array ); // pass array reference System.out.println( "\n\nThe values of the modified array are:" ); // output modified array elements for ( int value : array ) System.out.printf( " %d", value ); System.out.printf( "\n\nEffects of passing array element value:\n" + "array[3] before modifyElement: %d\n", array[ 3 ] ); modifyElement( array[ 3 ] ); // attempt to modify array[ 3 ] System.out.printf( "array[3] after modifyElement: %d\n", array[ 3 ] ); } Dr. Ammar Almomani-2017-BAU Page 54 public static void modifyArray( int array2[] ) { for ( int counter = 0; counter < array2.length; counter++ ) array2[ counter ] *= 2; } public static void modifyElement( int element ) { element *= 2; System.out.printf( "Value of element in modifyElement: %d\n", element ); } } Dr. Ammar Almomani-2017-BAU Page 55 7.9 Multidimensional Arrays Java does not support multidimensional arrays directly Allows you to specify one-dimensional arrays whose elements are also onedimensional arrays, thus achieving the same effect. In general, an array with m rows and n columns is called an m-by-n array. A two-dimensional array b with two rows and two columns could be declared and initialized with nested array initializers as follows: int[][] b = { { 1, 2 }, { 3, 4 } }; The lengths of the rows in a two-dimensional array are not required to be the same: int[][] b = { { 1, 2 }, { 3, 4, 5 } }; A multidimensional array with the same number of columns in every row can be created with an array-creation expression. int[][] b = new int[ 3 ][ 4 ]; 3 rows and 4 columns. A multidimensional array in which each row has a different number of columns can be created as follows: int[][] b = new int[ 2 ][ ]; // create 2 rows b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0 b[ 1 ] = new int[ 3 ]; // create 3 columns for row 1 Creates a two-dimensional array with two rows. Row 0 has five columns, and row 1 has three columns. Dr. Ammar Almomani-2017-BAU Page 56 Note: you should determine the size both of row and column in multidimensional array, other you will have error message , because Java does not support multidimensional arrays directly examples public static void main(String args[]) { int [][]b=new int[2][]; b[0]=new int[5]; b[1]=new int[5]; for (int row=0;row<b.length;row++){ for (int col=0;col<b.length;col++){ System.out.printf("%d\n", b[row][col]); } } } run: public static void main(String args[]) { int [][]b=new int[2][]; b[0]=new int[5]; for (int row=0;row<b.length;row++) { for (int col=0;col<b.length;col++) { System.out.printf("%d\n", b[row][col]); } } } run: public static void main(String args[]) { int [][]b=new int[2][]; for (int row=0;row<b.length;row++) { for (int col=0;col<b.length;col++) { System.out.printf("%d\n", b[row][col]); } } } run: run: public static void main(String args[]) { int [][]b=new int[0][2]; for (int row=0;row<b.length;row++) { for (int col=0;col<b.length;col++) { System.out.printf("%d\n", b[row][col]); } } } run: run: Dr. Ammar Almomani-2017-BAU 0 0 0 0 0 0 Exception in thread "main" java.lang.NullPointerException at test.While7.main(While7.java:21) Exception in thread "main" java.lang.NullPointerException at test.While7.main(While7.java:21) Exception in thread "main" java.lang.NullPointerException at test.While7.main(While7.java:21) Page 57 Ch7_ex6:// create and output two-dimensional arrays package ch7_6; public class tow_dimentional { public static void main( String[] args ) { int[][] array1 = { { 1, 2, 3 }, { 4, 5, 6 } }; int[][] array2 = { { 1, 2 }, { 3 }, { 4, 5, 6 } }; System.out.println( "Values in array1 by row are" ); outputArray( array1 ); // displays array1 by row System.out.println( "\nValues in array2 by row are" ); outputArray( array2 ); // displays array2 by row } // output rows and columns of a two-dimensional array public static void outputArray( int[][] array ) { // loop through array's rows for ( int row = 0; row <array.length; row++ ) { // loop through columns of current row for ( int column = 0; column < array[ row ].length; column++ ) System.out.printf( "%d ", array[ row ][ column ] ); System.out.println(); // start new line of output } }} run: Values in array1 by row are 1 2 3 4 5 6 Values in array2 by row are 1 2 3 4 5 6 Dr. Ammar Almomani-2017-BAU Page 58 ch7_ex7:TASK1:We need A Function to find the sum of two dimensional arrays A and B user will detect the size of array and the content as an example bellow? package ch7_7; import java.util.Scanner; public class sumtwoarray { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter number of rows: "); int rows = s.nextInt(); System.out.print("Enter number of columns: "); int columns = s.nextInt(); int[][] a = new int[rows][columns]; int[][] b = new int[rows][columns]; System.out.println("Enter the first matrix"); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { a[i][j] = s.nextInt(); } } System.out.println("Enter the second matrix"); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { b[i][j] = s.nextInt(); } } int[][] c = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { c[i][j] = a[i][j] + b[i][j]; } } System.out.println("The sum of the two matrices is"); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.print(c[i][j] + " "); } System.out.println(); } } } Dr. Ammar Almomani-2017-BAU run: Enter number of rows: 2 Enter number of columns: 3 Enter the first matrix 347 184 Enter the second matrix 321 104 The sum of the two matrices is 668 288 Page 59 CH8:Classes and Objects: A Deeper Look 8.2 Time Class Case Study Ch8_ex1: package ch8_1; public class Time1Test { public static void main( String[] args ) { // create and initialize a Time1 object Time1 time = new Time1(); // invokes Time1 constructor Class Time1 does not declare a constructor, so the class has a default constructor that is supplied by the compiler. // 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(); Access modifiers public and private control access to a class’s variables and methods. Each instance variable implicitly receives the default value 0 for an int. public methods present to the class’s clients a view of the services the class provides (the class’s public interface). // 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 System.out.print( "Universal time: " ); Clients need not be concerned with how the class accomplishes its tasks. private class members are not accessible outside the class. Method setTime and Throwing Exceptions (cont.) // attempt to set time with invalid values For incorrect values, setTime throws an exception of type IllegalArgumentException try { time.setTime( 99, 99, 99 ); // all values out of range } catch ( IllegalArgumentException e ) { System.out.printf( "Exception: %s\n\n", e.getMessage() ); end catch Notifies the client code that an invalid argument was passed to the method. } // // display time after attempt to set invalid values System.out.println( "After attempting invalid settings:" ); System.out.println(time.toUniversalString() ); @######! System.out.print( "Standard time: " ); System.out.println(time.toString() ); } // end main } // end class Time1Test Dr. Ammar Almomani-2017-BAU Can use try...catch to catch exceptions and attempt to recover from them. The throw statement creates a new object of type IllegalArgumentException. In this case, we call the constructor that allows us to specify a custom error message. After the exception object is created, the throw statement immediately terminates method setTime and the exception is returned to the code that attempted to set the time. Page 60 package ch8_1; public class Time1 { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 public void setTime( int h, int m, int s ) { if ( ( h >= 0 && h < 24 ) && ( m >= 0 && m < 60 ) && ( s>= 0 && s < 60 ) ) { hour = h; minute = m; second = s; } else throw new IllegalArgumentException( "hour, minute and/or second was out of range" ); } // convert to String in universal-time format (HH:MM:SS) public String toUniversalString() { return String.format( "%02d:%02d:%02d", hour, minute, second ); } 8.3 Controlling Access to Members Access modifiers public and private control access to a class’s variables and methods. public methods present to the class’s clients a view of the services the class provides (the class’s public interface). Clients need not be concerned with how the class accomplishes its tasks. For this reason, the class’s private variables and private methods (i.e., its implementation details) are not accessible to its clients. // 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" ) ); }} private class members are not accessible outside the class. run: The initial universal time is: 00:00:00 The initial standard time is: 12:00:00 AM Universal time after setTime is: 13:27:06 Standard time after setTime is: 1:27:06 PM Universal time: After attempting invalid settings: 13:27:06 Standard time: 1:27:06 PM Dr. Ammar Almomani-2017-BAU Page 61 8.4 Referring to the Current Object’s Members with the this Reference Ch8:ex2 public class ThisTest { public static void main( String[] args ) { SimpleTime time = new SimpleTime( 15, 30, 19 ); System.out.println(time.buildString() ); } // end main } // end class ThisTest // class SimpleTime demonstrates the "this" reference Class SimpleTime { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 // if the constructor uses parameter names identical to // instance variable names, the "this" reference is // required to distinguish between the names public SimpleTime( int hour, int minute, int second ) { this.hour = hour; // set "this" object's hour this.minute = minute; // set "this" object's minute this.second = second; // set "this" object's second } // end SimpleTime constructor // use explicit and implicit "this" to call toUniversalString public String buildString() { return String.format( "%24s: %s\n%24s: %s", "this.toUniversalString()", this.toUniversalString(), "toUniversalString()", toUniversalString() ); } // end method buildString // convert to String in universal-time format (HH:MM:SS) public String toUniversalString() { // "this" is not required here to access instance variables, // because method does not have local variables with same // names as instance variables return String.format( "%02d:%02d:%02d", hour, minute, second ); } // end method toUniversalString } // end class SimpleTime Dr. Ammar Almomani-2017-BAU Referring to the Current Object’s Members with the this Reference Every object can access a reference to itself with keyword this. When a non-static method is called for a particular object, the method’s body implicitly uses keyword this to refer to the object’s instance variables and other methods. Enables the class’s code to know which object should be manipulated. Can also use keyword this explicitly in a non-static method’s body. Can use the this reference implicitly and explicitly. If a method contains a local variable with the same name as a field, that method uses the local variable rather than the field. The local variable shadows the field in the method’s scope. A method can use the this reference to refer to the shadowed field explicitly. this explicitly in a non-static method’s body this cannot be used in a static method run: this.toUniversalString(): 15:30:19 toUniversalString(): 15:30:19 Page 62 8.5 Time Class Case Study: Overloaded Constructors ch8_ex3: Overloaded Constructors // Overloaded constructors used to initialize Time2 objects. public class Time2Test { public static void main( String[] args ) { Time2 t1 = new Time2(); // 00:00:00 Time2 t4 = new Time2( 12, 25, 42 ); // 12:25:42 Time2 t5 = new Time2( t4 ); // 12:25:42 System.out.println( "Constructed with:" ); System.out.println( "t1: all arguments defaulted" ); System.out.printf( " %s\n", t1.toUniversalString() ); System.out.println( "t4: hour, minute and second specified" ); System.out.printf( " %s\n", t4.toUniversalString() ); System.out.println( "t5: Time2 object t4 specified" ); System.out.printf( " %s\n", t5.toUniversalString() ); } // end main } // end class Time2Test Overloaded constructors enable objects of a class to be initialized in different ways. To overload constructors, simply provide multiple constructor declarations with different signatures. Recall that the compiler differentiates signatures by the number of parameters, the types of the parameters and the order of the parameter types in each signature Uses this in method-call syntax to invoke the Time2 constructor Using the this reference as shown here is a popular way to reuse initialization code provided by another of the class’s constructors rather than defining similar code in the no-argument constructor’s body. We use this syntax in four of the five Time2 constructors to make the class easier to maintain and modify. this reference that is allowed only as the first statement in constructor’s body Dr. Ammar Almomani-2017-BAU Page 63 public class Time2 { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 // Time2 no-argument constructor: // initializes each instance variable to zero public Time2() { this( 0, 0, 0 ); // invoke Time2 constructor with three arguments } // end Time2 no-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 // Time2 constructor: another Time2 object supplied public Time2( Time2 time ) { // invoke Time2 three-argument constructor this(time.getHour(), time.getMinute(), time.getSecond() ); } // end Time2 constructor with a Time2 object argument public void setTime( int h, int m, int s ) { setHour( h ); setMinute( m ); setSecond( s ); } public void setHour( int h ) { hour=((h >= 0 && h<24)?h:0); } public void setMinute( int m ) { minute=((m >= 0 && m<60)?m:0); } public void setSecond( int s ) { second =((s >= 0 && s<60)?s:0); } // end method setSecond Dr. Ammar Almomani-2017-BAU public int getHour() { return hour; } public int getMinute() { return minute; } public int getSecond() { return second; } // convert to String in universal-time format (HH:MM:SS) public String toUniversalString() { return String.format( "%02d:%02d:%02d", getHour(), getMinute(), getSecond() ); } } run: Constructed with: t1: all arguments defaulted 00:00:00 t4: hour, minute and second specified 12:25:42 t5: Time2 object t4 specified 12:25:42 Page 64 8.6 Default and No-Argument Constructors Every class must have at least one constructor. If you do not provide any in a class’s declaration, the compiler creates a default constructor that takes no arguments when it’s invoked.(zero for primitive numeric types,false for boolean values and null for references) If your class declares constructors, the compiler will not create a default constructor. 8.7 Notes on Set and Get Methods Classes often provide public methods to allow clients of the class to set(i.e., assign values to) or get (i.e., obtain the values of) private instance variables. Set methods are also commonly called mutator methods, because they typically change an object’s state—i.e., modify the values of instance variables. Get methods are also commonly called accessor methods or query methods. Dr. Ammar Almomani-2017-BAU Page 65 8.8 Composition: A class can have references to objects of other classes as members. The example in this web pageand is Employee objects having to Date objects. This isused called composition is sometimes referred to references as a has-a relationship. Employee.java has instance variables for the employee's first name, last name, date, it’s and date of Example: An AlarmClock object needs to know the current time and the birth time when hire: two String objects anditstwo Datesoobjects. A Date object, as defined by Date.java, hasobjects instance supposed to sound alarm, it’s reasonable to include two references to Time in an variablesobject. for month, and year: all in its. EmployeeTest.java creates two Date objects, which are then used to create an Employee object. ch8_4:EmployeeTest package ch8_4; public class EmployeeTest { public static void main( String[] args ) { Date birth = new Date( 7, 1949 ); Date hire = new Date( 3, 1988 ); Employee employee = new Employee( "Bob", "Blue", birth, hire ); System.out.println( employee ); // implicitly invokes the Employee’s toString method to display the values of its instancevariables }} Dr. Ammar Almomani-2017-BAU Page 66 package ch8_4; public class Date { private int month; // 1-12 private int year; // any year Constructor Date output the this reference as a String. Since this is a reference to the current Date object, the object’s to-String method public Date( int theMonth,int theYear ) { month = checkMonth( theMonth ); // validate month year = theYear; // could validate year public String toString() is called implicitly to obtain the object’s String representation System.out.printf( "Date object constructor for date %s\n", this ); } // end Date constructor // utility method to confirm proper month value private int checkMonth( int testMonth ) { if ( testMonth> 0 && testMonth<= 12 ) // validate month return testMonth; else // month is invalid throw new IllegalArgumentException( "month must be 1-12" ); } // end method checkMonth // return a String of the form month/day/year public String toString() { return String.format( "%d/%d", month, year ); } // end method toString } // end class Date Dr. Ammar Almomani-2017-BAU Page 67 package ch8_4; public class Employee { private String firstName; private String lastName; private Date birthDate; private Date hireDate; Class Employee Members birthDate and hireDate are references to Date objects. This demonstrates that a class can have as instance variables references to objects of other classes. // constructor to initialize name, birth date and hire date public Employee( String first, String last, Date dateOfBirth, Date dateOfHire ) { firstName = first; lastName = last; birthDate = dateOfBirth; hireDate = dateOfHire; } // end Employee constructor // convert Employee to String format public String toString() { returnString.format( "%s, %s Hired: %s Birthday: %s", lastName, firstName, hireDate, birthDate ); } // end method toEmployeeString } // end class Employee run: Date object constructor for date 7/1949 Date object constructor for date 3/1988 Blue, Bob Hired: 3/1988 Birthday: 7/1949 Dr. Ammar Almomani-2017-BAU Page 68 8.11 static Class Members In certain cases, only one copy of a particular variable should be shared by all objects of a class. A static field—called a class variable—is used in such cases. A static variable represents classwide information—all objects of the class share the same piece of data. The declaration of a static variable begins with the keyword static. Static variables have class scope. Can access a class’s public static members through a reference to any object of the class, or by qualifying the member name with the class name and a dot (.), as in Math.random(). private static class members can be accessed by client code only through methods of the class. static class members are available as soon as the class is loaded into memory at execution time. To access a public static member when no objects of the class exist (and even when they do), prefix the class name and a dot (.) to the static member, as in Math.PI. To access a private static member when no objects of the class exist, provide a public static method and call it by qualifying its name with the class name and a dot. Dr. Ammar Almomani-2017-BAU Page 69 A static method cannot access non-static class members, because a static method can be called even when no objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static method. The this reference must refer to a specific object of the class, and when a static method is called, there might not be any objects of its class in memory. If a static variable is not initialized, the compiler assigns it a default value—in this case 0, the default value for type int. String objects in Java are immutable—they cannot be modified after they are created. Therefore, it’s safe to have many references to one String object. If String objects are immutable, you might wonder why are we able to use operators + and += to concatenate String objects The following syntax imports a particular static member: import static packageName.ClassName.staticMemberName; import static java.lang.System.out import static java.lang.Math.PI; import static.java.lang.Math.cos; where packageNameis the package of the class, ClassName is the name of the class and staticMemberName is the name of the static field or method. The following syntax imports all static members of a class: import static packageName.ClassName.*; import static.java.lang.Math.*; * indicates that all static members of the specified class should be available for use in the class(es) declared in the file. static import declarations import only static class members. Regular import statements should be used to specify the classes used in a program. Keyword final specifies that a variable is not modifiable (i.e., it’s a constant) and any attempt to modify it is an error. private final int INCREMENT; Declares a final (constant) instance variable INCREMENT of type int. Dr. Ammar Almomani-2017-BAU Page 70 ch8_ex5: // Static variable used to maintain a count of the number of Employee objects in memory. package ch8_5; public class Employee { private String firstName; private String lastName; private static int count = 0; // number of Employees created // 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 // get first name public String getFirstName() { return firstName; } // end method getFirstName // get last name public String getLastName() { return lastName; } // end method getLastName // static method to get static count value public static int getCount() { return count; } // end method getCount } // end class Employee Dr. Ammar Almomani-2017-BAU Page 71 public class EmployeeTest { public static void main( String[] args ) { // show that count is 0 before creating Employees System.out.printf( "Employees before instantiation: %d\n", Employee.getCount() ); // create two Employees; count should be 2 Employee e1 = new Employee( "Susan", "Baker" ); Employee e2 = new Employee( "Bob", "Blue" ); // show that count is 2 after creating two Employees System.out.println( "\n Employees after instantiation: " ); System.out.printf( "via e1.getCount(): %d\n", e1.getCount() ); System.out.printf( "via e2.getCount(): %d\n", e2.getCount() ); System.out.printf( "via Employee.getCount(): %d\n", Employee.getCount() ); // get names of Employees System.out.printf( "\n Employee 1: %s %s\n Employee 2: %s %s\n", e1.getFirstName(), e1.getLastName(), e2.getFirstName(), e2.getLastName() ); // in this example, there is only one reference to each Employee, // so the following two statements indicate that these objects } // end main } // end class EmployeeTest run: Employees before instantiation: 0 Employee constructor: Susan Baker; count = 1 Employee constructor: Bob Blue; count = 2 Employees after instantiation: via e1.getCount(): 2 via e2.getCount(): 2 via Employee.getCount(): 2 Employee 1: Susan Baker Employee 2: Bob Blue Dr. Ammar Almomani-2017-BAU Page 72 Chapter 9:Object-Oriented Programming: Inheritance Inheritance A form of software reuse in which a new class is created by absorbing an existing class’s members and embellishing them with new or modified capabilities. inherit the members of an existing class. Existing class is the superclass New class is the subclass Each subclass can be a superclass of future subclasses. A subclass can add its own fields and methods. A subclass is more specific than its superclass and represents a more specialized group of objects. The subclass exhibits the behaviors of its superclass and can add behaviors that are specific to the subclass. This is why inheritance is sometimes referred to as specialization. The direct superclass is the superclass from which the subclass explicitly inherits. An indirect superclass is any class above the direct superclass in the class hierarchy. The Java class hierarchy begins with class Object (in package java.lang) Every class in Java directly or indirectly extends (or “inherits from”) Object. Java supports only single inheritance, in which each class is derived from exactly one direct superclass. Dr. Ammar Almomani-2017-BAU Page 73 We distinguish between the is-a relationship and the has-a relationship Is-a represents inheritance In an is-a relationship, an object of a subclass can also be treated as an object of its superclass Has-a represents composition In a has-a relationship, an object contains as members references to other objects : Note Maruti Suzuki Cars an employee has a BirthDate, and an Employee has a Telephone Number Dr. Ammar Almomani-2017-BAU Page 74 Dr. Ammar Almomani-2017-BAU Page 75 Modifier | Class | Package | Subclass | World(y : accessible , n : not accessible ) ————————————+———————+—————————+——————————+——————— public | y | y | y | y ————————————+———————+—————————+——————————+——————— protected | y | y | y | n ————————————+———————+—————————+——————————+——————— no modifier | y | y | n | n ————————————+———————+—————————+——————————+——————— private | y | n | n | n Inheritance issue A subclass can inherit methods that it does not need or should not have. The subclass can override (redefine) the superclass method with an appropriate implementation. 9.3 protected Members A class’s public members are accessible wherever the program has a reference to an object of that class or one of its subclasses. A class’s private members are accessible only within the class itself. protected access is an intermediate level of access between public and private. A superclass’s protected members can be accessed by members of that superclass, by members of its subclasses and by members of other classes in the same package protected members also have package access. All public and protected superclass members retain their original access modifier when they become members of the subclass A superclass’s private members are hidden in its subclasses They can be accessed only through the public or protected methods inherited from the superclass Subclass methods can refer to public and protected members inherited from the superclass simply by using the member names. When a subclass method overrides an inherited superclass method, the superclass method can be accessed from the subclass by preceding the superclass method name with keyword super and a dot (.) separator. toString is one of the methods that every class inherits directly or indirectly from class Object. Returns a String representing an object. Called implicitly whenever an object must be converted to a String representation. Class Object’s toString method returns a String that includes the name of the object’s class. This is primarily a placeholder that can be overridden by a subclass to specify an appropriate String representation. Dr. Ammar Almomani-2017-BAU Page 76 Private Like you'd think, only the class in which it is declared can see it. Package Private Can only be seen and used by the package in which it was declared. This is the default in Java (which some see as a mistake). Protected Package Private + can be seen by subclasses or package member. Public Everyone can see it. Default are accessible by the classes of the same package. In object-oriented terms, overriding means to override the functionality of an existing method. The benefit of overriding is: ability to define a behavior that's specific to the subclass type which means a subclass can implement a parent class method based on its requirement instanceof keyword is a binary operator used to test if an object (instance) is a subtype of a given Type. 9.4 Relationship between Superclasses and Subclasses Constructors are not inherited. The first task of a subclass constructor is to call its direct superclass’s constructor explicitly or implicitly toString is one of the methods that every class inherits directly or indirectly from class Object. Returns a String representing an object. Called implicitly whenever an object must be converted to a String representation. To override a superclass method, a subclass must declare a method with the same signature as the superclass method @Override annotation Indicates that a method should override a superclass method with the same signature. If it does not, a compilation error occurs. Constructors are not inherited. Dr. Ammar Almomani-2017-BAU Page 77 ch9_ex1: inheritance (bus extends car) package ch9_1; package ch9_1; public class firstjava { public class car { private int width=20; public int y; public void setdata (int w) { width=w; } public class bus extends car { } public int getdata() { return width; } } run: 10 10 package ch9_1; public static void main(String[] args) { bus call=new bus(); call.setdata(10); System.out.println(call.getdata()); call.y=10; System.out.println(call.y); } } car - width:int + y :int + setdata (w: int ) +getdata() : int bus firstjava main(args:String[])) UML :inheritance (bus extends car) Dr. Ammar Almomani-2017-BAU Page 78 ch9_ex2: Relationship between Superclasses and Subclasses package ch9_2; package ch9_2; public class food { public void eat() { System.out.println("i love the food"); } } public class falafel extends food { package ch9_2; public class shawerma extends food { } run: i love the food i love the food } package ch9_2; public class Hello { public static void main(String[] args) { falafel falobject= new falafel(); shawerma shawobject= new shawerma(); falobject.eat(); shawobject.eat(); } } food +eat(): falafel void shawerma Hello main(args:String[])) Dr. Ammar Almomani-2017-BAU Page 79 ch9_ex3:Relationship between Superclasses and Subclasses Box width: double height: double depth: double +<constructor> Box (w: double , h:double, d:double) getVolume() :void MatchBox run: Volume is : 1000.0 width of MatchBox 1 is 10.0 height of MatchBox 1 is 10.0 depth of MatchBox 1 is 10.0 weight of MatchBox 1 is 10.0 mainlist weight: double + <constructor> MatchBox ( w:double, h:double, d:double, m:double) main(args:String[])) package ch9_3; class Box { double width; double height; double depth; public Box(double w, double h, double d) { width = w; height = h; depth = d; } void getVolume() { System.out.println("Volume is : " + width * height * depth); }} package ch9_3; public class MatchBox extends Box { double weight; public MatchBox (double w, double h, double d, double m) { super(w, h, d); weight = m; }} Dr. Ammar Almomani-2017-BAU Page 80 package ch9_3; public class mainlist { public static void main(String args[]) { MatchBox mb1 = new MatchBox(10, 10, 10, 10); mb1.getVolume(); System.out.println("width of MatchBox 1 is " + mb1.width); System.out.println("height of MatchBox 1 is " + mb1.height); System.out.println("depth of MatchBox 1 is " + mb1.depth); System.out.println("weight of MatchBox 1 is " + mb1.weight); } } ch9_ex4: Relationship between Superclasses and Subclasses person - firstname:String - lastname:String + <constructor> :Person(String firstname,String lastname) +print() : void student professor - graduationyear: int - gpa: double + <constructor> student ( firstname: String, lastname:String ,graduationyear: int , gpa:double) + print():void + <constructor>professor(firstname:String , lastname: String) + print():void testoverride main(args:String[])) Dr. Ammar Almomani-2017-BAU run: professor details peter noetal student Details sam walton 2012 3.8 Page 81 package ch9_4; public class Person { private String firstname; private String lastname; public Person(String firstname,String lastname) { this.firstname=firstname; this.lastname=lastname; } public void print() { System.out.println("\t" + firstname + " " + lastname); } } package ch9_4; package ch9_4; public class professor extends Person{ public class student extends Person{ private int graduationyear; private double gpa; public student (String firstname,String lastname ,int graduationyear,double gpa) { super (firstname,lastname); this.graduationyear = graduationyear; this.gpa=gpa; } public void print() { System.out.println("student Details"); super.print(); System.out.println("\t" + graduationyear); System.out.println("\t" + gpa); } } public professor(String firstname,String lastname) { super(firstname, lastname); } @Override public void print(){ System.out.println("professor details"); super.print(); } } Dr. Ammar Almomani-2017-BAU Page 82 package ch9_4; public class testoverride { public static void main (String[] args){ professor knowitall= new professor ("peter","noetal"); knowitall.print(); student sam = new student("sam", "walton", 2012 ,3.8); sam.print(); } } ch9_ex5 - Quiz : 1 Dog Animal run: Animals can move + move(): void + move(): void Dogs can walk and run TestDog main(String Args[])) package ch9_5; class Animal { public void move(){ System.out.println("Animals can move"); }} package ch9_5; class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); } } Dr. Ammar Almomani-2017-BAU package ch9_5; public class TestDog{ public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//Runs the method in Dog class } } Page 83 Ch10- Object-Oriented Programming: Polymorphism Polymorphism Enables you to “program in the general” rather than “program in the specific.” Polymorphism enables you to write programs that process objects that share the same superclass as if they’re all objects of the superclass; this can simplify programming. Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object. With polymorphism, we can design and implement systems that are easily extensible Example: Let us look at an example. public interface Vegetarian{} public class Animal{} public class Deer extends Animal implements Vegetarian{} Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above example: Vegetarian A Deer IS-A Animal A Deer IS-A Vegetarian A Deer IS-A Deer A Deer IS-A Object Animal Deer When we apply the reference variable facts to a Deer object reference, the following declarations are legal: Deer d = new Deer(); Animal a = d; Vegetarian v = d; Object o = d; All the reference variables d, a, v, o refer to the same Deer object in the heap. Dr. Ammar Almomani-2017-BAU Page 84 Examples on Polymorphism Static Polymorphism: In Java, static polymorphism is achieved through method overloading. Method overloading means there are several methods present in a class having the same name but different types/order/number of parameters. Ch10_ex1 run: DemoOverload 5 + add(x:int,y:int):int + add(x:int,y:int,z:int):int + add(x:double,y:int):int 9 5 Test main(String :args[]) UML :inheritance : static Polymorphism: Overloading Dr. Ammar Almomani-2017-BAU Page 85 package ch10_1; package ch10_1; class Test{ class DemoOverload { public int add(int x, int y) { return x+y ; } public static void main(String[] args) { DemoOverload demo=new DemoOverload(); System.out.println(demo.add(2,3)); public int add(int x, int y, int z) { return x+y+z; } public int add(double x, int y) { return (int)x+y; } } Dr. Ammar Almomani-2017-BAU //method 1 called System.out.println(demo.add(2,3,4)); //method 2 called System.out.println(demo.add(2.5,3)); //method 3 called } } Page 86 Dynamic Polymorphism: Suppose a sub class overrides a particular method of the super class. Let’s say, in the program we create an object of the subclass and assign it to the super class reference. Now, if we call the overridden method on the super class reference then the sub class version of the method will be called. Have a look at the following example. Ch10_ex2 : Dynamic Polymorphism (MotorBike extends Vehicle) Vehicle + move(): void MotorBike + move(): void Test main(String :args[]) UML :inheritance : Dynamic Polymorphism: package ch10_2; class Vehicle { public void move(){ It should be noted that in the first call to move(), the reference type is Vehicle and the object being referenced is MotorBike. So, when a call to move() is made, Java waits until runtime to determine which object is actually being pointed to by the reference. In this case, the object is of the class MotorBike. So, the move() method of MotorBike class will be called. In the second call to move(), the object is of the class Vehicle. So, the move() method of Vehicle will be called. As the method to call is determined at runtime, this is called dynamic binding or late binding. System.out.println("Vehicles can move!!"); }} Dr. Ammar Almomani-2017-BAU Page 87 package ch10_2; class MotorBike extends Vehicle{ @Override public void move(){ System.out.println("MotorBike can move and accelerate too!!"); }} package ch10_2; class Test { public static void main(String[] args) { Vehicle vh=new MotorBike(); vh.move(); // prints MotorBike can move and accelerate too!! vh=new Vehicle(); vh.move(); // prints Vehicles can move!! Vehicle vh2=new MotorBike(); vh2.move(); // prints MotorBike can move and accelerate too!! } } run: MotorBike can move and accelerate too!! Vehicles can move!! MotorBike can move and accelerate too!! Ch10_ex3: Dynamic Polymorphism: (rectangle AND square extends figure) figure run: + draw(): void rectangle square + draw(): void figure rectangle square + draw(): void area main(String: args[]) Ch10_ex3: Dynamic Polymorphism: (rectangle AND square extends figure) Dr. Ammar Almomani-2017-BAU Page 88 package ch10_3; public class figure { void draw(){ System.out.println("figure"); } } package ch10_3; public class rectangle extends figure{ @Override void draw(){ System.out.println("rectangle"); } } class figure is the parent class polymorphism creation rules parent class object reference name= new create new object ex1: figure fig1=new rectangle(); meaning rectangle is a figure from figure parent class ex2: figure fig2=new square(); meaning square is a figure from figure parent class package ch10_3; public class square extends figure{ @Override void draw(){ System.out.println("square"); } } package ch10_3; public class area{ public static void main(String[] args) { figure fig0=new figure(); fig0.draw(); figure fig1=new rectangle(); fig1.draw(); figure fig2=new square(); fig2.draw(); }} Dr. Ammar Almomani-2017-BAU Page 89 Type of inheritance : Animal Vegetarian A Deer Animal Shape1: Single level inheritance A Deer Shape2: multi level inheritance -A interface Object1 Object2 Object3 . . . Super class or concrete calss Shap4: polymorphic array(Object from different class) Shape3: multi level inheritance-B ch10_ex4_poly (inheritance with array polymorphism ) super_class + parent_public_method(): void + parent_public_methodwithARG(int num):void - parent_private_method():void parent_protected_method():void child1 child2 parent_protected_method(): void parent_protected_method(): void run: This is child1-protected method This is parent_public_method() This is parent_public_methodwithARG()9 This is parent_protected_method() This is child1-protected method This is child2-protected method with_main main() ch10_ex4_poly (inheritance with array polymorphism ) Dr. Ammar Almomani-2017-BAU Page 90 ch10_ex4_poly (inheritance with array polymorphism ) package ch10_4; public class super_class { public void parent_public_method() { System.out.println ("This is parent_public_method()"); } public void parent_public_methodwithARG(int num) { System.out.println ("This is parent_public_methodwithARG()" +num); } private void parent_private_method() { System.out.println("This is parent_private_method()" ); } protected void parent_protected_method() { System.out.println("This is parent_protected_method()" ); }} package ch10_4; package ch10_4; public class child1 extends super_class{ @Override protected void parent_protected_method() { System.out.println("This is child 1-protected method"); } } public class with_main { public static void main(String[] args) { child1 childobj=new child1(); super_class superobj1=new super_class(); childobj.parent_protected_method(); childobj.parent_public_method(); childobj.parent_public_methodwithARG(9); superobj1.parent_protected_method(); package ch10_4; public class child2 extends super_class{ @Override protected void parent_protected_method() { System.out.println("This is child2-protected method"); }} Dr. Ammar Almomani-2017-BAU super_class[] superobj2=new super_class[2]; superobj2[0]=new child1(); superobj2[1]=new child2(); for(int i=0;i<2;i++) { superobj2[i].parent_protected_method(); } } } Page 91 Note: if you need calling method from super_class by child1 Class just use super key word as follow : public class child1 extends super_class{ protected void parent_protected_method() { System.out.println("This is child-protected method"); super.parent_protected_method() } } Object super calss belong to it self Super class Sub class Sub class Object sub class belong to it self and super class object Abstract class A Concrete class B package ch10_5; Dr. Ammar Almomani-2017-BAU Page 92 ch10_ex5: abstract class polymorphism is a general idea in Java that allows an object to behave as if it were an instance of another class; thus code is more independent from the concrete class. Given this idea, are the two method calls in the following main() method usages of polymorphism. The benefit of polymorphism is that it is very easy to add new classes of derived objects without breaking the calling code we need abstract class for abstract method, it is like contract between two classes if you going to inherit that class you need to Override that method defined in abstract class package ch10_5; abstract class A { int x=3,y=4; int z=x+y; void f() { System.out.println("A.f()"); System.out.printf("%d\n",z); } abstract void g(int x,int y); } package ch10_5; class B extends A { @Override void g(int x,int y) { int z=x+y; System.out.println("B.g()"); System.out.printf("%d\n",z); } package ch10_5; public class Test { public static void main(String[] args) { A a = new B(); a.f(); // Is this an example of Polymorphism? a.g(2,3); // if we write A b=new A();// error because we can't create abstract object class // ... }} run: instantiating a class simply means you are creating object of it. Abstract Methods and Classes An abstract class can be used as a type of template for other classes. The abstract class will hold common functionality for all classes that extend it. For example: Abtract Class Animal All animals move and breathe and reproduce so these can be put into the Animal Class. Now Concrete Class Dog,Cat etc. An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this: abstract void moveTo(double deltaX, double deltaY); If a class includes abstract methods, then the class itself must be declared abstract, as in: public abstract class GraphicObject { // declare fields // declare non abstract methods abstract void draw(); } When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract. A.f() 7 B.g() 5 Dr. Ammar Almomani-2017-BAU Page 93 Abstract classes permit providing a partial set of default implementations of methods in a class. Since they're incomplete, they can't be instantiated and used as they stand, but they can be subclassed to add the missing details in a way that's specific to that particular implementations, and those subclasses can be instantiated. Without abstract classes, you would have to provide dummy implementations of the methods you intend to override ... which could be done, but then there'd be the risk of forgetting to implement one of them. note: normal class cant contain abstract method Using an Interface To use an interface, a concrete class must specify that it implements the interface and must declare each method in the interface with the signature specified in the interface declaration. An interface declaration begins with the keyword interface and contains only constants and abstract methods. Unlike classes, all interface members must be public, and interfaces may not specify any implementation details, such as concrete method declarations and instance variables. All methods declared in an interface are implicitly public abstract methods, and all fields are implicitly public, static and final. 1- the different between abstract and interface class that if any class inherit abstact class it will be responsible to that class to implement all the method interface. 2- you can have constructor with abstract class for initialize the value but interface can't have constructor . 3-interface use to implement many inheritance in java to implement more than one interface use comma-separated list of interface name after keyword implements in the class declaration as follow. public class classname extends supercalssName implements first inteface, second interface,... Dr. Ammar Almomani-2017-BAU Page 94 Note: final methods can't be overriden, because that's what final is designed to do: it's a vote sign saying "do not override this". //Note2: you cannot inherit from final class A //but you can put it final with subclass //like: final class B extends A //ex: final class A { public void print() { System.out.printf("this is class A"); }} class B extends A { @Override public void print() { System.out.printf("this is class B"); }} public class Program { public static void main(String [] args) { A ob1; ob1 = new B(); ob1.print(); }} class A { public void print() { System.out.printf("this is class A"); }} class B extends A { @Override public void print() { System.out.printf("this is class B"); } } public class Program { public static void main(String [] args) { A ob1; ob1 = new B(); ob1.print(); }} Note3: you can't override method between any different class like override public method from protected method but if it the same types modifiers you can override Note4: any concrete class need to connect with interface class should be use implements not extends error interface A { void print(); } class B extends A { } Dr. Ammar Almomani-2017-BAU correct interface A { void print(); } class B implements A { } Page 95 UML: ch10_ex6 implement demo_interface2 interface class + interface_variable2=2: int + interface2_method(): void IS-A interface class demo_interface1 + interface_variable1=1: int implement demo_abstract override Int x abstract class + abstract_method():void non_abstract_method():void + demo_abstract():void If you need inheretance from demo_abstract2 you should create override because we have abstract method in demo_abstract IS-A demo_abstract2 Int x=2 abstract class IS-A demo_normal_class Concrete class + abstract_method():void display():void + interface2_method():void with_main main(String : args[]) ch10_ex6_abstract (abstract class and interface) Dr. Ammar Almomani-2017-BAU Page 96 ch10_ex6_abstract (abstract class and interface) package ch10_6; public abstract class demo_abstract implements demo_interface1,demo_interface2 { public abstract void abstract_method(); void non_abstract_method() { System.out.println("we can define it's functionality here"); } int x; public demo_abstract() { x=100000; } } package ch10_6; public abstract class demo_abstract2 extends demo_abstract { int x=2; } package ch10_6; public interface demo_interface1 extends demo_interface2 { public int interface_variable1=1; } package ch10_6; public interface demo_interface2 { public int interface_variable2=2;//variable of type public , final and static void interface2_method();//public abstract type } Dr. Ammar Almomani-2017-BAU Page 97 package ch10_6; public class demo_normal_class extends demo_abstract2{ @Override public void abstract_method(){ System.out.println("this is abstract method that must be overridden"); } void display() { int interface_variables_sum= interface_variable1 + interface_variable2; System.out.println("sum of interface value = " + interface_variables_sum); } @Override public void interface2_method(){ System.out.println("This is interface2 method"); }} package ch10_6; public class with_main { public static void main(String[] args) { demo_normal_class normalobj = new demo_normal_class(); System.out.println(normalobj.x); normalobj.abstract_method(); normalobj.non_abstract_method(); normalobj.display(); normalobj.interface2_method(); }} run: 2 this is abstract method that must be overridden we can define it's functionality here sum of interface value = 3 This is interface2 method Dr. Ammar Almomani-2017-BAU Page 98 Chapter 11-Exception Handling: A Deeper Look Exception handling Exception—an indication of a problem that occurs during a program’s execution. The name “exception” implies that the problem occurs infrequently. With exception handling, a program can continue executing (rather than terminating) after dealing with a problem. this called Robust and fault-tolerant programs Exceptions are thrown (i.e., the exception occurs) when a method detects a problem and is unable to handle it. Stack trace—information displayed when an exception occurs and is not handled. Information includes: The name of the exception in a descriptive message that indicates the problem that occurred The method-call stack (i.e., the call chain) at the time it occurred. Represents the path of execution that led to the exception method by method. This information helps you debug the program. 11.1 Example: Divide by Zero without Exception Handling (Cont.) Java does not allow division by zero in integer arithmetic. Throws an ArithmeticException. Java does allow division by zero with floating-point values If 0.0 is divided by 0.0, the result is NaN (not a number), package ch11_1; import java.util.Scanner; public class DivideByZeroNoExceptionHandling { // demonstrates throwing an exception when a divide-by-zero occurs public static int result( int x, int y ) { return x / y; // possible division by zero } // end method quotient public static void main( String[] args ) { Scanner scanner = new Scanner( System.in ); // scanner for input System.out.print( "Please enter an integer x: " ); int x = scanner.nextInt(); System.out.print( "Please enter an integer y: " ); int y = scanner.nextInt(); int result = result( x, y ); System.out.printf( "\nResult: %d / %d = %d\n", x, y, result ); } } Dr. Ammar Almomani-2017-BAU Page 99 Run: Please enter an integer x: 100 Please enter an integer y: 7 Result: 100 / 7 = 14 ---------------------------------------------------------Please enter an integer x: 100 Please enter an integer y: 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at ch11_dividebyzeronoexceptionhandling.DivideByZeroNoExceptionHandling.result (DivideByZeroNoExceptionHandling.java:15) at ch11_dividebyzeronoexceptionhandling.DivideByZeroNoExceptionHandling.main(DivideByZeroNoEx ceptionHandling.java:27) Java Result: 1 Last “at” line in the stack trace started the call chain. Each line contains the class name and method followed by the file name and line number. An InputMismatchException occurs when Scanner method nextInt receives a String that does not represent a valid integer. If a stack trace contains “Unknown Source” for a particular method not available to the JVM 11.2 Example: Handling ArithmeticExceptions and InputMismatchExceptions The application in Fig. 11.2 uses exception handling to process any ArithmeticExceptions and InputMistmatchExceptions that arise. If the user makes a mistake, the program catches and handles (i.e., deals with) the exception—in this case, allowing the user to try to enter the input again. Dr. Ammar Almomani-2017-BAU Page 100 package ch11_2; import java.util.InputMismatchException; import java.util.Scanner; public class ex2_DivideByZeroWithExceptionHandling { // demonstrates throwing an exception when a divide-by-zero occurs public static int result( int x, int y ) { return x / y; // possible division by zero } public static void main( String[] args ) { Scanner scanner = new Scanner( System.in ); // scanner for input boolean continueLoop = true; // determines if more input is needed do { try // read two numbers and calculate result { System.out.print( "Please enter an integer x: " ); int x = scanner.nextInt(); System.out.print( "Please enter an integer y: " ); int y = scanner.nextInt(); int result = result( x, y ); System.out.printf( "\n Result: %d / %d = %d\n", x, y, result ); continueLoop = false; // input successful; end looping } // end try catch ( InputMismatchException stringerror ) { System.err.printf( "\n Exception: %s\n", stringerror ); scanner.nextLine(); // discard input so user can try again System.out.println( "You must enter integers. Please try again.\n" ); } // end catch catch ( ArithmeticException integererror ) { System.err.printf( "\nException: %s\n", integererror ); System.out.println( "Zero is an invalid denominator. Please try again.\n" ); } // end catch } while ( continueLoop ); // end do...while } // end main } // end class DivideByZeroWithExceptionHandling Dr. Ammar Almomani-2017-BAU try block encloses code that might throw an exception code that should not execute if an exception occurs. Consists of the keyword try followed by a block of code enclosed in curly braces. catch block (also called a catch clause or exception handler) catches and handles an exception. Begins with the keyword catch and is followed by an exception parameter in parentheses and a block of code enclosed in curly braces. theSystem.err (standard error stream) object to output error messages. By default, displays data to the command prompt. To satisfy the declare part of the catch-or-declare requirement, the method must provide a throws clause containing the checked-exception type after its parameter list and before its method body. Page 101 run1: Please enter an integer x: 100 Please enter an integer y: 0 Exception: java.lang.ArithmeticException: / by zero Zero is an invalid denominator. Please try again. Please enter an integer x: 100 Please enter an integer y: 7 Result: 100 / 7 = 14 run2: Please enter an integer x: 100 Please enter an integer y: hello Exception: java.util.InputMismatchException You must enter integers. Please try again. Please enter an integer x: 100 Please enter an integer y: 7 Result: 100 / 7 = 14 Dr. Ammar Almomani-2017-BAU Page 102 note: When a method throws an exception, the method terminates and does not return a value, and its local variables go out of scope. 11.4 When to Use Exception Handling Exception handling is designed to process synchronous errors, which occur when a statement executes. Common examples in this book: out-of-range array indices arithmetic overflow division by zero invalid method parameters thread interruption unsuccessful memory allocation Exception handling is not designed to process problems associated with asynchronous events disk I/O completions network message arrivals mouse clicks and keystrokes 11.5 Java Exception Hierarchy Exception classes inherit directly or indirectly from class Exception, forming an inheritance hierarchy. Can extend this hierarchy with your own exception classes. Figure 11.3 shows a small portion of the inheritance hierarchy for class Throwable (a subclass of Object), which is the superclass of class Exception. Only Throwable objects can be used with the exception-handling mechanism. Class Throwable has two subclasses: Exception and Error. Class Exception and its subclasses represent exceptional situations that can occur in a Java program These can be caught and handled by the application. Class Error and its subclasses represent abnormal situations that happen in the JVM. Errors happen infrequently. These should not be caught by applications. Applications usually cannot recover from Errors. Dr. Ammar Almomani-2017-BAU Page 103 Checked exceptions vs. unchecked exceptions. Compiler enforces a catch-or-declare requirement for checked exceptions. An exception’s type determines whether it is checked or unchecked. Direct or indirect subclasses of class RuntimeException (package java.lang) are unchecked exceptions. Typically caused by defects in your program’s code (e.g., ArrayIndexOutOfBoundsExceptions). Subclasses of Exception but notRuntimeException are checked exceptions. Caused by conditions that are not in the control of the program—e.g., in file processing, the program can’t open a file because the file does not exist. Classes that inherit from class Error are considered to be unchecked If so, the compiler verifies that the checked exception is caught or is declared in a throws clause The compiler does not check the code to determine whether an unchecked exception is caught or declared. These typically can be prevented by proper coding. For example, an ArithmeticException can be avoided if a method ensures that the denominator is not zero before attempting to perform the division. Unchecked exceptions are not required to be listed in a method’s throws clause Even if they are, it’s not required that such exceptions be caught by an application. A catch parameter of a superclass-type can also catch all of that exception type’s subclass types. You can also catch each subclass type individuallyif those exceptions require different processing Dr. Ammar Almomani-2017-BAU Page 104 If there multiple catch blocks match a particular exception type, only the first matching catch block executes. It’s a compilation error to catch the exact same type in two different catch blocks associated with a particular try block. 11.6 finally Block Programs that obtain resources must return them to the system explicitly to avoid socalled resource leaks. Java automatically garbage collects memory no longer used by programs, thus avoiding most memory leaks. Other types of resource leaks can occur. Files, database connections and network connections that are not closed properly might not be available for use in other programs. The finallyblock is used for resource deallocation. Placed after the last catch block. finally block will execute whether or not an exception is thrown in the corresponding try block. finally blockwill execute if a try block exits by using a return, break or continue statement or simply by reaching its closing right brace. finally blockwill not execute if the application terminates immediately by calling method System.exit. Suppose a resource is allocated in a try block. 1- If no exception occurs, control proceeds to thefinally block, which frees the resource. Control then proceeds to the first statement after the finally block. 2-If an exception occurs, the try block terminates. The program catches and processes the exception in one of the corresponding catch blocks, then the finally block releases the resource and control proceeds to the first statement after the finally block. 3-If a catch block throws an exception, the finally block still executes. Then the exception is passed to the next outer try block—again, normally in the calling method. Dr. Ammar Almomani-2017-BAU Page 105 General format of try-catch-fnally try { statements resource-acquisition statements } // end try catch (A kindOfException exception1) { exception-handling statements } //end catch . . . catch(AnotherKindOfException exception2) { exception-handling statements } finally { statements recourse-release statements } // end finally System.out and System.err are streams—sequences of bytes. System.out(known as the standard output stream) displays a program’s output, System.err (known as the standard error stream) displays a program’s errors data output from System.err could be sent to a log file, data output from System.out can be displayed on the screen. An object can be thrown without containing information about the problem that occurred. In this case, simply knowing that an exception of a particular type occurred may provide sufficient information for the handler to process the problem correctly. Dr. Ammar Almomani-2017-BAU Page 106 ch11_ex3: try_catch_finally package ch11_ex4_try_catch_finally; public class ExcepTest{ public static void main(String args[]){ int a[] = new int[2]; try{ System.out.println("Access element three :" + a[3]); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } finally{ a[0] = 6; System.out.println("First element value: " +a[0]); System.out.println("The finally statement is executed"); } } } try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }finally { //The finally block always executes. } run: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed Dr. Ammar Almomani-2017-BAU Page 107 We can define our own Exception class as below: class MyException extends Exception{ } You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following Excep class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods. ch11_4: UML run: Depositing $500... Withdrawing $100... Withdrawing $ 600... Sorry, but you are short $ 400.0 ch11_4.Excep at ch11_4.CheckingAccount.withdraw(CheckingAccount.java:28) at ch11_4.BankDemo.main(BankDemo.java:23) Dr. Ammar Almomani-2017-BAU Page 108 ch11_4: Exception class to create your own Exception class package ch11_4; public class Excep extends Exception { private double amount; public Excep (double amount) { this.amount = amount; } public double getAmount() { return amount; }} package ch11_4; public class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws Excep { if(amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new Excep (needs); //create new exception } } } Dr. Ammar Almomani-2017-BAU package ch11_4; public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try { System.out.println("\nWithdrawing $100..."); c.withdraw(100.00); //well done c.withdraw(200.00); //well done System.out.println("\n Withdrawing $600..."); c.withdraw(100.00); //well not done } catch(Excep e) { System.out.println("Sorry, but you are short $" + e.getAmount()); e.printStackTrace(); } }} Page 109 Chapter 17: Files, Streams and Object Serialization 17.1 Introduction Data stored in variables and arrays is temporary It’s lost when a local variable goes out of scope or when the program terminates For long-term retention of data, computers use files Computers store files on secondary storage devices (hard disks, optical disks, flash drives) Data maintained in files is persistent data because it exists beyond the duration of program execution 17.2 Files and Streams Java views each file as a sequential stream of bytes Every operating system provides end-of-file marker or a count of the total bytes in the file A Java program simply receives an indication from the operating system when it reaches the end of the stream 17.2 Files and Streams (cont.) File streams can be used to input and output data as bytes or characters. Streams that input and output bytes are known as byte-based streams, representing data in its binary format. Streams that input and output characters are known as character-based streams, representing data as a sequence of characters. Files that are created using byte-based streams are referred to as binary files. Files created using character-based streams are referred to as text files. Text files can be read by text editors. Binary files are read by programs that understand the specific content of the file and the ordering of that content. Dr. Ammar Almomani-2017-BAU Page 110 17.2 Files and Streams (cont.) A Java program opens a file by creating an object and associating a stream of bytes or characters with it Java creates three stream objects when a program begins executing System.in (the standard input stream object) normally inputs bytes from the keyboard System.out (the standard output stream object) normally outputs character data to the screen System.err (the standard error stream object) normally outputs character-based error messages to the screen. Class System provides methods setIn, setOutandsetErrto redirect the standard input, output and error streams, respectively. Java programs perform file processing by using classes from package java.io. Includes definitions for stream classes FileInputStream(for byte-based input from a file) FileOutputStream (for byte-based output to a file) FileReader(for character-based input from a file) FileWriter(for character-based output to a file) You open a file by creating an object of one these stream classes. The object’sconstructor opens the file. Class File provides information about files and directories. Character-based input and output can be performed with classes Scanner and Formatter. Class Scanner is used extensively to input data from the keyboard. This class can also read data from a file. Class Formatter enables formatted data to be output to any text-based stream in a manner similar to method System.out.printf. Class File provides four constructors. The one with a String argument specifies the name of a file or directory to associate with the File object. The name can contain path information as well as a file or directory name. A file or directory’s path specifies its location on disk. An absolute path contains all the directories, starting with the root directory, that lead to a specific file or directory. A relative path normally starts from the directory in which the application began executing and is therefore “relative” to the current directory. The constructor with File and String arguments uses an existing File object that specifies the parent directory of the file or directory specified by the String argument. The fourth constructor uses a URI object to locate the file. A Uniform Resource Identifier (URI) is a more general form of the Uniform Resource Locators (URLs) that are used to locate websites. Dr. Ammar Almomani-2017-BAU Page 111 Stream I/O in Standard I/O (java.io Package) Basic Input & Output - Java Program Java FileInputStream : Byte Streams Dr. Ammar Almomani-2017-BAU Page 112 What is the difference between URI, URL and URN? A Uniform Resource Locator (URL) is a subset of the Uniform Resource Identifier (URI) that specifies where an identified resource is available and the mechanism for retrieving it.URL defines how the resource can be obtained. It does not have to be HTTP URL (http://), a URL can also be (ftp://) or (smb://) A Uniform Resource Name (URN) is a Uniform Resource Identifier (URI) that uses the URN scheme, and does not imply availability of the identified resource. Both URNs (names) and URLs (locators) are URIs, and a particular URI may be both a name and a locator at the same time. A stream is byte of data. Dr. Ammar Almomani-2017-BAU Page 113 Figure 17.2 lists some common File methods. The complete hierarchy of classes in package java.io can be viewed in the online documentation at http://download.oracle.com/javase/6/docs/api/java/io/package-tree.html Dr. Ammar Almomani-2017-BAU Page 114 ch17-1: File class used to obtain file and directory information. // Fig. 17.3: FileDemonstration.java // File class used to obtain file and directory information. import java.io.File; import java.util.Scanner; public class FileDemonstration { public static void main( String[] args ) { Scanner input = new Scanner( System.in ); System.out.print( "Enter file or directory name: " ); analyzePath(input.nextLine() ); } // end main // display information about file user specifies public static void analyzePath( String path ) { // create File object based on user input File name = new File( path ); if ( name.exists() ) // if name exists, output information about it { // display file (or directory) information System.out.printf( "%s%s\n%s\n%s\n%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s", name.getName(), " exists", ( name.isFile() ? "is a file" : "is not a file"), ( name.isDirectory() ? "is a directory" : "is not a directory" ), ( name.isAbsolute() ? "is absolute path" : "is not absolute path" ), "Last modified: ",name.lastModified(), "Length: ",name.length(), //size of byte "Path: ",name.getPath(), "Absolute path: ", name.getAbsolutePath(), "Parent: ",name.getParent() ); Dr. Ammar Almomani-2017-BAU if ( name.isDirectory() ) // output directory listing { String[] directory = name.list(); System.out.println( "\n\nDirectory contents:\n" ); for ( String directoryName : directory ) System.out.println(directoryName ); } // end if } // end outer if else { System.out.printf( "%s %s", path, "does not exist." ); } } // end method analyzePath } // end class FileDemonstration Page 115 RUN1: Enter file or directory name: C:\Program Files\Java Java exists is not a file is a directory is absolute path Last modified: 1415246431411 Length: 0 Path: C:\Program Files\Java Absolute path: C:\Program Files\Java Parent: C:\Program Files Directory contents: jdk1.8.0_20 jre1.8.0_25 RUN2: Enter file or directory name: C:\Program Files\Java\jdk1.8.0_20\README.HTML README.HTML exists is a file is not a directory is absolute path Last modified: 1415221723394 Length: 159 Path: C:\Program Files\Java\jdk1.8.0_20\README.HTML Absolute path: C:\Program Files\Java\jdk1.8.0_20\README.HTML Parent: C:\Program Files\Java\jdk1.8.0_20 Dr. Ammar Almomani-2017-BAU Page 116 17.3 Class File 17.3 Class File A separator character is used to separate directories and files in the path. On Windows, the separator character is a backslash (\). On Linux/UNIX, it’s a forward slash (/). 17.4 Sequential-Access Text Files Sequential-access files store records in order by the record-key field. Text files are human-readable files. 17.4.1 Creating a Sequential-Access Text File Formatter outputs formatted Strings to the specified stream. The constructor with one String argument receives the name of the file, including its path. If a path is not specified, the JVM assumes that the file is in the directory from which the program was executed. If the file does not exist, it will be created. If an existing file is opened, its contents are truncated A SecurityException occurs if the user does not have permission to write data to the file. A FileNotFoundException occurs if the file does not exist and a new file cannot be created. static method System.exit terminates an application. An argument of 0 indicates successful program termination. A nonzero value, normally indicates that an error has occurred. The argument is useful if the program is executed from a batch file on Windows or a shell script on UNIX/Linux/Mac OS X. THE end of file key IS 1- window <ctrl> z <Enter> 2- UNIX/Linux/Mac OS X <Ctrl> d <Enter> http://www.tutorialspoint.com/java/java_overriding.htm Scanner method hasNext determines whether the end-of-file key combination has been entered. A NoSuchElementException occurs if the data being read by a Scanner method is in the wrong format or if there is no more data to input. Formatter method format works like System.out.printf A FormatterClosedException occurs if the Formatter is closed when you attempt to output. Formatter method close closes the file. If method close is not called explicitly, the operating sys-tem normally will close the file when program execution terminates. Dr. Ammar Almomani-2017-BAU Page 117 17.4 Sequential-Access Text Files 17.4.1 Creating a Sequential-Access Text File package ch17_3; import java.io.*; import java.lang.*; import java.util.*; public class createfile { private Formatter x; public void openFile(){ try { x=new Formatter ("chinese.txt"); // open the file or create it } catch ( SecurityException securityException ) { System.err.println( "You do not have write access to this file." ); System.exit( 1 ); // terminate the program } // end catch catch ( FileNotFoundException fileNotFoundException ) { System.err.println( "Error opening or creating file." ); System.exit( 1 ); // terminate the program } // end catch } // end method openFile public void addrecord() { try { for (int i=1;i<4;i++) { x.format("%s%s%s","20 ","backy ","roberts\n"); } } catch ( FormatterClosedException formatterClosedException ) { System.err.println( "Error writing to file." ); } // end catch catch ( NoSuchElementException elementException ) { System.err.println( "Invalid input. Please try again." ); } } public void closeFile() { x.close(); run: programe will create chinese.txt file contents as follow 20 backy roberts 20 backy roberts 20 backy roberts Dr. Ammar Almomani-2017-BAU } } you can use this package class in this project import java.io.FileNotFoundException; import java.lang.SecurityException; import java.util.Formatter; import java.util.FormatterClosedException; import java.util.NoSuchElementException; import java.util.Scanner; Page 118 17.4.2 Reading Data from a Sequential-Access Text File ch7_3 package ch17_3; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class App { public static void main(String[] args) throws FileNotFoundException { String fileName="C:/Users/ammar2/Documents/NetBeansProjects/ch17_3/example.txt"; File textFile=new File(fileName); try { Scanner in=new Scanner(textFile); int value =in.nextInt(); System.out.println("Read value " + value); in.nextLine();// for reading line 2 int count=2; while(in.hasNextLine()) { String line=in.nextLine(); System.out.println(count + ":" + line); count++; } in.close(); } catch(FileNotFoundException e) { e.printStackTrace();} run://programe will read "example.txt" } Read value 3 } 2:line one 3:line two 4:line three note the path of txt file can be separate by 5: \\ or / 6:cat C:/Users/ammar2/ 7:fox C:\\Users\\ammar2\\ 8:dog 9:cat Dr. Ammar Almomani-2017-BAU Page 119 1. Using the Path Class: Non-blocking I/O (usually called NIO, and sometimes called "New I/O") is a collection of Java programming language APIs that offer features for intensive I/O operations. The Java NIO APIs are provided in the java.nio package and its sub packages. The documentation by Oracle identifies these features. Buffers for data of primitive types Character set encoders and decoders A file interface that supports locks and memory mapping of files up to Integer.MAX_VALUE bytes (2 GiB) Path.toRealPath(LinkOption ... options) has the following syntax. Path toRealPath(LinkOption ... options) Dr. Ammar Almomani-2017-BAU throws IOException Page 120 Using the Path Class: ch17-4 package pathclass; import java.io.*; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args) throws IOException { Path path=Paths.get("C:\\Users\\ammar2\\Documents\\NetBeansProjects\\pathclass\\loremipsum.txt"); // may be non real path System.out.println(path.toString()); // to string give us the file name and path we passed it System.out.println(path.getFileName()); // pathclass System.out.println(path.getNameCount()); // names number (6) System.out.println(path.getName(0)); // users index 0 System.out.println(path.getName(1)); //ammar2 index 1 System.out.println(path.getName(path.getNameCount()-1)); // loremipsum.txt System.out.println(path.getName(path.getNameCount()-2)); // pathclass // if you work with non existing file you need exception try { Path real_path = path.toRealPath(LinkOption.NOFOLLOW_LINKS); System.out.println("Path to real path: " + real_path); } catch (IOException e) { System.err.println(e); } }} run1 : no error C:\Users\ammar2\Documents\NetBeansProjects\pathclass\loremipsum.txt loremipsum.txt 6 Users ammar2 loremipsum.txt pathclass C:\Users\ammar2\Documents\NetBeansProjects\pathclass\loremipsum.txt Dr. Ammar Almomani-2017-BAU Page 121 run2: we have error in directory C:\Users\ammar2\Documents\NetBeansProjects\pathclass\loremip.txt loremip.txt 6 Users ammar2 loremip.txt pathclass java.nio.file.NoSuchFileException: C:\Users\ammar2\Documents\NetBeansProjects\pathclass\loremip.txt Dr. Ammar Almomani-2017-BAU Page 122 17.3 Java Basics - IO Part 1 - Files and Streams ch17_5: package filedemo; import java.io.*; //you can use this package or class below import java.net.URL; //import java.io.File; //import java.io.PrintWriter; //import java.io.FileInputStream; //import java.io.FileOutputStream; //import java.io.InputStream; //import java.io.OutputStream; //import java.io.BufferedWriter; public class FileDemo { public static void main(String[] args) throws IOException { File path= new File("hello.txt"); System.out.println("we got a file: " + path); System.out.println("Does it exists? " + path.exists()); System.out.println("What? " + path.isDirectory()); String contentsToWrite="hello world"; // order to write in file /* FileInputStream(for byte-based input from a file) FileOutputStream (for byte-based output to a file) */ OutputStream outStream = new FileOutputStream(path); outStream.write(contentsToWrite.getBytes()); outStream.close(); // to create buffer for big data BufferedReader reader =new BufferedReader(new InputStreamReader( new FileInputStream(path))); String firstLine= reader.readLine(); // to read first line of file reader.close (); Dr. Ammar Almomani-2017-BAU System.out.println("Read a Line: " + firstLine); // TO read full url web page data URL url=new URL("https://javamail.java.net/docs/NOTE S.txt"); InputStream stream=url.openStream(); BufferedReader reader2=new BufferedReader(new InputStreamReader(stream)); String line =reader2.readLine(); while(line !=null) { System.out.println(line); line=reader2.readLine(); } System.out.println("Done reading!"); } } run: we got a file: hello.txt Does it exists? true what? false Read a Line: hello world <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" . . . all file </html> Done reading! Page 123