Dr.Ammar Almomani. Dept. of Information Technology, Al-Huson University College, Al- Balqa Applied University. Dr. Ammar Almomani-2017-BAU Page 1

Size: px
Start display at page:

Download "Dr.Ammar Almomani. Dept. of Information Technology, Al-Huson University College, Al- Balqa Applied University. Dr. Ammar Almomani-2017-BAU Page 1"

Transcription

1 Dr.Ammar Almomani Dept. of Information Technology, Al-Huson University College, Al- Balqa Applied University Dr. Ammar Almomani-2017-BAU Page 1

2 Java Programming Syllabus First semester/ 2017 Course Title: Java Programming Faculty Name: Al-huson University College Dep. Name: Information technology Course No: Time: Prerequisite: [Object Oriented programming lab] Location : Credit Hours: 3 Semester: first semester 2016/2017 Instructor: Dr. Ammar ALmomani ammarnav6@gmail.com 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), 10 TH EDITION Course website: 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 20% Second Exam 20% Home work and quiz 10% Final exam 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

3 Course Outline and Schedule: Ch-No Chapters and details Hours 1 1- Introduction Java 1.1 Introduction 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 Memory Concepts viii Contents 2.7 Arithmetic 2.8 Decision Making: Equality and Relational Operators 3 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 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 4 Control Statements: Part 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 Control Statements: Part 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 1.30 Dr. Ammar Almomani-2017-BAU Page 3

4 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 Creating and Using a CommissionEmployee Class Creating and Using abasepluscommissionemployee Class 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 Page 4

5 finally Block 11.7 Stack Unwinding and Obtaining Information from an Exception Object 11.8 Chained Exceptions 11.9 Declaring New Exception Types Preconditions and Postconditions Assertions (New in Java SE 7) Multi-catch: Handling Multiple Exceptions in One catch 12 GUI Components: Part 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 Buttons That Maintain State JCheckBox JRadioButton JComboBox; Using an Anonymous Inner Class for Event Handling JList Multiple-Selection Lists Mouse Event Handling Second exam 20% Files, Streams and Object Serialization 17.1 Introduction 17.2 Files and Streams 17.3 Class File 17.4 Sequential-Access Text Files Creating a Sequential-Access Text File 726xiv Contents Reading Data from a Sequential-Access Text File 3 27 Networking 27.1 Introduction 27.2 Manipulating URLs 27.3 Reading a File on a Web Server 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 4.30 Dr. Ammar Almomani-2017-BAU Page 5

6 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 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 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 As of % 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

7 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 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

8 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

9 Fig1:Java programs normally go through five phases Dr. Ammar Almomani-2017-BAU Page 9

10 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 Dr. Ammar Almomani-2017-BAU Page 10

11 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

12 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

13 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

14 CH3:ex1_GradeBookTest package ch3; public class GradeBookTest public static void main (String Args[]) GradeBook mygradebook=new GradeBook(); mygradebook.displaymessage(); // end main // end class GradeBookTest Parentheses in combination with a class name represent a call to a constructor, which is similar to a method but is used only at the time an object is created to initialize the object s data. GradeBook mygradebook=new GradeBook(); Meaning create Gradebook Object and assign it to variable my GradeBook mygradebook.displaymessage(); meaning invoked method displaymessage(). package ch3; public class GradeBook // display a welcome message to the GradeBook user public void displaymessage() System.out.println( Welcome to the Grade Book! ); // end method displaymessage // end class GradeBook A static method (such as main) is special It can be called without first creating an object of the class in which the method is declared. 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

15 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 ); // end method displaymessage // end class GradeBook package ch3_2; 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 Parameter: Additional information a method needs to perform its task. A method call supplies values called arguments for each of the method s parameters. More on Arguments and Parameters The number of arguments in a method call must match the number of parameters in the parameter list of the method s declaration. 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! Dr. Ammar Almomani-2017-BAU Page 15

16 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

17 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 EX: WDQD The default value for a field of type String is null // 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

18 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

19 CH3_ex4 package ch3_4; Answer:Q1 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

20 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

21 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

22 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

23 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

24 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

25 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( ); // create Account object Account account2 = new Account( ); // 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

26 Ch4.control statement 1 Three types of selection statements. if ( studentgrade>= 60 ) System.out.println( "Passed" ); if statement: Format: if ( condition ) Statement; Format: if ( grade >= 60 ) System.out.println( "Passed" ); else System.out.println( "Failed" ); if else statement: if ( Condition ) StatementOne; else StatementTwo; Ch4_ex1: if else if : Multiple-Selection Statement (1) package ch4_ex1; public class if_else Java s logical operators enable you to form more complex conditions by combining simple conditions. The logical operators are 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 && (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). Dr. Ammar Almomani-2017-BAU Page 26

27 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 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 Dr. Ammar Almomani-2017-BAU Page 27

28 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); run: enter your grade (1,2,3,4,5): 3 Well done Your grade is run: enter your grade (1,2,3,4,5): 5 You passed Better try again Your grade is run: enter your grade (1,2,3,4,5): 7 Invalid grade Your grade is 7 Dr. Ammar Almomani-2017-BAU Page 28

29 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 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 ); increment; run: x sum output 1 0--> The sum is:55 The sum is: 55 Dr. Ammar Almomani-2017-BAU Page 29

30 Ch4.ex4:write aprograme to calculate the current series ( )? 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 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 x y total output Total is 385 run: **** **** **** **** **** Note: 1%2=1 2%2=0 3%1=1 run: Total is 385 Dr. Ammar Almomani-2017-BAU Page 30

31 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 row column output 10 1 >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> 7... <<<<<<<<<< <<<<<<<<<< run: >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< Dr. Ammar Almomani-2017-BAU Page 31

32 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"); 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= average=60.00 Dr. Ammar Almomani-2017-BAU Page 32

33 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: 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

34 //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: x+=++y; System.out.printf ("x =%d\n", x); break; 1) x= x + ++y; 2) x= 5+9 =14 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

35 case 3: x=--y+x--+x; System.out.printf ("x =%d\n", x); break; x= --y+x--+x; x= =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; 1)x= x- (-y)%3; 5-(-8)%3 5--2=7 case 5: y+=--y+x-y%x--; System.out.printf ("y =%d\n", y); break; 1) y= y+--y+x-y%x--; % = 18 case 6: x= ++y - --x + y++; System.out.printf ("x =%d\n", x); break; x= ++y - --x + y++; =14 Note: y++ value in next will be 10 Dr. Ammar Almomani-2017-BAU Page 35

36 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 ); run: Sum is 110 Dr. Ammar Almomani-2017-BAU Page 36

37 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(); 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 Dr. Ammar Almomani-2017-BAU Page 37

38 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: Ch5: break and continue Statements Ch5.ex5: break statement package ch5_5; public class Break 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 ); run: 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 Dr. Ammar Almomani-2017-BAU Page 38

39 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: 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; if(x < 50 && x > 0) System.out.println("OK"); if(x < 50 & x > 0) System.out.println("Yup" ); Output: OK Yup Note: &:evaluates both sides of the operation. &&:evaluates the left side of the operation, if it's true, it continues and evaluates the right side. The same condition for other Dr. Ammar Almomani-2017-BAU Page 39

40 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; public class localvariable 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); run: couter=1 x= 1 couter=2 x= 1 couter=3 x= 1 couter=4 x= 1 Ch5.9:error in counter definition package ch5_9; public class Error public static void main(string[] args) 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); Run Error, because counter in final statement is undefined, outside for statement System.out.printf("couter=%d x= %d\n", counter, x); Dr. Ammar Almomani-2017-BAU Page 40

41 Ch5.ex10: nested for with break statement package ch5.ex10; public class Nestedfor 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); run: 2 is prime 3 is prime 5 is prime 7 is prime For-Cond(T/F) I J COUT F is prime F is prime T (break)!(0==1) T F (break)!(1==1) F 4 2 No print 5 2 No print F is prime F F 6 2 No print T F!(1==1) 7 2 No print T (break)!(1==1) T is prime Dr. Ammar Almomani-2017-BAU Page 41

42 Ch6: Methods: A Deeper Look Dr. Ammar Almomani-2017-BAU Page 42

43 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 public static void main( String[] args ) System.out.printf( "Math.abs( ) = %f\n", Math.abs( ) ); 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( ) = %f\n", Math.sqrt( ) ); System.out.printf( "Math.PI = %f\n", Math.PI ); System.out.printf( "Math.E = %f\n", Math.E ); // end main // end class run: Math.abs( ) = Math.floor( 9.2 ) = Math.floor( -9.8 ) = Math.max( 2.3, 12.7 ) = Math.min( 2.3, 12.7 ) = Math.pow( 2.0, 7.0 ) = Math.sqrt( ) = Math.PI = Math.E = Math fields for common mathematical constants Math class constants PI and E Math.PI = ( ) Math.E = ( ) 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

44 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: 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

45 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 Description java.applet The Java Applet Package contains a class and several interfaces required to create Java applets programs that execute in web browsers. java.awt The Java Abstract Window Toolkit Package contains the classes and interfaces required to create and manipulate GUIs java.io The Java Input/Output Package contains classes and interfaces that enable programs to input and output data. java.lang The Java Language Package contains classes and interfaces, This package is imported by the compiler into all programs java.net The Java Networking Package contains classes and interfaces that enable programs to communicate via computer networks like the Internet. java.util 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

46 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: 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=5,6%6=0 : the range (1-6) because ( 1+0=1)...(5+1=6) Dr. Ammar Almomani-2017-BAU Page 46

47 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

48 // 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

49 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 Dr. Ammar Almomani-2017-BAU Page 49

50 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. ArrayList collection 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. 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

51 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 Index Value Dr. Ammar Almomani-2017-BAU Page 51

52 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; Index Value public class even public static void main( String[] args ) int ARRAY_LENGTH = 10; // constant int[] array = new int[ ARRAY_LENGTH ]; // create array // calculate value for each array element for ( int counter = 0; counter <array.length; counter++ ) array[ counter ] = * counter; System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings // output each array element's value for ( int counter = 0; counter <array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] ); 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 ); 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; Dr. Ammar Almomani-2017-BAU Page 52

53 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 * ); // 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

54 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

55 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

56 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

57 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: 0 0 Exception in thread "main" java.lang.nullpointerexception at test.while7.main(while7.java:21) 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: Exception in thread "main" java.lang.nullpointerexception at test.while7.main(while7.java:21) 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: Exception in thread "main" java.lang.nullpointerexception at test.while7.main(while7.java:21) Dr. Ammar Almomani-2017-BAU Page 57

58 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 Values in array2 by row are Dr. Ammar Almomani-2017-BAU Page 58

59 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(); run: Enter number of rows: 2 Enter number of columns: 3 Enter the first matrix Enter the second matrix The sum of the two matrices is Dr. Ammar Almomani-2017-BAU Page 59

60 8.2 Time Class Case Study Ch8_ex1: CH8:Classes and Objects: A Deeper Look 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 // 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(); // 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: " ); // attempt to set time with invalid values 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 // 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 Class Time1 does not declare a constructor, so the class has a default constructor that is supplied by the compiler. Each instance variable implicitly receives the default value 0 for an int. 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. private class members are not accessible outside the class. Method settime and Throwing Exceptions (cont.) For incorrect values, settime throws an exception of type IllegalArgumentException Notifies the client code that an invalid argument was passed to the method. 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. Dr. Ammar Almomani-2017-BAU Page 60

61 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 ); // 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" ) ); 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. 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

62 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 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. run: 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. Can use the this reference implicitly and explicitly. this explicitly in a non-static method s body this cannot be used in a static method this.touniversalstring(): 15:30:19 touniversalstring(): 15:30:19 Dr. Ammar Almomani-2017-BAU Page 62

63 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

64 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 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 Dr. Ammar Almomani-2017-BAU Page 64

65 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

66 8.8 Composition: A class can have references to objects of other classes as members. The example This is used called in this composition web page and is Employee is sometimes objects referred having to references as a has-a relationship. to Date objects. Employee.java Example: has An instance AlarmClock variables object for the needs employee's to know the first current name, time last and name, the birth time when date, it s and date of hire: two supposed String objects to sound and its two alarm, Date so objects. it s reasonable A Date object, to include as defined two references by Date.java, to Time has objects instance an variables object. 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

67 package ch8_4; public class Date private int month; // 1-12 private int year; // any year public Date( int themonth,int theyear ) month = checkmonth( themonth ); // validate month year = theyear; // could validate 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 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

68 package ch8_4; public class Employee private String firstname; private String lastname; private Date birthdate; private Date hiredate; // 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 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. 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

69 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

70 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

71 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

72 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

73 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

74 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

75 Dr. Ammar Almomani-2017-BAU Page 75

76 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

77 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 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

78 ch9_ex1: inheritance (bus extends car) package ch9_1; package ch9_1; package ch9_1; public class car private int width=20; public int y; public void setdata (int w) width=w; public int getdata() return width; public class bus extends car public class firstjava 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); run: 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

79 ch9_ex2: Relationship between Superclasses and Subclasses package ch9_2; public class food public void eat() System.out.println("i love the food"); package ch9_2; public class shawerma extends food run: i love the food i love the food package ch9_2; public class falafel extends 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(): void falafel shawerma Hello main(args:string[])) Dr. Ammar Almomani-2017-BAU Page 79

80 ch9_ex3:relationship between Superclasses and Subclasses Box width: double height: double depth: double +<constructor> Box (w: double, h:double, d:double) getvolume() :void run: Volume is : 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 MatchBox 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

81 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 - graduationyear: int - gpa: double student professor + <constructor> student ( firstname: String, lastname:string,graduationyear: int, gpa:double) + print():void + <constructor>professor(firstname:string, lastname: String) + print():void testoverride main(args:string[])) run: professor details peter noetal student Details sam walton Dr. Ammar Almomani-2017-BAU Page 81

82 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; public class professor extends Person public professor(string firstname,string lastname) super(firstname, public void print() System.out.println("professor details"); super.print(); package ch9_4; 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); Dr. Ammar Almomani-2017-BAU Page 82

83 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 Animal Dog run: + move(): void + move(): void Animals can move 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"); 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 Dr. Ammar Almomani-2017-BAU Page 83

84 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: A Deer IS-A Animal A Deer IS-A Vegetarian A Deer IS-A Deer A Deer IS-A Object 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; Vegetarian Animal Deer All the reference variables d, a, v, o refer to the same Deer object in the heap. Dr. Ammar Almomani-2017-BAU Page 84

85 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 DemoOverload + add(x:int,y:int):int + add(x:int,y:int,z:int):int + add(x:double,y:int):int run: Test main(string :args[]) UML :inheritance : static Polymorphism: Overloading Dr. Ammar Almomani-2017-BAU Page 85

86 package ch10_1; class DemoOverload public int add(int x, int y) return x+y ; public int add(int x, int y, int z) return x+y+z; package ch10_1; class Test public static void main(string[] args) DemoOverload demo=new DemoOverload(); System.out.println(demo.add(2,3)); //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 public int add(double x, int y) return (int)x+y; Dr. Ammar Almomani-2017-BAU Page 86

87 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) package ch10_2; class Vehicle public void move() Vehicle + move(): void MotorBike + move(): void UML :inheritance : Dynamic Polymorphism: System.out.println("Vehicles can move!!"); Test main(string :args[]) 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. Dr. Ammar Almomani-2017-BAU Page 87

88 package ch10_2; class MotorBike extends 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: rectangle + draw(): void square figure rectangle square + draw(): void + draw(): void area main(string: args[]) Ch10_ex3: Dynamic Polymorphism: (rectangle AND square extends figure) Dr. Ammar Almomani-2017-BAU Page 88

89 package ch10_3; class figure is the parent class public class figure void draw() System.out.println("figure"); package ch10_3; public class rectangle extends void draw() System.out.println("rectangle"); 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 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

90 Type of inheritance : Animal Vegetarian A Deer Animal Shape1: Single level inheritance A Deer Shape2: multi level inheritance -A interface Super class or concrete calss Shape3: multi level inheritance-b Object1 Object2 Object3... Shap4: polymorphic array(object from different class) 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 parent_protected_method(): void with_main child2 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 main() ch10_ex4_poly (inheritance with array polymorphism ) Dr. Ammar Almomani-2017-BAU Page 90

91 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; public class child1 extends protected void parent_protected_method() System.out.println("This is child 1-protected method"); package ch10_4; public class child2 extends protected void parent_protected_method() System.out.println("This is child2-protected method"); package ch10_4; 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(); 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(); Dr. Ammar Almomani-2017-BAU Page 91

92 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 package ch10_5; Concrete class B Dr. Ammar Almomani-2017-BAU Page 92

93 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 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: A.f() 7 B.g() 5 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. Dr. Ammar Almomani-2017-BAU Page 93

94 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

95 Note: vote final methods can't be overriden, because that's what final is designed to do: it's a 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 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 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 correct interface A void print(); class B implements A Dr. Ammar Almomani-2017-BAU Page 95

96 UML: ch10_ex6 demo_interface2 implement 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 IS-A demo_abstract2 If you need inheretance from demo_abstract2 you should create override because we have abstract method in demo_abstract abstract class Int x=2 IS-A demo_normal_class with_main Concrete class + abstract_method():void display():void + interface2_method():void main(string : args[]) ch10_ex6_abstract (abstract class and interface) Dr. Ammar Almomani-2017-BAU Page 96

97 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

98 package ch10_6; public class demo_normal_class extends 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 = " + 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 System.out.println(normalobj.x); normalobj.abstract_method(); normalobj.non_abstract_method(); normalobj.display(); normalobj.interface2_method(); demo_normal_class(); 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

99 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 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

100 Run: Please enter an integer x: 100 Please enter an integer y: 7 Result: 100 / 7 = 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 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

101 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 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. Dr. Ammar Almomani-2017-BAU Page 101

102 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

103 note: When a method throws an exception, the method terminates and does not return a value, and its local variables go out of scope 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

104 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

105 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 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

106 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

107 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

108 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 $ Withdrawing $ Withdrawing $ Sorry, but you are short $ 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

109 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 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(); Dr. Ammar Almomani-2017-BAU Page 109

110 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

111 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

112 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

113 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 ( 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

114 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 Dr. Ammar Almomani-2017-BAU Page 114

JAVA- PROGRAMMING CH2-EX1

JAVA- PROGRAMMING CH2-EX1 http://www.tutorialspoint.com/java/java_overriding.htm package javaapplication1; public class ch1_ex1 JAVA- PROGRAMMING CH2-EX1 //main method public static void main(string[] args) System.out.print("hello

More information

Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program.

Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program. 1 Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program. public class Welcome1 // main method begins execution of Java application System.out.println( "Welcome to Java Programming!" ); } //

More information

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved. 1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved. 1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 1 2 Introduction to Classes and Objects You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M Control Structures Intro. Sequential execution Statements are normally executed one

More information

Lecture 7: Classes and Objects CS2301

Lecture 7: Classes and Objects CS2301 Lecture 7: Classes and Objects NADA ALZAHRANI CS2301 1 What is OOP? Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly

More information

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I AL GHURAIR UNIVERSITY College of Computing CSC 209 JAVA I week 3- Control Statements: Part I Objectives: To use the if and if...else selection statements to choose among alternative actions. To use the

More information

Object Oriented Programming. Java-Lecture 1

Object Oriented Programming. Java-Lecture 1 Object Oriented Programming Java-Lecture 1 Standard output System.out is known as the standard output object Methods to display text onto the standard output System.out.print prints text onto the screen

More information

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of Basic Problem solving Techniques Top Down stepwise refinement If & if.. While.. Counter controlled and sentinel controlled repetition Usage of Assignment increment & decrement operators 1 ECE 161 WEEK

More information

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 3 Nothing can have value without being an object of utility. Karl Marx Your public servants serve you right. Adlai E. Stevenson Knowing how to answer one who speaks, To reply to one who sends a message.

More information

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M tutor Isam M. Al Jawarneh, PhD student isam.aljawarneh3@unibo.it Mobile Middleware

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 3 Introduction to Classes and Objects OBJECTIVES In this chapter you will learn: What classes, objects, methods and instance variables are. How to declare a class and use it to create an object. How to

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba Laboratory Session: Exercises on classes Analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

More information

How to engineer a class to separate its interface from its implementation and encourage reuse.

How to engineer a class to separate its interface from its implementation and encourage reuse. 1 3 Introduction to Classes and Objects 2 OBJECTIVES In this chapter you ll learn: What classes, objects, member functions and data members are. How to define a class and use it to create an object. How

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) Methods (Deitel chapter 6) 1 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) 1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Computer Programming C++ Classes and Objects 6 th Lecture

Computer Programming C++ Classes and Objects 6 th Lecture Computer Programming C++ Classes and Objects 6 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved Outline

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

More information

IQTIDAR ALI Lecturer IBMS Agriculture University Peshawar

IQTIDAR ALI Lecturer IBMS Agriculture University Peshawar IQTIDAR ALI Lecturer IBMS Agriculture University Peshawar Upon completing the course, you will understand Create, compile, and run Java programs Primitive data types Java control flow Operator Methods

More information

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014 M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014 Question One: Choose the correct answer and write it on the external answer booklet. 1. Java is. a. case

More information

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors Outline Overview history and advantage how to: program, compile and execute 8 data types 3 types of errors Control statements Selection and repetition statements Classes and methods methods... 2 Oak A

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Course: Object-Oriented Programming with Java Instructor : Assoc. Prof. Dr. Marenglen Biba Office : Faculty building

More information

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved. 1 6 Functions and an Introduction to Recursion 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare

More information

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995 Java Introduc)on History of Java Java was originally developed by Sun Microsystems star:ng in 1991 James Gosling Patrick Naughton Chris Warth Ed Frank Mike Sheridan This language was ini:ally called Oak

More information

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

More information

A A B U n i v e r s i t y

A A B U n i v e r s i t y A A B U n i v e r s i t y Faculty of Computer Sciences O b j e c t O r i e n t e d P r o g r a m m i n g Week 4: Introduction to Classes and Objects Asst. Prof. Dr. M entor Hamiti mentor.hamiti@universitetiaab.com

More information

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

Control Statements. Musa M. Ameen Computer Engineering Dept.

Control Statements. Musa M. Ameen Computer Engineering Dept. 2 Control Statements Musa M. Ameen Computer Engineering Dept. 1 OBJECTIVES In this chapter you will learn: To use basic problem-solving techniques. To develop algorithms through the process of topdown,

More information

Control Statements: Part Pearson Education, Inc. All rights reserved.

Control Statements: Part Pearson Education, Inc. All rights reserved. 1 5 Control Statements: Part 2 2 Not everything that can be counted counts, and not every thing that counts can be counted. Albert Einstein Who can control his fate? William Shakespeare The used key is

More information

Introduction to Java

Introduction to Java Introduction to Java Module 1: Getting started, Java Basics 22/01/2010 Prepared by Chris Panayiotou for EPL 233 1 Lab Objectives o Objective: Learn how to write, compile and execute HelloWorld.java Learn

More information

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

Objectives of CS 230. Java portability. Why ADTs?  8/18/14 http://cs.wellesley.edu/~cs230 Objectives of CS 230 Teach main ideas of programming Data abstraction Modularity Performance analysis Basic abstract data types (ADTs) Make you a more competent programmer

More information

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept F1 A Java program Ch 1 in PPIJ Introduction to the course The computer and its workings The algorithm concept The structure of a Java program Classes and methods Variables Program statements Comments Naming

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba Before writing a program to solve a problem, have a thorough understanding of the problem and a carefully planned approach to solving it. Understand the types of building

More information

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will

More information

Methods: A Deeper Look

Methods: A Deeper Look www.thestudycampus.com Methods: A Deeper Look 6.1 Introduction 6.2 Program Modules in Java 6.3 static Methods, static Fields and ClassMath 6.4 Declaring Methods with Multiple Parameters 6.5 Notes on Declaring

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 Suppose you want to drive a car and make it go faster by pressing down on its accelerator pedal. Before you can drive a car, someone has to design it and build it. A car typically begins as engineering

More information

JAVA Ch. 4. Variables and Constants Lawrenceville Press

JAVA Ch. 4. Variables and Constants Lawrenceville Press JAVA Ch. 4 Variables and Constants Slide 1 Slide 2 Warm up/introduction int A = 13; int B = 23; int C; C = A+B; System.out.print( The answer is +C); Slide 3 Declaring and using variables Slide 4 Declaring

More information

Control Statements: Part 1

Control Statements: Part 1 4 Let s all move one place on. Lewis Carroll Control Statements: Part 1 The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert Frost All

More information

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

More information

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases. Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 2: Sentinel-Controlled Repetition In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability.

More information

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3 Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Introduction to Java Applications; Input/Output and Operators

Introduction to Java Applications; Input/Output and Operators www.thestudycampus.com Introduction to Java Applications; Input/Output and Operators 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

More information

https://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.asp...

https://asd-pa.perfplusk12.com/admin/admin_curric_maps_display.asp... 1 of 8 8/27/2014 2:15 PM Units: Teacher: ProgIIIAPCompSci, CORE Course: ProgIIIAPCompSci Year: 2012-13 Computer Systems This unit provides an introduction to the field of computer science, and covers the

More information

CS11 Java. Fall Lecture 1

CS11 Java. Fall Lecture 1 CS11 Java Fall 2006-2007 Lecture 1 Welcome! 8 Lectures Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7-8 Lab Assignments Made available on Mondays Due one week later Monday, 12 noon

More information

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 Motivations If you assigned a negative value for radius

More information

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Course Overview This course teaches programmers the skills necessary to create Java programming system applications and satisfies the

More information

CompSci 125 Lecture 02

CompSci 125 Lecture 02 Assignments CompSci 125 Lecture 02 Java and Java Programming with Eclipse! Homework:! http://coen.boisestate.edu/jconrad/compsci-125-homework! hw1 due Jan 28 (MW), 29 (TuTh)! Programming:! http://coen.boisestate.edu/jconrad/cs125-programming-assignments!

More information

Fundamentals of Programming Session 7

Fundamentals of Programming Session 7 Fundamentals of Programming Session 7 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java

More information

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Methods 2003 Prentice Hall, Inc. All rights reserved. 2 Introduction Modules Small pieces of a problem e.g., divide and conquer Facilitate design, implementation, operation and maintenance

More information

Welcome to the Primitives and Expressions Lab!

Welcome to the Primitives and Expressions Lab! Welcome to the Primitives and Expressions Lab! Learning Outcomes By the end of this lab: 1. Be able to define chapter 2 terms. 2. Describe declarations, variables, literals and constants for primitive

More information

Section 2.2 Your First Program in Java: Printing a Line of Text

Section 2.2 Your First Program in Java: Printing a Line of Text Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two

More information

The Java language has a wide variety of modifiers, including the following:

The Java language has a wide variety of modifiers, including the following: PART 5 5. Modifier Types The Java language has a wide variety of modifiers, including the following: Java Access Modifiers Non Access Modifiers 5.1 Access Control Modifiers Java provides a number of access

More information

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 9/e Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Copyright 1992-2012 by Pearson Copyright 1992-2012 by Pearson Before writing a program to solve a problem, have

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All for repetition statement do while repetition statement switch multiple-selection statement break statement continue statement Logical

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Object Oriented Concepts and Programming (CSC244) By Dr. Tabbasum Naz

Object Oriented Concepts and Programming (CSC244) By Dr. Tabbasum Naz Object Oriented Concepts and Programming (CSC244) By Dr. Tabbasum Naz tabbasum.naz@ciitlahore.edu.pk Course Outline Course Title Object Oriented Concepts and Course Code Credit Hours 4(3,1) Programming

More information

Lecture 1 Java SE Programming

Lecture 1 Java SE Programming Lecture 1 Java SE Programming presentation Java Programming Software App Development Assoc. Prof. Cristian Toma Ph.D. D.I.C.E/D.E.I.C Department of Economic Informatics & Cybernetics www.dice.ase.ro cristian.toma@ie.ase.ro

More information

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac

More information

Methods: A Deeper Look

Methods: A Deeper Look 1 2 7 Methods: A Deeper Look OBJECTIVES In this chapter you will learn: How static methods and variables are associated with an entire class rather than specific instances of the class. How to use random-number

More information

13 th Windsor Regional Secondary School Computer Programming Competition

13 th Windsor Regional Secondary School Computer Programming Competition SCHOOL OF COMPUTER SCIENCE 13 th Windsor Regional Secondary School Computer Programming Competition Hosted by The School of Computer Science, University of Windsor WORKSHOP I [ Overview of the Java/Eclipse

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Course: Object-Oriented Programming with Java (4 credit hours) Instructor : Assoc. Prof. Dr. Marenglen Biba Office

More information

Introduction to OOP Using Java Pearson Education, Inc. All rights reserved.

Introduction to OOP Using Java Pearson Education, Inc. All rights reserved. 1 1 Introduction to OOP Using Java 2 Introduction Sun s implementation called the Java Development Kit (JDK) Object-Oriented Programming Java is language of choice for networked applications Java Enterprise

More information

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,

More information

CO Java SE 8: Fundamentals

CO Java SE 8: Fundamentals CO-83527 Java SE 8: Fundamentals Summary Duration 5 Days Audience Application Developer, Developer, Project Manager, Systems Administrator, Technical Administrator, Technical Consultant and Web Administrator

More information

A variable is a name for a location in memory A variable must be declared

A variable is a name for a location in memory A variable must be declared Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;

More information

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition 5.2 Q1: Counter-controlled repetition requires a. A control variable and initial value. b. A control variable

More information

Chapter 3. Selections

Chapter 3. Selections Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

More information

COWLEY COLLEGE & Area Vocational Technical School

COWLEY COLLEGE & Area Vocational Technical School COWLEY COLLEGE & Area Vocational Technical School COURSE PROCEDURE FOR JAVA PROGRAMMING CIS1868 3 Credit Hours Student Level: This course is open to students on the college level in either freshman or

More information

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries 1 CONTENTS 1. Introduction to Java 2. Holding Data 3. Controllin g the f l o w 4. Object Oriented Programming Concepts 5. Inheritance & Packaging 6. Handling Error/Exceptions 7. Handling Strings 8. Threads

More information

Mathematics/Science Department Kirkwood Community College. Course Syllabus. Computer Science CSC142 1/10

Mathematics/Science Department Kirkwood Community College. Course Syllabus. Computer Science CSC142 1/10 Mathematics/Science Department Kirkwood Community College Course Syllabus Computer Science CSC142 Bob Driggs Dean Cate Sheller Instructor 1/10 Computer Science (CSC142) Course Description Introduces computer

More information

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class. Name: Covers Chapters 1-3 50 mins CSCI 1301 Introduction to Programming Armstrong Atlantic State University Instructor: Dr. Y. Daniel Liang I pledge by honor that I will not discuss this exam with anyone

More information

AP CS Unit 3: Control Structures Notes

AP CS Unit 3: Control Structures Notes AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

Introduction to Computer Science I

Introduction to Computer Science I Introduction to Computer Science I Classes Janyl Jumadinova 5-7 March, 2018 Classes Most of our previous programs all just had a main() method in one file. 2/13 Classes Most of our previous programs all

More information

SYLLABUS JAVA COURSE DETAILS. DURATION: 60 Hours. With Live Hands-on Sessions J P I N F O T E C H

SYLLABUS JAVA COURSE DETAILS. DURATION: 60 Hours. With Live Hands-on Sessions J P I N F O T E C H JAVA COURSE DETAILS DURATION: 60 Hours With Live Hands-on Sessions J P I N F O T E C H P U D U C H E R R Y O F F I C E : # 4 5, K a m a r a j S a l a i, T h a t t a n c h a v a d y, P u d u c h e r r y

More information

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester

More information

Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information