Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Java Programming Language Abd El-Aziz Ahmed Abd El-Aziz Assistant Professor Institute of Statistical Studies and Research, Dept. of Computer and Information Sciences, Cairo University Outline Introduction. Lecture 1. Lecture 2. Lecture 3. Lecture 4. Lecture 5. Lecture 6. Lecture 7. Lecture 8. Lecture 9. Lecture 10. 2 Outline Introduction. Lecture 1. Lecture 2. Lecture 3. Lecture 4. Lecture 5. Lecture 6. Lecture 7. Lecture 8. Lecture 9. Lecture 10. 3 Introduction The objective of this course is to learn how to develop programs using java programming language. The references are: 1. “The Complete Reference, Java 2”, Herbert Schildt, nineth edition. 2. “ Java, How to program” , Paul Deitel and Harvey Deitel, Tenth edition. 3. http://www.java2s.com/ 4 Introduction The slides are available on scholar.cu.edu.eg/zizo. The grades are distributed as follows: 1. 70 marks for final exam. 2. 10 marks for quiz 1. 3. 10 marks for practical exam. 4. 10 marks for assignments. 5 Outline Introduction. Lecture 1. Lecture 2. Lecture 3. Lecture 4. Lecture 5. Lecture 6. Lecture 7. Lecture 8. Lecture 9. Lecture 10. 6 Lecture 1 Introduction to Object Oriented Programming The programming methodologies are : Procedural programming. Object-Oriented programming (OOP). 7 Lecture 1(Cont.) Introduction to Object Oriented Programming Procedural programming: • The languages use the procedural programming include Pascal • • • • and C languages. Involves dividing a large program into a set of modules to perform specific tasks. Module consists of single or multiple procedures. Procedures are also known as functions, routines, subroutines, or methods in various programming languages. In a program following procedural methodology, each step of a subprogram is linked to the previous step. 8 Lecture 1(Cont.) Introduction to Object Oriented Programming Procedural programming: 9 Lecture 1(Cont.) Introduction to Object Oriented Programming Procedural programming: The benefits are: 1. Easy to read program code. 2. Easy to manipulate code as a various procedures. 3. Code is more flexible as you can change the procedures. 10 Lecture 1(Cont.) Introduction to Object Oriented Programming Procedural programming: The features of procedural programming methodology are : 1. Large program are divided into smaller programs. 2. Most of the data are shared as global that can accessed from any where within the program. 3. The procedures are interdependent that can’t be reused in different applications. 11 Lecture 1(Cont.) Introduction to Object Oriented Programming Procedural programming: The procedural language’s limitations are: 1. The functions are interdependent, therefore, it’s difficult to separate one from another. They can’t be reused in other programs. 2. The data are visible and accessible, making it easy to manipulate the data from anywhere in the program. 12 Lecture 1(Cont.) Introduction to Object Oriented Programming Object- Oriented Programming (OOP) In this methodology, the large application is broken into independent components called objects, which can be integrated to create a complete program. The advantages of Object-Oriented programming are: 1. Real world programming. 2. Reusability of code. 3. Modularity of code. 4. Resilience to change()المرونة. 5. Information hiding. 13 Lecture 1(Cont.) Introduction to Object Oriented Programming Object- Oriented Programming (OOP) Real world programming: The object-oriented approach models the real world more accurately than the conventional, procedural approach. Reusability of code: In the object-oriented approach, you build classes, which can be used by several applications. Modularity of code: An object can be maintained independently of other objects. Resilience to change: Object-oriented programming also enables you to evolve various versions of software. When a change is suggested, the old system need not be completely re-built from scratch. 14 Lecture 1(Cont.) Introduction to Object Oriented Programming Object- Oriented Programming (OOP) Information hiding: Information hiding ensures data security in a program. Identifying the Applications of Object-Oriented Programming: 1. Character User Interface (CUI) based Applications: is an interface used to interact with a computer by typing commands on the command-line. CUI is not user-friendly because a user needs to remember all the commands and the syntax of the commands. 2. Graphical User Interface (GUI) based Applications: GUI is a method of interacting with a computer by directly manipulating graphical images in addition to text. 15 Lecture 1(Cont.) Introduction to Object Oriented Programming Object- Oriented Programming (OOP) Identifying the Applications of Object-Oriented Programming: 3. Computer Aided Designing/Manufacturing (CAD/CAM) :Concept of OOP is used to create graphical and numerical building blocks that can be assembled to form portable, flexible, and cost effective solutions for various real life problems. 16 Lecture 1(Cont.) Introduction to Object Oriented Programming Object- Oriented Programming (OOP): Classes and Objects: A class is the blueprint of objects. A class defines the structure and behaviors of an object or a set of objects. A class is a collection of various attributes and methods. Objects are the basic building of OOP. An object is an instance of a class. You can access the data of a class by using its methods. 17 Lecture 1(Cont.) Introduction to Object Oriented Programming Object- Oriented Programming (OOP): Classes and Objects: Objects display the following characteristics: 1. State: is indicated by a set of attributes and the values of these attributes. 2. Behavior: refers to a change of the state over a period of time. It is how an object acts and reacts, in terms of its state changes. 3. Identity: each object has a unique identity. The state and behavior comprise the properties of an object. The objects of the same class have the same behavior (methods), may or may not have the same state, but will never have the same identity. 18 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : 1. Encapsulation. 2. Abstraction . 3. Inheritance . 4. Polymorphism . 19 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Encapsulation: is the process of hiding all of the details of an object that do not contribute to its essential characteristics. Encapsulation is the feature that provides security to the data as well as the methods of a class. 20 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Abstraction: An Abstraction denotes the essential characteristics of an object that distinguishes it from all other kinds of objects and thus provides crisply defined conceptual boundaries, relative to the perspective of the viewer. Abstraction refers to the attributes of an object that clearly demarcates it from other objects. The concept of abstraction is implemented in object-oriented programming by creating classes. Encapsulation hides the irrelevant()ذات غير صلةdetails of an object and abstraction makes only the relevant details of an object visible. 21 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Inheritance: Enables you to extend the functionality of an existing class. Enables you to add new features and functionality to an existing class without modifying the existing class. Enables you to share data and methods among multiple classes. Superclass and Subclass : • A superclass or parent class is the one from which another class inherits attributes and behavior. • A subclass or child class is a class that inherits attributes and behavior from a superclass. 22 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : 23 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Relationships Between Classes 1. Kind-of relationship. 2. Is-A relationship. 3. Part-of relationship. 4. Has-A relationship. 24 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Kind of relationship: the kind-of relationship is used at the class level to describe the relationship between a superclass and a subclass. A subclass is a kind-of the superclass. Confirmed Ticket Kind-of Ticket 25 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Is-A relationship: it’s used at the instance level to describe the relationship between an instance (object) and a class. Confirmed Ticket Ticket for New York IsA Kind of Ticket Is-A 26 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Part-of relationship: when a class is an element of another class, it depicts the part-of relationship. Address Part of Student 27 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Has-A relationship: it’s the reverse of part-of relationship. When a class consists of another class, it depicts the has-a relationship. The has-a relationship is known as aggregation or composition. Student Detail Has-a Address 28 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Types of Inheritance: • Single inheritance • Multiple inheritance 29 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Single Inheritance: a subclass is derived from only one superclass. 30 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Multiple Inheritance: a subclass is derived from more than one superclass. 31 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Other types of Inheritance: 1. Multilevel. 2. Hybrid. 3. Hierarchical. 4. Multipath. 32 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Multilevel: a class is derived from an inherited class. For example, C inherits B and B inherits A. In this case, the class C inherits the data and methods of class B and class A (The data and methods of class A appears only once in class C), so the inheritance type for class C is multilevel. 33 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Hybrid: a derived class exhibits two or more than two types of inheritance. For example, D inherits from B and C (multiple inheritance), and B inherits from A (single inheritance), so the inheritance type for class D is hybrid. 34 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Hierarchical Inheritance: More than one subclass derived from a single base class. For example, A is the parent for B, and B is the parent of C, and D. 35 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Multipath Inheritance: it’s a combination of multiple and hierarchical inheritance. For example, A is the parent for B and C (hierarchical) and D inherits from B and C (multiple), then D has two paths of inheritance: A, B, D and A,C, D. 36 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Abstract classes and Methods: an abstract class is a class that can’t be instantiated. It contains methods that have no code. The methods having no implementation in the abstract class are called abstract methods. An abstract method is implemented in the subclasses of the abstract class instead of being implemented in the abstract class. 37 Lecture 1(Cont.) Introduction to Object Oriented Programming Features of Object- Oriented Programming : Polymorphism: is derived from two Latin words poly which means many and morph which means forms. Polymorphism enables an entity to have more than one form depending upon the context in which it’s used. For example, if the Deer class is inherited from the Animal and Vegetarian classes, then A Deer IS-A an Animal and A Deer IS-A Vegetarian, therefore, the Deer class is considered to be polymorphic. 38 Lecture 2 Java Programming Language Evolution of Java Year Development 1990 Sun Microsystems team headed by James Gosling developed software to manipulate electronic devices. 1991 A new language called Oak was introduced using C++. 1993 WWW appeared on the internet that transformed the text-based internet into graphical internet. 1994 Sun Microsystems team developed a web browser called HotJava to locate and run applet programs on the internet 1995 Oak was renamed as Java 1996 Java was established as an OOPL 39 Lecture 2 Java Programming Language What is the Java Technology? It’s a programming language. Its syntax is similar to C++ syntax. It’s used for creating all kind of applications, such as: 1. Character User Interface (CUI) Applications: has access to the system resources, such as file systems and can read and write to files on local computers. 2. Graphical User Interface (GUI) Applications: used in the Windows environment. 3. Applets: are small executable programs that run on a Web page and require a Javaenabled browser, such as Internet Explorer or Netscape Navigator. 4. Servlets: are the programs that are used to extend the functionality of Web servers. 5. Packages: are collection of classes that can be reused by applications and applets. 40 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Java applications are standalone programs (platform independent) , which run on any machine where the Java runtime environment (JRE) is installed. It’s a development environment, it provides a large suite of tools: a compiler (javac), Core class library(classes.zip and rt.jar), Debugger (jdb), a documentation generator (javadoc), an a class file packaging tool, Java Archive utility (jar), Bytecode interpreter (java). 41 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Java2 comes in three sizes: J2ME (Micro Edition): for applications running on mobile and embedded devices: mobile phones, set-top boxes, or Blu-ray Disc. J2SE (Standard Edition): complete ground-up development environment . J2EE (Enterprise Edition): everything in the J2SE plus an application server and prototyping tools. There are two main deployment environments. First, the JRE supplied by the Java 2 Software Development Kit (Java 2 SDK or JDK). 42 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? The JRE contains the Java Virtual Machine (JVM) and a complete set of class files for all of the java technology packages, which includes basic language classes, GUI component classes, and advanced collections API. 43 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? The second deployment environment is the browser. Most commercial browsers supply a java technology interpreter and runtime environment. 44 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Characteristics of Java: 1. Simple: in java, the programmer doesn’t need to handle memory manipulation. Java provides a system-level thread that tracks each memory allocation. During idle cycles in the JVM, the garbage collection thread checks for and frees any memory that can be freed. 2. Object-Oriented: the most basic program in java must be within a class. 45 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Characteristics of Java: 3. Compiled and Interpreted: the java programs are first compiled and then interpreted. While compiling, the compiler checks for the errors in the program and lists all the errors on the screen. After you have made the program error free and have recompiled it, the compiler converts the program into a computer language. The java compiler compiles the code into a Bytecode (machine code instructions for the JVM) that’s understood by java and stored in file (.class) extension. 46 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Characteristics of Java: The compiler generates a class file for each class in the source. At run time, the Bytecodes are loaded, checked, and run in an interpreter. In case of applets, the Bytecodes are downloaded, and they are interpreted by the JVM built-into the browser. A JVM contain an interpreter that interprets this Bytecode into a machine code and runs it. While interpreting, the interpreter reads and executes the code line by line. 47 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Characteristics of Java: The Interpreter can execute java code directly on any computer which a JVM has been installed. JVM is not a platform independent. Each platform needs to have its own JVM to run java applications. The java compiler is written in java, but the interpreter is written in C language. 48 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Characteristics of Java: 4. Portable: It refers to the ability of a program to run on any platform without changing the source code of the program. 5. Distributed: Java is used to develop applications that can be distributed among various computers on the network. Java is designed for distributed environment of the internet, because it supports various internet protocols, such as TCP/IP. 6. Secure: Java has built-in security features that verify that the programs don’t perform any destructive task, such as accessing the files on a remote system. 49 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? In java, the compiled Bytecode is strongly type checked. Any changes made in the Bytecode are flagged as errors and the program does not execute, which ensures the security of the java programs over the internet. 50 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Java Architecture : 1. Java programming language and class files: A java program is saved with .java extension. A .java file is compiled using javac (compiler) to generate the .class file, which contains the Bytecode. The JVM contains an interpreter that converts the Bytecode contained in the .class file to a machine object code and runs it. The JVM needs to be implemented for each platform running on a different operating system. 51 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Java Architecture : 2. Java Virtual Machine (JVM): is an imaginary machine that’s implemented by emulating it in a software on a real machine. The code for the JVM is stored in .class files, each of which contains codes for one public class. The VJM provides concrete definitions for the implementation of an instruction set, a register set, the class file format, a runtime stack, a garbage-collected heap, a memory area, fatal error reporting mechanism, and high-precision timing support. 52 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Java Architecture : Sun Microsystems provides implementations of the JVM for the Solaris OS, Linux, and Microsoft Windows. 53 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Java Architecture : JVM components : 1. Class loader: it dynamically loads the .class files from hard disks or network in the memory. Theses classes are determined from the class that contains the main(). A JVM has two types of class loaders: • Primordial Class Loader: it loads the java API required by the running program. • Class Loader Objects: it loads the classes of the running program. 54 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Java Architecture : JVM components : 2. Bytecode verifier: it checks the format of the class files, no pointer, violates access rights on objects, no operand stack overflows or underflows, the correction of parameters for all operations, and no illegal data conversions , such as converting integers to object reference. 55 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Java Architecture : JVM components : 3. Execution Engine (Interpreter): It interprets (converts the Bytecode to machine object code) and runs the Bytecode line by line. The interpreter has two functions: it converts and executes bytecodes, and it makes the appropriate calls to the underlying hardware. 56 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Java Architecture : JVM components : 4. Just-In-Time (JIT) compiler: some VJM contains JIT compiler. It compiles a portion of the verified Bytecode into machine (executable) code which is executed directly on the hardware platform without interpreting, because the JIT compiled code is in the machine code format. The running of the JIT compiled is faster than the running of the interpreted code, because it’s compiled and doesn’t require to be run, line after line. Hence the java code is running close to the speed of C or C++ with a small delay at the load time to enable the code to be compiled to the native machine code. 57 Lecture 2 (Cont.) Java Programming Language What is the Java Technology? Java Architecture : 3. Java Application Programming Interface (API): is a collection of classes and Interfaces that provide capabilities, such as GUI (J.F.C/Swing) and JDBC API. The related classes and interfaces of the java API are grouped into packages. 58 Lecture 2 (Cont.) Java Programming Language A Simple Java Application // code 2-1 The TestGreeting.java Application // Sample “Hello World” Application public class TestGreeting // we can remove the modifier public and then { public static void main (String [] args) { Greeting hello=new Greeting(); hello.greet(); } } 59 Lecture 2 (Cont.) Java Programming Language A Simple Java Application /*…*/ or // is used for comment. public class TestGreeting : this line declares the class name as TestGreeting. Therefore after the compilation a TestGreeting.class is created containing the compiled code in the same directory of the source code. The class can be defined with or without the modifier public. The name of the class which contains the main() must be similar to the file name . 60 Lecture 2 (Cont.) Java Programming Language A Simple Java Application public static void main (String [] args) : this line is where the program starts to execute. The interpreter (java) must find the main() to begin the executing or it refuses to run the program. Therefore the class that contains the main() must have the same name of the java file containing the class, to can the compiler knows the class name form the java file name and creates classname.class file, hence the interpreter can run the classname.class file that contains the main(). 61 Lecture 2 (Cont.) Java Programming Language A Simple Java Application public: it means the main() can be accessed by any platform has the JRE. static: it tells the compiler that the main() is usable. No instance of the class is needed to execute static methods. void: it means the main() doesn’t return any value. String [] args: it declares an array of parameters of type string to the main(). The parameters are types in the command line, such as java TestGreeting agrs[0] args[1] …. 62 Lecture 2 (Cont.) Java Programming Language A Simple Java Application Greeting hello=new Greeting();: this line creates an abject of the class Greeting. The new operator creates a space for the new object and initializes its data to 0 or null and returns a reference of the new object to be stored in the reference variable hello, so the variable hello contains the address(reference) of the new object returned by new operator. Since the class TestGreeting refers to the class Greeting (in Greeting.java), then the class Greeting is compiled automatically and Greeting.class is created. 63 Lecture 2 (Cont.) Java Programming Language A Simple Java Application Note: in cmd the Greeting.java and the class Greeting must be of the same name, while in IDE, such as netbeans, it’s not necessary, because the IDE creates a default package for the TestGreeting.java (containing main()) and Greeting.java(greeting.java), so the compiler can find Greeting class easily. 64 Lecture 2 (Cont.) Java Programming Language A Simple Java Application Code 2-2 The Greeting.java class public class Greeting { public void greet()// Between the parentheses, don’t write void, because //void is a data type , so it written as (void a) { System.out.println("Hello omar"); } } 65 Lecture 2 (Cont.) Java Programming Language A Simple Java Application public void greet() {System.out.println("Hello Omar");}: this is the definition of the greet(). This method is public, to can be accessed from the TestGreeting class. System : is a class provides standard input, standard output, and error output streams. This class is contained in the package java.lang. This is the default package which is imported automatically. out: is a static member variable belonging to the System class. out is an object of the class PrintStream. It’s used without an object, because it’s static variable. 66 Lecture 2 (Cont.) Java Programming Language A Simple Java Application printlin(): is a method of the object out used to print a message to the output stream. To create a java program: 1. Install the jdk. 2. Set the path variable for jdk\bin folder, such as D:\jdk1.6.0_25\bin as the following: r.click on my computer, properties, Advanced system settings, Advanced, environment variables, path, click edit and paste the path D:\jdk1.6.0_25\bin. So you can run the executable programs, such as javac, java, or xjc(xml schema compiler) from any directory c:> or d:> regardless of the path of the bin folder. 67 Lecture 2 (Cont.) Java Programming Language A Simple Java Application For example, if the jdk\bin folder in D partition, we can run javac as c:> javac d:\myjava\bank.java, where d:\myjava\bank.java is the path of the java file. In cmd change to the java file directory or you must give the complete path of the java files while compiling them. After the creation of the file, compile it as: d:\work files>my courses\java\Lecture2> javac TestGreeting.java. (javac and java location is known form Path variable). 68 Lecture 2 (Cont.) Java Programming Language A Simple Java Application The TestGreeting.class is stored in the same directory as the source file. The Greeting.java has been found since the class name is similar to the java file name, and compiled into Greeting.class automatically by the compiler, because TestGreeting class uses Greeting class. To run the program: d:\work files>my courses\java\Lecture2> java TestGreeting (classname.class). Netbeans and eclips are IDE. 69 Lecture 2 (Cont.) Java Programming Language A Simple Java Application 70 Lecture 2 (Cont.) Java Programming Language A Simple Java Application To see the Bytecode of the class file TestGreeting, write the command: javap –c TestGreeting. Javap –c (java print code) command prints the instructions that consist of the java Bytecode for each of the methods in the TestGreeting class. To see all the options, write: >javap –help. To create a documentation about TestGreeting.java, write:>javadoc TestGreeting.java or javadoc *.java. 71 Lecture 2 (Cont.) Java Programming Language A Simple Java Application /** documentation */. This is a documentation comment and in general its called doc comment. The JDK javadoc tool uses doc comments when preparing automatically generated documentation. Javadoc is a tool which comes with JDK and it is used for generating Java code documentation in HTML format from Java source code which has required documentation in a predefined format. 72 Lecture 2 (Cont.) Java Programming Language A Simple Java Application /** * The HelloWorld program implements an application that * simply displays "Hello World!" to the standard output. * * @author Zara Ali * @version 1.0 * @since 2014-03-31 */ public class HelloWorld { public static void main(String[] args) {/*Prints Hello, World! on standard output. System.out.println("Hello World!"); } }. 73 Lecture 3 Java Source File Java source file takes the following forms: Package declaration; Import declaration; Class declaration; 74 Lecture 3 (Cont.) Class Declaration Access specifiers class classname { attributes declaration; constructor declaration method declaration } Access specifiers are: public, private, protected, and friendly . 75 Lecture 3 (Cont.) Class Declaration public: is used to declare a member as public. private: is used to restrict the accessing of the member to the same level. private class member is accessed by the members of the same class. private class is referenced by classes in the same package. protected: variables and methods that are declared as protected are accessible only to the subclasses of the class in which they are declared. friendly (default): If you don’t specify any access specifier, the scope of data members and methods is friendly. A class, variable , or method with friendly access is accessible only to the classes of the same package. 76 Lecture 3 (Cont.) Class Declaration Access modifiers are: static, final, and abstract. static : is used with methods, variables, and inner classes that belongs to a class not to any instance of the class. final: is used with methods, variables, and classes. It indicates that the data member cannot be modified. A variable declared final is initialized at the declaration. A final method can’t be modified in the subclass. A final class can’t be inherited. All members of a final class are implicitly final. abstract: is used for methods and classes only. An abstract class is used as base class with abstract methods without implementations. Abstract methods has no implementation. 77 Lecture 3 (Cont.) Class Declaration The main difference between access specifiers and modifiers is that access specifiers defines the accessibility of the data members in a class and the modifiers determine how these members are used and modified by other classes. 78 Lecture 3 (Cont.) Attribute Declaration Access specifier type name [= intial value]; Method Declaration Access specifier return type name ( arguments) {} 79 Lecture 3 (Cont.) Identifier, Keywords, and Types In java, a statement must be terminated with a semicolon (;). A block is a set of statements bounded by {}. White spaces are ignored by the compiler. The identifier is a name given to a variable, class, or method. It must start with a letter, _, or $. Identifiers are case sensitive. The key words are not allowed as identifiers. For convention, the class name is title class, such as FirstApp, and the methods and variables are camel class, such as showBalance() and balanceAccount. 80 Lecture 3 (Cont.) Identifier, Keywords, and Types Packages names should be nouns in lowercase. There are two data types in java: 1. Primitive data types: integer (Byte (one byte), short (two bytes), int (four byte), long (eight bytes)), float (float (four byte), double (eight bytes)), char (two bytes), boolean (one byte). 81 Lecture 3 (Cont.) Identifier, Keywords, and Types boolean truth = true;//the literals (values) true, false, and null are //lowercase. char letter=‘\t’; int x=2(decimal form); int y= 077 (leading 0 indicates octal form); int z= 0xBAAC (leading 0x indicates hexadecimal). So the literals of integer type can be represented as decimal , octal, or hexa. All numeric types are signed numbers (no unsigned types). int x = 2L; // illegal, L indicates the decimal value 2 is represented as long value) 82 Lecture 3 (Cont.) Identifier, Keywords, and Types long x=77L(l);// long literal; long x=77; // represented as int Integer literals are int type by default unless appending L (l); double x=3.14; float y=2.3; (illeagel)// by default represented as double float x=3.14 f(F); //represented as float double x=3.5 f; // represented as float Floating literals are double by default unless appending f or F. 83 Lecture 3 (Cont.) Identifier, Keywords, and Types // code 3-1 public class Assign { public static void main(String argu[]) { int x,y ; float z=3.14f;// double z=3.14f; but z=3.14 is an error requires casting to //double double w=3.135; boolean truth= true; char c=‘A’; }} There is no casting between integers and booleans, so truth=1 is an error. 84 Lecture 3 (Cont.) Identifier, Keywords, and Types //code 3-2 public class MainClass { char c = 0xffff; // max char hex value byte b = 0x7f; // max byte hex value short s = 0x7fff; // max short hex value int i1 = 0x2f; // Hexadecimal (lowercase) int i2 = 0X2F; // Hexadecimal (uppercase) int i3 = 0177; // Octal (leading zero) // Hex and Oct also work with long. long n1 = 200L; // long suffix long n2 = 200l; // long suffix (but can be confusing) long n3 = 200; 85 Lecture 3 (Cont.) Identifier, Keywords, and Types public class MainClass { float f1 = 1; // not allowed float f2 = 1F; // float suffix float f3 = 1f; // float suffix float f4 = 1e-45f; // 10 to the power float f5 = 1e+9f; // float suffix double d1 = 1; double d2 = 1D; // double suffix double d3 = 47e47d; // 10 to the power }} 86 Lecture 3 (Cont.) Identifier, Keywords, and Types Overflow As int data type is 32 bit in Java, any value that surpasses 32 bits gets rolled over. In numerical terms, it means that after incrementing 1 on Integer.MAX_VALUE (2147483647), the returned value will be 2147483648. In fact you don't need to remember these values and the constants Integer.MIN_VALUE and Integer.MAX_VALUE can be used. 87 Lecture 3 (Cont.) Identifier, Keywords, and Types // code 3-3 public class MainClass { public static void main(String[] args) { int big = 0x7fffffff; // max int value 2147483647 System.out.println("big = " + big); int bigger = big + 1; System.out.println("bigger = " + bigger);// -2147483648}} 88 Lecture 3 (Cont.) Identifier, Keywords, and Types Underflow: Underflow is the opposite of overflow. While we reach the upper limit in case of overflow, we reach the lower limit in case of underflow. Thus after decrementing 1 from Integer.MIN_VALUE, we reach Integer.MAX_VALUE. Here we have rolled over from the lowest value of int to the maximum value. Integer y=1; y=y.Min_VALUE-1; System.out.println(y); 89 Lecture 3 (Cont.) Identifier, Keywords, and Types Casting of Expressions Casting means assigning a value of one type to a variable of another type. The casting between the compatible types are performed automatically, such as an int value can be assigned to a long variable, and a float value can be assigned to a double variable. If we assign a long variable to an int variable or a float variable to a double variable, the information may be lost, hence the compiler requires you to confirm the assignment with casting by placing the desired type between parentheses. For example: 90 Lecture 3 (Cont.) Identifier, Keywords, and Types // code 3-4 long x=99l; long z= 100; // 100 is an int type (default). int y=x; // wrong, needs casting to int int y= (int) x; // OK int y=99L; // wrong, needs casting to int int y= (int) 99L;// Ok. Information may be lost int y=99; // default integer literal. double l=12.4 f;// 12.f is a float type. float g=12.4;// 12.4 is a double type (default), illegal. 91 Lecture 3 (Cont.) Identifier, Keywords, and Types Variables can be promoted automatically to a longer form, such as int to long when there would be no loss of information in the arithmetic operations. For binary operators, such as + operator, when the two operands are of primitive types, the result type is determined as the largest of either operand, or int . Therefore, all binary operations on numeric types result in at least an int result, and possibly a larger one if long, flaot, double operands are in the expression. 92 Lecture 3 (Cont.) Identifier, Keywords, and Types short +short= int short+byte=int byte+byte=int int+int=int int+float=float int+doubel=double float+double=double int/int=int int/float=float 93 Lecture 3 (Cont.) Identifier, Keywords, and Types // code 3-5 short a=1,b=2,c ; c=a+b;// causes an error, because it assigns int to short. However, if c is declared as int, or a cast is done as c=(short) a+b; 94 Lecture 3 (Cont.) Identifier, Keywords, and Types String Concatenation with +: The + operator performs a concatenation of a String objects, producing a new String. For example: String fname=“omar”; String sname=“zizo”; String fullname=fname+” ”+ sname; If either argument of the + operator is a String object, the other argument is converted to a String object. All objects can be converted to a String automatically, using the toString() member function. 95 Lecture 3 (Cont.) Identifier, Keywords, and Types 2. Abstract data types (wrapper): they are derived from the primitive data types and have more functions than primitive data types, such as Character, String, Short, Byte, Integer, Float, Double, and Boolean. All variables refer to objects rather than primitives are called reference variables. 96 Lecture 3 (Cont.) Identifier, Keywords, and Types // code 3-6 public class Main { public static void main(String[] argv) throws Exception { Boolean refBoolean = new Boolean (true);// we can write: Boolean refBoolean = true; boolean bool = refBoolean.booleanValue();// true Byte refByte = new Byte((byte) 123); byte b = refByte.byteValue();//123 Character refChar = new Character('x'); char c = refChar.charValue(); Short refShort = new Short((short) 123); short s = refShort.shortValue(); 97 Lecture 3 (Cont.) Identifier, Keywords, and Types // code 3-6 public class Main { public static void main(String[] argv) throws Exception { Integer refInt = new Integer(123);// int refInt=123; int i = refInt.intValue(); Long refLong = new Long(123L); long l = refLong.longValue(); Float refFloat = new Float(12.3F); float f = refFloat.floatValue(); Double refDouble = new Double(12.3D); double d = refDouble.doubleValue(); } } 98 Lecture 3 (Cont.) Identifier, Keywords, and Types // code 3-7 public class Main { public static void main(String[] args) { System.out.println("Min byte value = " + Byte.MIN_VALUE);// static System.out.println("Max byte value = " + Byte.MAX_VALUE); // static System.out.println("Min short value = " + Short.MIN_VALUE); // static System.out.println("Max short value = " + Short.MAX_VALUE); // static System.out.println("Min int value = " + Integer.MIN_VALUE); // static System.out.println("Max int value = " + Integer.MAX_VALUE); // static System.out.println("Min float value = " + Float.MIN_VALUE); // static System.out.println("Max float value = " + Float.MAX_VALUE); // static System.out.println("Min double value = " + Double.MIN_VALUE); // static System.out.println("Max double value = " + Double.MAX_VALUE); // static }} 99 Lecture 3 (Cont.) Identifier, Keywords, and Types The following are some methods of the class Integer: 1 xxxValue() Converts the value of this Number object to the xxx data type and returned it. 2 compareTo() Compares this Number object to the argument. 3 equals() Determines whether this number object is equal to the argument. 5 toString() Returns a String object representing the value of specified int or Integer. 6 parseInt() This method is used to get the primitive data type of a certain String. 7 abs() Returns the absolute value of the argument. 5 toString() Returns a String object representing the value of specified int or Integer. 6 valueOf() Returns an Integer object holding the value of the specified primitive. 100 Lecture 3 (Cont.) Identifier, Keywords, and Types The Java platform provides the String class to create and manipulate strings. String greeting = new String("Hello world!“);. This statement creates a string. String greeting = "Hello world!“;. It also creates a string, because, whenever the compiler encounters a string literal in the code, the compiler creates a String object with its value in this case, "Hello world!'. char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'}; String helloString = new String(helloArray); // also creates a string object. 101 Lecture 3 (Cont.) Identifier, Keywords, and Types Some methods supported by String class are as follows: Char charAt (index) :returns the character at the specified index. int compareTo(String o): compares two strings lexicographically. int compareToIgnoreCase(String str) : compares two strings lexicographically, ignoring case differences. String concat(String str): concatenates the specified string to the end of this string. boolean equals(Object o) : compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. 102 Lecture 3 (Cont.) Identifier, Keywords, and Types Some methods supported by String class are as follows: int length() : returns the length of this string. int indexOf(int ch) :returns the index within this string of the first occurrence of the specified character. int indexOf(int ch, int fromIndex) :returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. int indexOf(String str): returns the index within this string of the first occurrence of the specified substring. 103 Lecture 3 (Cont.) Identifier, Keywords, and Types Some methods supported by String class are as follows: String substring(int beginIndex): returns a new string that is a substring of this string. String substring(int beginIndex, int endIndex): returns a new string that is a substring of this string. char[] toCharArray() :converts this string to a new character array. String toLowerCase(): converts all of the characters in this String to lower case using the rules of the default locale. String toString():this object (which is already a string!) is itself returned. 104 Lecture 3 (Cont.) Identifier, Keywords, and Types Some methods supported by String class are as follows: String toUpperCase() : converts all of the characters in this String to upper case using the rules of the default locale. String trim():returns a copy of the string, with leading and trailing whitespace omitted. String valueOf(primitive data type x) :returns the string representation of the passed data type argument. 105 Lecture 3 (Cont.) Identifier, Keywords, and Types Java provides the Date class available in java.util package, this class encapsulates the current date and time. The Date class supports two constructors. The constructor Date() initializes the object with the current date and time. Date date = new Date(); // display time and date using toString() System.out.println(date.toString());.// Fri Mar 11 18:39:19 EET 2015 boolean after(Date date):tests if this date is after the specified date. boolean before(Date date):tests if this date is before the specified date. 106 Lecture 3 (Cont.) Identifier, Keywords, and Types int compareTo(Date date) : compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. long getTime():returns how many milliseconds have passed since January 1, 1970, 00:00:00 GMT represented by this Date object. For example: Date date = new Date(97, 1, 23); long diff = date.getTime(); System.out.println("If date is 23-01-1997, " + diff + " have passed."); // If date is 23-01-1997, 856648800000 seconds have passed. 107 Lecture 3 (Cont.) Identifier, Keywords, and Types SimpleDateFormat , in java.text, is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. For example: Date d=new Date(); SimpleDateFormat ft = new SimpleDateFormat ("E dd.MM.yyyy 'at' hh:mm:ss a zzz"); System.out.println(ft.format(d));// Fri 06.03.2015 at 06:39:19 PM EET GregorianCalendar is a concrete implementation of a Calendar class . It’s assignment. 108 Lecture 3 (Cont.) Identifier, Keywords, and Types To read data from user, we use Scanner class in package java.util. For example: Scanner s=new Scanner(System.in); String f=""; f=s.next(f); System.out.println(f.charAt(0)); 109 Lecture 3 (Cont.) Identifier, Keywords, and Types // code 3-8 Public class UDate{private int day, month, year;} public class MyDate { private UDate cdate,bdate; public getcurrDate (){…}// public getBDate(){…}// public String calAge(){…} }// complete the code to get the age ass //assignment } public class TestMyDate{ public static void main(String args[]){ MyDate userdate= new MyDate(); userdate. getcurrDate (); userdate .getBDate (); userdate.calAge();}} 110 Lecture 3 (Cont.) Identifier, Keywords, and Types userdate is a reference variable contains the address of an object of type MyDate. Variables inside a method are called local variables. The local variables must be initialized manually before the first use. The compiler enforces that the method code cannot read a variable value before it assigned a value. Access specifiers cannot be used for local variables. Method parameters are created each time the method is called and they exist until the method is existed. The variables defined in a method are local to this method, so we can use the same variable name in several methods. 111 Lecture 3 (Cont.) Identifier, Keywords, and Types The variables defined outside the methods are two kinds: 1. Static class variables are created when the class is loaded and continue to exist for as long the class is loaded. They are initialized by the new operator. 2. Member (instant) variables are declared without the keyword static. They continue to exist for as long as the object exists. They are initialized by the new operator to their default values when the objects are constructed. 112 Lecture 3 (Cont.) Identifier, Keywords, and Types Variable Default value of primitive types Byte, short, and int 0 long 0L Float 0.0 F Double 0.0 D Char ‘\u0000’ (null) Boolean false All reference types null 113 Lecture 3 (Cont.) Identifier, Keywords, and Types // code 3-9 Public class ClassInitializer { boolean t; char c; byte b; short s; int i; long l; float f; double d;// member variables void print(String s) // s is a local variable{ System.out.println(s); } void printInitialValues() { print("Data type Initial value"); print("boolean print("char [" + c + "]"); print("short " + s); print("int " + i); print("long " + l); print("float " + f); print("double print("byte " + t); " + b); " + d); } 114 Lecture 3 (Cont.) Identifier, Keywords, and Types Public void comp() { int x=9, y,z; if(x>50) { y=9; } z=x+y;// y must be initialized before the first use. } 115 Lecture 3 (Cont.) Constructors A constructor is a set of instructions designed to initialize an instance of a class. Parameters are passed to constructors in the same way as methods. The name of the constructor must be the same as the class name. It has no return type, not even void. This is because the implicit return type of a class’ constructor is the class type itself. The access specifiers for constructors are public, private , and protected. Every class has at leat one constructor . If we don’t write a constructor, java provides one called the default constructor. This constructor has no parameters and has an empty body. If you add any constructor to the class, the default constructor is lost. 116 Lecture 3 (Cont.) Constructors // code 3-4 public class Date { private int day, month, year; public Date (int y, int m, int y){…}// }// use this class and complete the code to get the age as //assignment } public class TestMyDate{ public static void main(String args[]){ … } } 117 Lecture 3 (Cont.) Constructors Using the new operator to construct a new object causes the following: 1. The space for the new object is allocated and initialized to the forms 0 or null. 2. Any explicit initialization is performed. It overrides 0 and null by the explicit values. 3. The constructor is executed. The arguments passed in the () to new operator are passed to the constructor to initialize the member variables. 4. The return value from new is a reference to the new object in the heap, stored in the reference variable. 118 Lecture 3 (Cont.) Assigning References int x=7; int y=x; x and y are two independent variables. MyDate s=new MyDate (1,1,2015). MyDate t= s. s and t are two references of type MyDate. They refer to the same object of type MyDate. 119 Lecture 3 (Cont.) Passing by Value Java passes the arguments to the methods only by value. Therefore, the value in the calling method is not changed. When an object instance is passed as an argument to a method, the value of the argument is not the object, but a reference to the object. Therefore, the called method can change the contents of the object, but not the object reference. It’s common to pass by reference, but it’s not. 120 Lecture 3 (Cont.) The This reference this keyword does the following: 1. Resolve ambiguity between instance variables and parameters. 2. Pass the current object as a parameter to another method. 121 Lecture 3 (Cont.) The This reference // code 3-10 public class MyDate { private int day=1; private int month=1; private int year=2015; public MyDate (int day, int month, int year) { this.day=day; this.month=month; this year=year}//resolve ambiguity. public MyDate addDays (int days) { MyDate newDate= new MyDate(this);………}// this refers to the current / /object as a parameter. } 122 Lecture 3 (Cont.) Packages To group the related classes, use the package statement. If we want to group the TestGreeting and Greeting class files into a package, create a folder with the same name of the package name , for example in : d:\work files>my courses\java\Lecture2>, then modify the code2-1 and code 2-2 as follows: 123 Lecture 3 (Cont.) Packages // code 3-11 package myclasses; public class TestGreeting{ public static void main (String [] args) { Greeting hello=new Greeting(); hello.greet(); } } 124 Lecture 3 (Cont.) Packages // code 3-12 package myclasses; public class Greeting { public void greet() { System.out.println("Hello omar"); }} The folder myclasses contain the class files TestGreeting and Greeting. If package statement is not included in the file, all classes declared in that file belong to the default package which hasn’t a name. 125 Lecture 3 (Cont.) Packages Use the -d option in the compilation command, such as: d:\work files>my courses\java\Lecture2> javac –d . *.java Or d:\work files>my courses\java\Lecture2> javac –d . TestGreeting.java -d . Greeting.java. The –d specifies the destination where to put the generated class file. The dot (.) means put the class files in the folder myclasses directly. The running as the following command: d:\work files>my courses\java\Lecture2> java myclassses.TestGreeting (java packagename.class file). Or d:\work files>my courses\java\Lecture2> java myclassses/TestGreeting 126 Lecture 3 (Cont.) Import Statement The default package java.lang is imported automatically. The import statement takes the following forms: import pkgname[.subpkgname]. Classname; or import pkgname[.subpkgname]. *; (all classes) . The import statement tells the compiler where to find the classes. #include directive makes the compiler go to the C/C++ standard library and copy the code from the header files into the program. As a result, the program size increases, thus wasting memory and processor’s time. 127 Lecture 3 (Cont.) Import Statement import statement makes the JVM go to the Java standard library, execute the code there , and substitute the result into the program. Here, no code is copied and hence no waste of memory or processor’s time. Hence import is an efficient mechanism than #include. Therefore , a java source file takes the following forms: Package declaration; Import declaration; Class declaration; 128 Lecture 3 (Cont.) Import Statement // code 3-13 package myclasses; import myclasses.Greeting; public class TestGreeting { public static void main (String [] args) { greeting hello=new greeting(); hello.greet(); } } 129 Lecture 4 Operators Arithmetic operators (+,-,*,/,%). Increment and decrement (++ and --). Relational operators (<,>,<=,>=,==,!=). Logical operators : short-circuit (&&, ||, !) and bitwise logical operators (&,|,~,^ (XOR)), which are performed on the binary representation used in integers. The bitwise are byte-sized binary numbers. & 00101101 | 00101101 01001111 01001111 00001101 01101111 ~ 01001111 ^ 00101101 01001111 10110000 01100010 130 Lecture 4 (Cont.) Operators // code 4-1 public class Test { public static void main(String args[]) { int a = 60; /* 60 = 0011 1100 */ int b = 13; /* 13 = 0000 1101 */ int c = 0; c = a & b; /* 12 = 0000 1100 */ System.out.println("a & b = " + c ); c = a | b; /* 61 = 0011 1101 */ System.out.println("a | b = " + c ); 131 Lecture 4 (Cont.) Operators // code 4-1 c = a ^ b; /* 49 = 0011 0001 */ System.out.println("a ^ b = " + c ); c = ~ a; /*-61 = 1100 0011 */ System.out.println("~ a = " + c ); }} 132 Lecture 4 (Cont.) Operators Right shift operators (>> (signed)and >>>(unsigned)). 128>>1=128/21 =64. 256>>4=256/24 =16. -256>>4=-256/24 =-16. 10110>>2= 10 101 (the left operands value is moved from right by the number of bits specified by the right operand). 10110>>>2=00 101(the left operands value is moved from right by the number of bits specified by the right operand and shifted values are filled up with zeros). 133 Lecture 4 (Cont.) Operators Left shift operator (<<) 128<<1=128*21 =256 16<<2=16*22 =64. The left operands value is moved from left by the number of bits specified by the right operand. The shift operators are permitted only on integral types. The unsigned right shift >>> is effective only on int or long values. If we use it on a short or byte value, the value is promoted, with sign extension, to an int before >>> is applied. By this point, the unsigned shift usually has become a signed shift. 134 Lecture 4 (Cont.) Operators // code 4-2 public class Test { public static void main(String args[]) { int a = 60; /* 60 = 0011 1100 */ int b = 13; /* 13 = 0000 1101 */ int c = 0; c = a << 2; /* 240 = 1111 0000 */ System.out.println("a << 2 = " + c ); c = a >> 2; /* 15 = 1111, right shift for the first 2 bits from right */ System.out.println("a >> 2 = " + c ); c = a >>> 2; /* 15 = 0000 1111 */ System.out.println("a >>> 2 = " + c );}} 135 Lecture 4 (Cont.) Operators Assignment operators (+=,-=,*=,/=,%=,<<=,>>=,&=,|=,^=). Conditional Operator ( ? : ): Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as: variable x = (expression) ? value if true : value if false. 136 Lecture 4 (Cont.) Operators // code 4-3 public class MainClass { public static void main(String args[]) { int a = 1, b = 2, c = 3; a += 5; b *= 4; c += a * b; c %= 6; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c);} } 137 Lecture 4 (Cont.) Operators //code 4-4 public class Test { public static void main(String args[]){ int a=10 , b; b = (a == 1) ? 20: 30; System.out.println( "Value of b is : " + b ); // 30 b = (a == 10) ? 20: 30;// 20 System.out.println( "Value of b is : " + b ); } } 138 Lecture 4 (Cont.) Operators instanceof operator: this operator is used only for object reference variables. The operator checks whether the object is of a particular type (class type or interface type). instanceof operator is written as: ( Object reference variable ) instanceof (class/interface type). If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is the example: 139 Lecture 4 (Cont.) Operators //code 4-5 public class Test { public static void main(String args[]){ String name = "James"; // following will return true since name is type of //String boolean result = name instanceof String; System.out.println( result );// true } } 140 Lecture 4 (Cont.) Operators //code 4-6 class Vehicle {} public class Car extends Vehicle { public static void main(String args[]){ Vehicle a = new Car(); // Car c=new Vehicle() is not correct. boolean result = a instanceof Car; System.out.println( result ); // true} } 141 Lecture 4 (Cont.) Operators Precedence Category Operator Associativity unary ++,--(pre),!,~ Right to left Multiplicative *, /, % Left to right Additive + ,- Left to right Shift >>, >>>, << Left to right Relational >, >= ,< ,<= Left to right Equality ==, != Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND && Left to right Logical OR || Left to right Conditional ?: Right to left Assignment = +,= -,= *,= /,= %,= >>=, <<=, &= ,^= ,|= Right to left 142 Lecture 4 (Cont.) IF Statement The if statement is a conditional branch statement. The syntax of the if statement is either one of these two: If (booleanExpression) { statement (s) } if (booleanExpression) { statement (s) } else { statement (s) } 143 Lecture 4 (Cont.) IF Statement // code 4-7 public class MainClass { public static void main(String[] args) { int x = 9; if (x %2== 0) System.out.println(x+” is even”); else System.out.println(x+” is odd”); }} 144 Lecture 4 (Cont.) IF Statement // code 4-8 public class MainClass { public static void main(String[] arg) { int a = 2,b=3, char op=‘+; if (op ==‘+’ 0) { System.out.println(“sum is “ + (a+b)); else if (op == ’-’) { System.out.println(" (“sub is “ + (a-b)); ……… }} 145 Lecture 4 (Cont.) Switch Statement It’s an alternative to a series of else if. The switch statement allows you to choose a block of statements to run from a selection of code, based on the return value of an expression. The expression used in the switch statement must return an int, a byte, a short, a char, or an enumerated value. If there’s no break statement in the code, the execution continues into the code for the next case without checking the case expression’s value. A return statement can be used instead of a break statement. Moreover, if the switch statement in a loop, then a continue statement would cause execution to exit out of the switch statement. 146 Lecture 4 (Cont.) IF Statement // code 4-8 public class MainClass { public static void main(String[] args) { char i = '1'; switch (i) { case '1' : System.out.println("One."); break; case ‘2’ : System.out.println("Two."); break; case ‘3’ : System.out.println("Three."); break; default: System.out.println("You did not enter a valid value."); }}// //what happen if switch begins with default. 147 Lecture 4 (Cont.) Looping Statement For Loop for (init exp; cond exp; inc/dec exp) { statement (s);} for (init exp1, init exp2 ; cond exp; inc/dec exp1, inc/dec exp2) { statement (s);} For example, for ( int i=0; i<10; i++) { System..out. Println(i+ “ squared is ”+ (i * i));} In the previous example, int i is declared and defined within the for block. The variable i is accessible only within the scope of this for block. 148 Lecture 4 (Cont.) Looping Statement while Loop while ( cond exp) { statement (s);} For example, int i=0 while(i<10) { System..out. Println(i+ “ squared is ”+ i * i); i++;} do/while Loop do { statement (s);} while ( cond exp); For example, int i=0 do { System..out. Println(i+ “ squared is ”+ (i * i)); i++;} while(i<10); Use the for loop in cases where the loop is to be executed a predetermined number of times. Use the while and do loops in cases where this is not determined beforehand. 149 Lecture 4 (Cont.) Looping Statement The break statement is used to exit from a loop, for example: do{ statements; if (cond) {break;} statements }while (test exp); The continue statement is used to skip over and jump to the end of the loop body, and return the control to the loop-control, for example: do{ statements; if (cond) {continue;} statements }while (test exp); 150 Lecture 5 Arrays Arrays are used to group objects of the same type. Arrays enable you to refer to the group of objects by a common name. You can declare arrays of any type; either primitive or class: char s[];// array declaration (no size is specified). Point p[];// where Pointer is a class. char [] t,s ;// more readable as char array of s. When declaring arrays with brackets to the left, the brackets apply to all variables to the right of the brackets. An array is an object of the class Array (java.util.Arrays). The declaration doesn’t create the object itself. Instead, the declaration of an array creates a reference to an array object. 151 Lecture 5 (Cont.) Arrays The actual memory used by the array elements is allocated dynamically either by a new statement or by an array initializer. To create an array, s= new char[26]; this line creates an array of 26 char values. After creation, the array elements are initialized to the default value (‘\u000’). new operator allows to determine the size of the array before memory allocating. However, since the array is created, the size can’t be changed. The object s contains a reference to the first element of the array. The values of the array are s[0]…s[25]. 152 Lecture 5 (Cont.) Arrays Example: public char [] createArray() { char [] s ;// an object refers to an array object // int x=26; // char []s=new char [x]; s= new char [26];// creates an array, initializes each cell to null, and assign the //reference of the newly created array to s. //we can write, char []s={‘a’, ‘b’, ‘c’, …..}; for (int i=0; i<26; i++) s[i]=( char) (‘A’+ i);// casting is needed, because the result is int. return s; }// this method returns an array of char 153 Lecture 5 (Cont.) Arrays Example: public Point [] createArray() { Point [] p ;// an object refers to an array object p= new Point [10];// creates an array and initialize each cell to null, indicating //that it doesn’t refer to a Point object. // Point [] p={new Point(1,2), new Point(3,4),} for (int i=0; i<10; i++) p[i]= new Point (i, i+1);// a real Point object is created. return p; }// this method returns an array of Point 154 Lecture 5 (Cont.) Arrays // code 5-1 public class TestArray { public static void main(String [] args) { double [] myList = {1.9, 2.9, 3.4, 3.5}; for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } Assignment: write a java program to sort an array. Moreover, the program allows the user to search about a value in the array. The program continues until the user stop it. 155 Lecture 5 (Cont.) Arrays J2SE version 5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable. //Code 5-2 public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; for (double element: myList) { System.out.println(element); } } } 156 Lecture 5 (Cont.) Arrays We can also pass arrays to methods. For example, the following method displays the elements in an int array: public static void printArray(int[] array) // pass by value { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } } 157 Lecture 5 (Cont.) Arrays A method may also return an array. For example, the method shown below returns an array that is the reversal of another array: public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; } The length attribute of the array object stores the number of elements in the array. If an out-of-bounds runtime access occurs, a runtime exception is thrown. 158 Lecture 5 (Cont.) Arrays In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look and act like regular multidimensional arrays. However, as you will see, there are a couple of subtle differences than the other languages. To declare a multidimensional array variable, specify each additional index using another set of square brackets. For example, the following declares a two-dimensional array variable called twoDim: int [][] twoDim=new int [4][];// twoDim=new int [][4] is not legal. twoDim[0]=new int [5]; twoDim[1]=new int [5]; The object that is created by first call to new is an array that contains 4 elements. Each element is a null reference to an object of type array of int, and we must initialize each array separately. 159 Lecture 5 (Cont.) Arrays Because of this separation, we can create non-rectangular arrays of arrays. That is, we can initialize the elements of twoDim as follows: twoDim[0]=new int [2]; twoDim[1]=new int [4]; twoDim[2]=new int [6]; twoDim[3]=new int [8]; If we write, int [][] twoDim= new int [4][5], then we create an array of 4 arrays of 5 integers for each one, i.e., we do not need to allocate the same number of elements for each dimension. We can’t resize an array. However, we can use the same reference variable to refer to a new array. For example: int [] myArray=new int [6]; myArray=new int [10]; In this case, the first array is lost unless another reference to it is retained. 160 Lecture 5 (Cont.) Arrays Java provides a static method called arraycopy in System class, to copy arrays. For example: int [] myArray={1,2,3,4,5,6}; int [] hold={10,9,8,7,6,5,4,3,2,1}; System.arraycopy(myArray,0,hold,0, myArray.length);// copy all of myArray to //hold array, so hold has 1,2,3,4,5,6,4,3,2,1. Assignment 3 161 Lecture 6 Inheritance The aim of the inheritance is the reusability; i.e., an object of one class can reuse the methods and attributes from another class. For example, an employee class and a manager class. A manager is an employee, but an employee with additional features. 162 Lecture 6 (Cont.) Inheritance // code 6-1. public class Employee{ public String name=“”; public double salary; public Date birthdate(); Public String getDetails(){…};} // code 6-2. public class Manager{ public String name=“”; public double salary; public Date birthdate(); public String department; Public String getDetails(){…};} 163 Lecture 6 (Cont.) Inheritance Instead of creating a manager class with duplicate data, we create a subclass called manager from the existing employee as follows: public class Manager extends Employee{ public String department;} Java permits a class to extend one other class only at the compile time, called single inheritance. The interfaces provides the benefits of multiple inheritance without suffering from any of its drawbacks. The extends keyword allows the subclasses to inherit all the properties of the superclass except for the private properties of the superclass. 164 Lecture 6 (Cont.) Inheritance Access Control public: allows access in same class, same package, subclass, and universe. private: allows access in same class only. protected: allows access in same class, same package, and subclass. (it allows the inheritance between classes in different packages). friendly (default):allows access in same class and same package. (it allows the inheritance between classes in the same package). 165 Lecture 6 (Cont.) Inheritance Overriding Methods The subclass inherits the data or methods members which have the access public or protected. If a method is defined in a subclass so that the name, return type, and arguments list match exactly of a method in the parent class, the new method is said to override the old one. Rules for method overriding: 1. The argument list should be exactly the same as that of the overridden method. 2. The return type should be the same or a subclass of the return type declared in the original overridden method in the superclass. 166 Lecture 6 (Cont.) Inheritance Rules for method overriding: 3. The access level cannot be more restrictive than the overridden method's access level. For example: if the superclass method is declared public then the overridding method in the subclass cannot be either private or protected (if the method is private access, it will be public access). 4. Instance methods can be overridden only if they are inherited by the subclass. 5. A method declared final cannot be overridden. 6. A method declared static cannot be overridden but can be re-declared. 7. If a method cannot be inherited, then it cannot be overridden. 8. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. 9. A subclass method can invoke a superclass method using the keyword super. 167 Lecture 6 (Cont.) Inheritance // code 6-3. public class Employee{ private String name, private double salary; private Date birthdate(); public String getDetails(){return name+” ”+salary};} // code 6-2. public class Manager extends Employee{ public String department; public String getDetails(){return super. getDetails()+ department};} 168 Lecture 6 (Cont.) Inheritance Polymorphism An object has only one form given to it when constructed. However, a variable is polymorphic, because it can refer to objects of different forms. Java permits you to refer to an object with a variable that’s one of the parent class types, so we can write: Employee e = new Manager(); Using the variable (e), we can access only the parts Manager class that are parts of Employee class. The specific parts of Manager class (dep(),setdep(),getdep()) are hidden for e, because the compiler considers e as an Employee not a Manager at the compile time. 169 Lecture 6 (Cont.) Inheritance Polymorphism if we write, e. getDetails(); the compiler will not flag an error, because getDetails() is a part from the Employee class. (compile time). At run time , there is an instance of Manager and no instance of Employee, so the overridden getDetails() of Manager will be executed. This called virtual method invocation. In C++, you get this behavior only if you mark the method as virtual in the source. The overriding is called dynamic polymorphism. 170 Lecture 6 (Cont.) Inheritance Heterogeneous Collections We can create collections of objects that have a common class. Such collections are called homogeneous collections. For example: MyDate[] dates= new MyDate[2]; Dates[0]= new MyDate(22,12,1979); Dates[1]= new MyDate(22,1,1970); A heterogeneous collection is a collection of dissimilar items that have a common ancestor class. Employee [] staff= new Employee [3]; staff[0]= new Employee(); staff[1]= new Manager(); staff[2]= new Engineer(); 171 Lecture 6 (Cont.) Inheritance Heterogeneous Collections In Java, all classes are inherited from the Object class. Therefore, we can use an array of Object as a container for any combinations of objects. 172 Lecture 6 (Cont.) Inheritance Polymorphic Arguments We can write a method that accepts a generic objects and works on objects of any subclass of this objects. For example: public static double tax(Employee e)// Polymorphic Arguments{ if (e instanceof Manager) return e.getsal()*0.2; // getsal() in the Employee class else if(e instanceof Engineer) return e.getsal()*0.1; else return e.getsal()*0.1; } 173 Lecture 6 (Cont.) Inheritance Polymorphic Arguments if (e instanceof Manager) Manager m=(Manager) e; If you don't make casting, an attempt to execute specific parts from Manager class would fail because the compiler cannot locate these parts in the Employee class. The class to which the cast is taking place must be some subclass of the current reference type. If the compiler permits casting, the object type is checked at runtime. 174 Lecture 6 (Cont.) Inheritance Overloading Methods (Static Polymorphism) We have overloading, if there are some methods with the same name and different arguments in the type or count. The behavior of the overloaded method is determined in the compile time. Instead of using many methods with the same name, Java added a new feature in js2e5 called variable arguments. For example, public static int avg (int...count)// count is an object of type array int[].This //permits the method to iterates over the array. { int sum=0; for(int i:count) sum+=i; return sum/count.length; }. 175 Lecture 6 (Cont.) Inheritance Overloading Constructor this keyword in the constructor must be the first line of the constructor. Java automatically calls the default constructor of the parent class before the calling of the constructor of the derived class, so the parent's constructor is not inherited. Java doesn't call the parent parameterized constructor. Hence, you must use super() at the first line of a derived constructor to call the parent parameterized constructor. If we don't call super(list), the compiler calls super() implicitly. In this case, if there is no parent's constructor with zero parameters, a complier error results. 176 Lecture 6 (Cont.) Inheritance Constructor and Initializing Objects new operator process do the following: 1.allocate memory for the object. 2.initialize the instance vars to their default values. 3.bind the constructor parameters if found. 4.if there's explicit this(), call recursively. 5.call recursively the implicit or expilicit super(), except for object class (no parent). 6.execute the explicit initialization. 7.execute the body of the current constructor. 177 Lecture 6 (Cont.) Inheritance The Object Class If a class is declared with no extends, the compiler adds implicitly the code extends Object. This enables you to override methods, such as equals() and toString(). The equal() works as == operators; i.e; for any two reference variables x and y, x==y or x.equals(y) returns true if and only if x and y refer to the same object. Therefore, equals() is overridden to compare the contents of x and y. For example, the equals() in String class returns true if and only if the arguments is not null and is a String object represents the same sequence of characters. 178 Lecture 6 (Cont.) Inheritance The Object Class The toString() converts an object to a String. The compiler converts an object to a String automatically, when a string conversion takes place. For example, Date now= new Date(); System.out.println(now); // equivalent to System.out.println(now.toString()); This statement will print the reference of the object refereed by the reference variable now. Therefore, toString() is overridden in the Date class to can print the content of the object refereed by the reference variable now. 179 Lecture 7 Static Keyword The static keyword declares members (attributes, methods, and nested classes) that are associated with the class rather than the instances of the class. Class Attributes (Variables) The class attribute is a shared attribute among all instances of a class. For example, you could use it as the basis for communication between instances or to keep track of the number of instances that have been created. public class Count { private int serialno; public static int count=0;// static var public Count() { count++; serialno=count;} 180 Lecture 7 (Cont.) Static Keyword A static variable is similar to a global variable. Java doesn’t have a global variable, but a static variable is a single variable that is accessible from any instance of the class. If a static variable is public, it can be accessed using the class name. A class can contain code in static blocks called static initializers that are not part of normal methods. Static blocks are used to initialize the static attributes. They are executed once when the class is loaded. If a class contains more than one static block, they are executed in the order of their appearance in the class. public static int count; static { counter= 0;} 181 Lecture 7 (Cont.) Static Keyword Static Methods (Class Methods) The class method can be used using the class name. Because the class method can be invoked without any instance, there is no this value. Therefore, a static method can’t access instance variables (non static) other than the local variables, static attributes, and its parameters. Attempting to access non static variables causes a compiler error. The non static methods can access the static attributes. 182 Lecture 7 (Cont.) Static Keyword Static Methods (Class Methods) Static methods can’t be overridden. Two static methods with the same signature in a class hierarchy means that there are two independent class methods. If a class method is applied to an object reference, the method invoked is the one for the class for which the variable was declared. The main() is a static because the JVM doesn’t create an instance of the class when executing the main(). Therefore, the main() can only access the static attributes of a class to which it belongs. Hence, if you have member data (non static), you must create an object to access them. 183 Lecture 7 (Cont.) Final Keyword The final keyword declares attributes, methods, and classes. Final classes: can’t be inherited. For example, java.lang.String class, all the wrapper classes, and class Scanner are final classes. Final methods: can’t be changed nor overridden. Final variables: are constant. It should be initialized in the declaration. For example: public final double pi=3.14;// should be initialized final Point x=new Point(3,4);// x can’t refer to any other object. However, //you can change it’s contents, because only the reference itself is final. 184 Lecture 7 (Cont.) Final Keyword A blank final variable is a final variable that is not initialized in its declaration. The initialization is delayed. A blank final instance variable must be initialized in a constructor or an instance initializer (set once only). A blank final local variable is initialized at any time in the body of the method (set once only). For example: private final int x; { x=9; } A static final variable can’t be initialized in a constructor, because the constructor is executed and try to access it during the creation of each object. 185 Lecture 7 (Cont.) Final Keyword // code 7-1 public class Employee { public static final int x; {x=0;}// legal /* public Employee () {x=0;} error ; “can’t assign a value to a final variable” */ public final int y; public Employee () {y=0;}// legal } 186 Lecture 7 (Cont.) Enumerated Types It’s used to make the code more professional code. Enumeration means having a finite set of symbolic names that represents the values of an attribute. For example, to represent the week days, you should create a set of symbols: Saturday,…, Friday. 187 Lecture 7 (Cont.) Enumerated Types // code 7-2 enum WeekDays // enum creates a type called WeekDays as a class { // public, static, and final members Saturday, Sunday, Monday //names without values} The constructor of WeekDays with no arguments public class Employee { public WeekDays w; public static void main(String a[]){ Employee e=new Employee(); e.w=WeekDays.Monday; // check the members of WeekDays }} 188 Lecture 7 (Cont.) Enumerated Types // code 7-3 enum WeekDays // enum creates a type called WeekDays as a class { // public, static, and final members Saturday (0), Sunday (1), Monday (2) ;//names with explicit values Private WeekDays(int x){}// Sunday(1.4) if the constructor argu is float }// end of enum public class Employee { public WeekDays w; public static void main(String a[]){ Employee e=new Employee(); e.w=WeekDays.Monday; // check the members of WeekDays }} 189 Lecture 7 (Cont.) Static Imports If you have to access the static members of a class, it is necessary to qualify the references with class name from which they come. This is also true for enumeration type. J2SE version 5.0 provides the static import feature that enables unqualified access to static members without having to qualify them with the class name. import static packagename.classname.*; we use * to can access all the static members of the class. In this case, we can refer to the static members without the class name . Hence, we don't need to import the whole class. 190 Lecture 7 (Cont.) Abstract Class It’s a class that declares methods that don’t supply implementations (abstract methods). The implementations of the methods are supplied by the subclasses. The abstract class may or may not contain any abstract method, but the abstract method must be included in an abstract class. The access modifier of the abstract method may be protected, default, or public. The abstract class as a concrete class, it contains constructors, concrete methods, and attributes. 191 Lecture 7 (Cont.) Abstract Class The abstract class is a partial blueprint(the methods are not implemented), so we can't create an object of the abstract class. The subclasses of the abstract class are the only classes that can implement the abstract methods, so the inheritance is requited with the abstract class. The inheritance makes the abstract class as a complete class. The subclass must implement (override) all the abstract methods of the abstract class. Any child class must either override the abstract method or declare itself abstract. A child class that inherits an abstract method must override it. If they do not, they must be abstract and any of their children must override it. 192 Lecture 8 Interfaces The interface provides the ability to capture the similarities between unrelated classes without forcing a class relationship. The interface provides multiple inheritance by declaring a class implements several interfaces. An interface is a collection of public and abstract methods, and public, static, and final attributes (constant only). A class implements an interface, thereby inheriting the abstract methods of the interface. The class can implement one or more interfaces and the interface can be implemented by many classes. However, a class extends only one class. Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. 193 Lecture 8 (Cont.) Interfaces An interface is similar to a class in the following ways: 1. An interface can contain any number of abstract methods. 2. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file. 3. The bytecode of an interface appears in a .class file. 4. Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name. An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements. 194 Lecture 8 (Cont.) Interfaces However, an interface is different from a class in several ways, including: 1. You cannot instantiate an interface. 2. An interface does not contain any constructors. 3. All of the methods in an interface are abstract. 4. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. 5. There ‘s no object of an interface . 6. An interface is not extended by a class; it is implemented by a class. 7. An interface can extend multiple interfaces. 195 Lecture 8 (Cont.) Interfaces The important differences between abstract class and interface are: 1. Abstract class can have abstract as well as non-abstract(concrete) methods whereas interface can have only abstract methods. 2. Abstract class doesn't support the feature of multiple inheritance whereas interface supports the feature of multiple inheritance. 3. Abstract class should be extended by extends keyword, whereas interface should be implemented by implements keyword. 4. Abstract class can have final and non-final variables, but interface contains only static final variables i.e. constants. 196 Lecture 8 (Cont.) Interfaces If we have Engineer, technician, and manager classes, we can provide their base functionalities in an abstract class called an Employee class which is the root of the inheritance tree. Now if we want to make something fly. What can fly? Birds, airplane, Superman, and Houseflys , so these classes should provide similar functionalities, even though they are widely spaced on an inheritance tree. The solution? Make them use interfaces. 197 Lecture 8 (Cont.) Interfaces interface flyer { takeoff(); land(); fly();} Public class Bird extends Animal implements Flyer { public void takeoff(){// takeoff () implementation} public void land(){// land () implementation} public void fly(){//fly () implementation} public void eat(){// override eating behavior} public void buildnest(){//its behavior} } 198 Lecture 8 (Cont.) Interfaces An interface is implicitly abstract. We do not need to use the public or abstract keyword when declaring an interface. Each method in an interface is also implicitly public abstract, so the abstract keyword is not needed. The class Bird inherit the class Animal and implement the interface Flyer. This sounds like multiple inheritance, but it is not. The danger of multiple inheritance is that a class could inherit two distinct implementations of the same method. This is not possible with interface, because an interface method declaration supplies no implementations. 199 Lecture 8 (Cont.) Interfaces When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration. 200 Lecture 8 (Cont.) Exceptions There are three types of errors: 1. Compile error: it’s determined by the compiler, such as syntax error. 2. Logical error: it’s an error in the idea of the code. It must be detected by the programmer. 3. Run time error: it’s an error occurred during the run time. In this case, JVM creates an exception object to indicate the programmer about the run time error and terminate the program. 201 Lecture 8 (Cont.) Exceptions An exception is an mechanism used by programmers to describe what to do when something unexpected happens. There are three types of errors: 1. Compile error: it’s determined by the compiler, such as syntax error. 2. Logical error: it’s an error in the idea of the code. It must be detected by the programmer. 3. Run time error: it’s an error occurred during the run time. In this case, JVM creates an exception object to indicate the programmer about the run time error and terminate the program. 202 Lecture 8 (Cont.) Exceptions The try-catch statement It’s a mechanism provided by java for figuring out which exception was thrown and how to recover form it. Example: public static void main(String a[]) { int sum=0; for(int i=0;i<a.length;i++) sum+=Integer.parseInt(a[i]); System.out.println(sum);} /* if the user inputs strings, such as "two", JVM will creates an object of NumberFormatException class, i.e., the exception is occurred and the program will be terminated .* / 203 Lecture 8 (Cont.) Exceptions The try-catch statement public static void main( String a[]) When the exception occurred and we catch the exception using try block /* a try block finds the exception and throws it to a catch block.*/ try { int sum=0; for(String i: a) sum+=Integer.parseInt(i); System.out.println("the sum= "+ sum); } catch(NumberFormatException e) { System.err.println(e.getMessage() ); }// e.printStackTrace() /* if the inputs are 1, two, 3.0,4, the catch block is executed for two and the loop will not be continued and sum will not printed. The program will continue to execute the code after the catch block.*/ 204 Lecture 8 (Cont.) Exceptions The try-catch statement public static void main( String a[]) When the exception occurred and we catch the exception using try block /* a try block finds the exception and throws it to a catch block.*/ int sum=0; for(String i: a) { try {sum+=Integer.parseInt(i);} catch(NumberFormatException e) { System.err.println(e.getMessage() ); }}// e.printStackTrace() System.out.println("the sum= "+ sum); /* if the inputs are 1, two, 3.0,4, the catch block is executed for two and 3.0. the sum will be printed (5)*/ 205 Lecture 8 (Cont.) Exceptions The try-catch statement public static void main( String a[]) { try{ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } /* The output is: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block*/ 206 Lecture 8 (Cont.) Exceptions The try-catch statement A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following: try { //Protected code } catch(ExceptionType1 e1) { //Catch block } catch(ExceptionType2 e2) { //Catch block } catch(ExceptionType3 e3) { //Catch block } 207 Lecture 8 (Cont.) Exceptions The try-catch statement The previous statements demonstrate three catch blocks after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. 208 Lecture 8 (Cont.) Exceptions The try-catch statement If a method does not handle an exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. public void deposit(double amount) throws IOException, … { // Method implementation throw new IOException(); } 209 Lecture 8 (Cont.) Exceptions The try-catch statement The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. if try block throws an exception, the catch block will handle the exception and finally block will be executed. if try block doesn't throw an exception, the catch block will not executed and finally block will be executed. finally block will not be executed if the machine shut down, System.exit () is invoked, or the power turned off. if try block has a return statement, finally block will be executed before the return. 210 Lecture 8 (Cont.) Exceptions The try-catch statement In other words, when try is executed, finally is executed. int sum=0; for(String i: a) { try {sum+=Integer.parseInt(i);} catch(NumberFormatException e) { System.err.println(e.getMessage() ); }// e.printStackTrace() finally{ System.out.println("the sum= "+ sum);}} In the above example, try inside a for loop, so if try executed 4 times, finally executed 4 times. 211 Lecture 8 (Cont.) Exceptions The try-catch statement In otherwords, when try is executed, finally is executed. int sum=0; for(String i: a) { try {sum+=Integer.parseInt(i); return;} catch(NumberFormatException e) { System.err.println(e.getMessage() ); }// e.printStackTrace() finally{ System.out.println("the sum= "+ sum);}} 212 Lecture 8 (Cont.) Exceptions The try-catch statement Note the following: A catch clause cannot exist without a try statement. It is not necessary to have finally clauses when ever a try/catch block is present. The try block cannot be present without either catch clause or finally clause. 213 Lecture 9 Collections A collection is a single object managing a group ob objects. The objects in the collection are called elements which are of type Objects. The Collections API contains interfaces . Some of them are as follows: 1. Collection: a group of objects knows as elements. Implementations (classes) determine whether there is ordering and whether duplicates are permitted. 2. Set: an unordered collection; no duplicates are permitted. 3. Lists: an ordered collection; duplicates are permitted. 214 Lecture 9 (Cont.) Collections A collection is a single object managing a group ob objects. 215 Lecture 9 (Cont.) Collections A Set Example An ArrayList Example 216 Lecture 9 (Cont.) I/O Fundamental A stream is a flow of data from a source to a sink. Sources and sinks are also called input streams and output streams. We read from an input stream, but can’t write to it. We write to an output stream, but can’t read from it. There are two stream classes : Byte Stream and Character Stream. In Byte Stream, each character is represented by ASCII code in 8 bits, however in Character Stream, each character is represented by Unicode in 16 bits. Byte Stream is implemented by: InputStream (abstract class) (source) and OutputStream (abstract class)(sink). Character Stream is implemented by: Reader (abstract class)(source) and Writer (abstract class)(sink). 217 Lecture 9 (Cont.) I/O Fundamental The InputStream class provide three methods: int read(): read one character each time. int read(byte [] buffer): read from the file until the is full or end of file. int read(byte [] buffer, int offset, int length). The first method returns an int, which contains either a byte read from the stream, or -1, which indicates the end of file condition. The other two methods read the stream into a byte array and return the number of bytes read. The two int args in the third method indicate a sub range in the target array that needs to be filled. void close(): when you finished, close the stream. int available(): returns the number of bytes that are available to be read from the stream. 218 Lecture 9 (Cont.) I/O Fundamental The OutputStream class provide three methods: void write(int): write one character each time. void write(byte [] buffer): read from the file until the is full or end of file. void write (byte [] buffer, int offset, int length). void close(): when you finished, close the stream. 219 Lecture 9 (Cont.) I/O Fundamental The Reader class provide three methods: int read(): read one character each time (unicode char). int read(byte [] buffer): read from the file until the array is full or end of file. int read(byte [] buffer, int offset, int length). The first method returns an int, which contains either a unicode character read from the stream, or -1, which indicates the end of file condition. The other two methods read the stream into a byte array and return the number of bytes read. The two int args in the third method indicate a sub range in the target array that needs to be filled. void close(): when you finished, close the stream. int available(): returns the number of bytes that are available to be read from the stream. 220 Lecture 9 (Cont.) I/O Fundamental The Writer class provide three methods: void write(int): write one character each time. void write(char [] buffer): read from the file until the is full or end of file. void write (char [] buffer, int offset, int length). void write (String s). void write (String [] s, int offset, int length). void close(): when you finished, close the stream. 221 Lecture 9 (Cont.) I/O Fundamental The FileInputStream class implements the InputStream class. The FileReader class implements the Reader class. The FileOutputStream class implements the OutputStream class. The FileWriter class implements the Writer class. 222 Lecture 9 (Cont.) I/O Fundamental import java. io.*; public class TestStream{ public static void main(String []s) { try{ FileReader input=new FileReader (“file1”)// IOException try{FileWriter output=new FileWriter (“file2”) try{ char [] buf= new char [128]; int charsRead; charsRead=input.read(buf)// read from file1 to fill buf with 128 chars. // or reach end of file (-1) while(charsRead!=-1) {output.write(buf,0, charsRead)// append the // full array to file2 charsRead=input.read(buf);}}// read the next 128 char from file1to fill //buf . 223 Lecture 9 (Cont.) I/O Fundamental finally {output.close();} finally {input.close();} }catch(IOException) { e,printStackTrace();} }} 224