Object-oriented Programming in Java Object-oriented Programming in Java Object-oriented Programming in Java Learner’s Guide © 2013 Aptech Limited All rights reserved. No part of this book may be reproduced or copied in any form or by any means – graphic, electronic or mechanical, including photocopying, recording, taping, or storing in information retrieval system or sent or transferred without the prior written permission of copyright owner Aptech Limited. All trademarks acknowledged. APTECH LIMITED E-mail: ov-support@onlinevarsity.com First Edition - 2013 Dear Learner, We congratulate you on your decision to pursue an Aptech course. designs its courses using a sound instructional design model – from conceptualization to execution, incorporating the following key aspects: Scanning the user system and needs assessment Needs assessment is carried out to find the educational and training needs of the learner Technology trends are regularly scanned and tracked by core teams at Aptech Ltd. TAG* analyzes these on a monthly basis to understand the emerging technology training needs for the Industry. An annual Industry Recruitment Profile Survey# is conducted during August - October to understand the technologies that Industries would be adapting in the next 2 to 3 years. An analysis of these trends & recruitment needs is then carried out to understand the skill requirements for different roles & career opportunities. The skill requirements are then mapped with the learner profile (user system) to derive the Learning objectives for the different roles. Needs analysis and design of curriculum The Learning objectives are then analyzed and translated into learning tasks. Each learning task or activity is analyzed in terms of knowledge, skills and attitudes that are required to perform that task. Teachers and domain experts do this jointly. These are then grouped in clusters to form the subjects to be covered by the curriculum. In addition, the society, the teachers, and the industry expect certain knowledge and skills that are related to abilities such as learning-to-learn, thinking, adaptability, problem solving, positive attitude etc. These competencies would cover both cognitive and affective domains. A precedence diagram for the subjects is drawn where the prerequisites for each subject are graphically illustrated. The number of levels in this diagram is determined by the duration of the course in terms of number of semesters etc. Using the precedence diagram and the time duration for each subject, the curriculum is organized. Design & development of instructional materials The content outlines are developed by including additional topics that are required for the completion of the domain and for the logical development of the competencies identified. Evaluation strategy and scheme is developed for the subject. The topics are arranged/organized in a meaningful sequence. The detailed instructional material – Training aids, Learner material, reference material, project guidelines, etc.- are then developed. Rigorous quality checks are conducted at every stage. Strategies for delivery of instruction Careful consideration is given for the integral development of abilities like thinking, problem solving, learning-to-learn etc. by selecting appropriate instructional strategies (training methodology), instructional activities and instructional materials. The area of IT is fast changing and nebulous. Hence considerable flexibility is provided in the instructional process by specially including creative activities with group interaction between the students and the trainer. The positive aspects of web based learning –acquiring information, organizing information and acting on the basis of insufficient information are some of the aspects, which are incorporated, in the instructional process. Assessment of learning The learning is assessed through different modes – tests, assignments & projects. The assessment system is designed to evaluate the level of knowledge & skills as defined by the learning objectives. Evaluation of instructional process and instructional materials The instructional process is backed by an elaborate monitoring system to evaluate - on-time delivery, understanding of a subject module, ability of the instructor to impart learning. As an integral part of this process, we request you to kindly send us your feedback in the reply pre- paid form appended at the end of each module. *TAG – Technology & Academics Group comprises members from Aptech Ltd., professors from reputed Academic Institutions, Senior Managers from Industry, Technical gurus from Software Majors & representatives from regulatory organizations/forums. Technology heads of Aptech Ltd. meet on a monthly basis to share and evaluate the technology trends. The group interfaces with the representatives of the TAG thrice a year to review and validate the technology and academic directions and endeavors of Aptech Ltd. Aptech New Products Design Model Key Aspects 1 Evaluation of Scanning the user Instructional system and needs Processes and assessment Material 2 6 Need Analysis Assessment of and design of learning curriculum 3 Design and 5 Strategies for development of delivery of instructional instructions material 4 assessment : sự đánh giá curriculum : giảng dạy familiarize(s,one) with : làm quen với aim to : nhằm mục đích enable : cho phép, cung cấp intend to : có ý định Preface The book, Object-oriented Programming in Java, aims to enable the students to use the advanced object- oriented features of Java. This book intends to familiarize the reader with the latest version of Java, that is, Java SE 7. Java SE 7 introduces several new features as well as provides enhancements on the earlier versions. The book begins with the creation of user-defined exceptions and assertions in Java. It explains the java.lang package classes and explains storing of objects in different type of collections. The book proceeds with the explanation of the basic concept of multithread programming and its relevance in Java in terms of threads. The book also explains the concepts of collections, regular expressions and covers various Application Programming Interfaces (APIs) in Java programming language. These include File Input/Output, Concurrency, Generics, and so on. The book provides the explanation of Java Database Connectivity (JDBC) API 4.1 and its interfaces to develop Java applications that interact with database objects to persist data in them. The book also discusses on the various design patterns and internationalization features that are supported in Java. This book is the result of a concentrated effort of the Design Team, which is continuously striving to bring you the best and the latest in Information Technology. The process of design has been a part of the ISO 9001 certification for Aptech-IT Division, Education Support Services. As part of Aptech’s quality drive, this team does intensive research and curriculum enrichment to keep it in line with industry trends. We will be glad to receive your suggestions. Design Team “ “ Nothing is a waste of time if you use the experience wisely Table of Contents Sessions 1. Exceptions and Assertions 2.lang Package Quan Trọng 3. Collections API Quan trọng 4. Generics Quan trọng 5. File Handling in Java 6. New Features in File Handling 7. Introduction to Threads Quang trọng 8. Multithreading and Concurrency quang trọng 9. Advanced JDBC Features 11. Design Patterns Quan trọng 12. Internationalization and Localization Session 1 Exceptions and Assertions Welcome to the Session, Exceptions and Assertions. This session explains the creation and use of exceptions in Java. It deals with creation of user-defined exceptions and throwing exceptions from methods. Further, this session explains the concept and use of Assertions. Lastly, the session explains the different types of assertions and its limitations. In this Session, you will learn to: Describe exception Explain the use of try-catch-finally blocks Explain throwing and handling exceptions Explain handling multiple exceptions in a single catch block Explain the use of try-with-resources Describe creation and use of custom exceptions Explain assertions and its types 1 even though : mặc dù Session ability to handle : khả năng xử lý Exceptions and Assertions unexpected events : các sự kiện không trông mong xảy ra 1.1 Introduction Java programming language provides the ability to handle unexpected events in the program. This is because, even though a code is well written, it is prone to behave erroneously. With the help of exception handling, the developer can ensure that the user gets a proper message in case some error occurs in the program. It also helps to ensure that in case of an error, the data and processes that the program is using do not get affected adversely. erroneously: sự sai lầm affected adversely : bị ảnh hưởng 1 cách bất lơi proper : thích hơp, đúng = right, correct 1.2 Overview of Exceptions An exception is an event occurring during program execution that leads to disruption of the normal flow of the program’s instructions. Exception handling in Java is a way for ensuring smooth execution of a program. To handle the exceptions, Java provides the try-catch-finally blocks. Using these blocks, the developer can check the program statements for errors and handle them in case they occur. An exception : 1 ngoại lệ in order to = so as to : để mà(làm gì đó) 1.1 try-catch-finally Block In order to handle exceptions, the developer needs to identify the statements that may lead to exceptions and enclose them within a try block. Next, exception handlers need to be associated with a try block by providing one or more catch blocks directly after the try block. The syntax of a try-catch block is as follows: enclose : đính kèm need to be associated : cần identify : xác nhận đc liên kiết Syntax: try { . } catch (ExceptionType name) { } catch (ExceptionType name) { } particular: riêng, cụ thể, đặc biệt . Each catch block acts as an exception handler that handles a particular type of exception. The parameter, ExceptionType, indicates the type of exception that the handler can handle. This parameter must be the name of a class inheriting from the Throwable class. The code within the catch block is executed if and when the exception handler is invoked. The first catch block in the call stack whose exception type matches the type of the exception thrown is invoked by the runtime system to handle the exception.0 © Aptech Limited 1 Session Exceptions and Assertions Code Snippet 1 shows an example of try-catch block. Code Snippet 1: public class Calculator{ int result; public void divide(int num1, int num2){ try{ result = num1/num2; //line 1 -- statement that might raise exception }catch(ArithmeticException ex){ // printing the error message System.println(“Denominator cannot be set to zero!!!” + ex.getMessage()); } } raise : (verd) đưa ra, đề ra , đề khởi ra cái gì đó to inform : để báo cho ai biết } In the code, line 1 might raise an exception when the value of num2 is set to 0. Therefore, a catch block is provided to handle the exception. The class that will handle the exception is ArithmeticException. When the exception occurs, it will be raised in the try block and handled by the catch block. The statement within the catch block will be executed to inform the user of the error. The statement provides a user-friendly message along with a built-in error message using the getMessage() method. tin nhắn thân thiện người dùng 1 tin nhắn lỗi đc dựng sẵn The finally block is executed even if an exception occurs in the try block. It helps the programmer to ensure that the cleanup code does not get accidentally bypassed by a break, continue, or return statement in the try block. It is advisable to write the cleanup code in a finally block, even when no exceptions are expected. even if : nếu như Some conditions in which the finally block may not execute are as follows: When the Java Virtual Machine (JVM) exits while the try or catch code is being executed. If the thread executing the try or catch code is interrupted or killed. interrupted: bị gián đoạn In these cases, the finally block may not execute even though the application as a whole continue execution.0 © Aptech Limited 1 Session Exceptions and Assertions Code Snippet 2 explains the use of the finally block.